babylon.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583
  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. if (other.x < this.x)
  3201. this.x = other.x;
  3202. if (other.y < this.y)
  3203. this.y = other.y;
  3204. if (other.z < this.z)
  3205. this.z = other.z;
  3206. return this;
  3207. };
  3208. /**
  3209. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3210. * @param other defines the second operand
  3211. * @returns the current updated Vector3
  3212. */
  3213. Vector3.prototype.maximizeInPlace = function (other) {
  3214. if (other.x > this.x)
  3215. this.x = other.x;
  3216. if (other.y > this.y)
  3217. this.y = other.y;
  3218. if (other.z > this.z)
  3219. this.z = other.z;
  3220. return this;
  3221. };
  3222. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3223. /**
  3224. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3225. */
  3226. get: function () {
  3227. var absX = Math.abs(this.x);
  3228. var absY = Math.abs(this.y);
  3229. if (absX !== absY) {
  3230. return true;
  3231. }
  3232. var absZ = Math.abs(this.z);
  3233. if (absX !== absZ) {
  3234. return true;
  3235. }
  3236. if (absY !== absZ) {
  3237. return true;
  3238. }
  3239. return false;
  3240. },
  3241. enumerable: true,
  3242. configurable: true
  3243. });
  3244. /**
  3245. * Gets a new Vector3 from current Vector3 floored values
  3246. * @returns a new Vector3
  3247. */
  3248. Vector3.prototype.floor = function () {
  3249. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3250. };
  3251. /**
  3252. * Gets a new Vector3 from current Vector3 floored values
  3253. * @returns a new Vector3
  3254. */
  3255. Vector3.prototype.fract = function () {
  3256. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3257. };
  3258. // Properties
  3259. /**
  3260. * Gets the length of the Vector3
  3261. * @returns the length of the Vecto3
  3262. */
  3263. Vector3.prototype.length = function () {
  3264. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3265. };
  3266. /**
  3267. * Gets the squared length of the Vector3
  3268. * @returns squared length of the Vector3
  3269. */
  3270. Vector3.prototype.lengthSquared = function () {
  3271. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3272. };
  3273. /**
  3274. * Normalize the current Vector3.
  3275. * Please note that this is an in place operation.
  3276. * @returns the current updated Vector3
  3277. */
  3278. Vector3.prototype.normalize = function () {
  3279. var len = this.length();
  3280. if (len === 0 || len === 1.0)
  3281. return this;
  3282. var num = 1.0 / len;
  3283. this.x *= num;
  3284. this.y *= num;
  3285. this.z *= num;
  3286. return this;
  3287. };
  3288. /**
  3289. * Normalize the current Vector3 to a new vector
  3290. * @returns the new Vector3
  3291. */
  3292. Vector3.prototype.normalizeToNew = function () {
  3293. var normalized = new Vector3(0, 0, 0);
  3294. this.normalizeToRef(normalized);
  3295. return normalized;
  3296. };
  3297. /**
  3298. * Normalize the current Vector3 to the reference
  3299. * @param reference define the Vector3 to update
  3300. * @returns the updated Vector3
  3301. */
  3302. Vector3.prototype.normalizeToRef = function (reference) {
  3303. var len = this.length();
  3304. if (len === 0 || len === 1.0) {
  3305. reference.set(this.x, this.y, this.z);
  3306. return reference;
  3307. }
  3308. var scale = 1.0 / len;
  3309. this.scaleToRef(scale, reference);
  3310. return reference;
  3311. };
  3312. /**
  3313. * Creates a new Vector3 copied from the current Vector3
  3314. * @returns the new Vector3
  3315. */
  3316. Vector3.prototype.clone = function () {
  3317. return new Vector3(this.x, this.y, this.z);
  3318. };
  3319. /**
  3320. * Copies the given vector coordinates to the current Vector3 ones
  3321. * @param source defines the source Vector3
  3322. * @returns the current updated Vector3
  3323. */
  3324. Vector3.prototype.copyFrom = function (source) {
  3325. this.x = source.x;
  3326. this.y = source.y;
  3327. this.z = source.z;
  3328. return this;
  3329. };
  3330. /**
  3331. * Copies the given floats to the current Vector3 coordinates
  3332. * @param x defines the x coordinate of the operand
  3333. * @param y defines the y coordinate of the operand
  3334. * @param z defines the z coordinate of the operand
  3335. * @returns the current updated Vector3
  3336. */
  3337. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3338. this.x = x;
  3339. this.y = y;
  3340. this.z = z;
  3341. return this;
  3342. };
  3343. /**
  3344. * Copies the given floats to the current Vector3 coordinates
  3345. * @param x defines the x coordinate of the operand
  3346. * @param y defines the y coordinate of the operand
  3347. * @param z defines the z coordinate of the operand
  3348. * @returns the current updated Vector3
  3349. */
  3350. Vector3.prototype.set = function (x, y, z) {
  3351. return this.copyFromFloats(x, y, z);
  3352. };
  3353. // Statics
  3354. /**
  3355. * Get the clip factor between two vectors
  3356. * @param vector0 defines the first operand
  3357. * @param vector1 defines the second operand
  3358. * @param axis defines the axis to use
  3359. * @param size defines the size along the axis
  3360. * @returns the clip factor
  3361. */
  3362. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3363. var d0 = Vector3.Dot(vector0, axis) - size;
  3364. var d1 = Vector3.Dot(vector1, axis) - size;
  3365. var s = d0 / (d0 - d1);
  3366. return s;
  3367. };
  3368. /**
  3369. * Get angle between two vectors
  3370. * @param vector0 angle between vector0 and vector1
  3371. * @param vector1 angle between vector0 and vector1
  3372. * @param normal direction of the normal
  3373. * @return the angle between vector0 and vector1
  3374. */
  3375. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3376. var v0 = vector0.clone().normalize();
  3377. var v1 = vector1.clone().normalize();
  3378. var dot = Vector3.Dot(v0, v1);
  3379. var n = Vector3.Cross(v0, v1);
  3380. if (Vector3.Dot(n, normal) > 0) {
  3381. return Math.acos(dot);
  3382. }
  3383. return -Math.acos(dot);
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set from the index "offset" of the given array
  3387. * @param array defines the source array
  3388. * @param offset defines the offset in the source array
  3389. * @returns the new Vector3
  3390. */
  3391. Vector3.FromArray = function (array, offset) {
  3392. if (!offset) {
  3393. offset = 0;
  3394. }
  3395. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3396. };
  3397. /**
  3398. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3399. * This function is deprecated. Use FromArray instead
  3400. * @param array defines the source array
  3401. * @param offset defines the offset in the source array
  3402. * @returns the new Vector3
  3403. */
  3404. Vector3.FromFloatArray = function (array, offset) {
  3405. return Vector3.FromArray(array, offset);
  3406. };
  3407. /**
  3408. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3409. * @param array defines the source array
  3410. * @param offset defines the offset in the source array
  3411. * @param result defines the Vector3 where to store the result
  3412. */
  3413. Vector3.FromArrayToRef = function (array, offset, result) {
  3414. result.x = array[offset];
  3415. result.y = array[offset + 1];
  3416. result.z = array[offset + 2];
  3417. };
  3418. /**
  3419. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3420. * This function is deprecated. Use FromArrayToRef instead.
  3421. * @param array defines the source array
  3422. * @param offset defines the offset in the source array
  3423. * @param result defines the Vector3 where to store the result
  3424. */
  3425. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3426. return Vector3.FromArrayToRef(array, offset, result);
  3427. };
  3428. /**
  3429. * Sets the given vector "result" with the given floats.
  3430. * @param x defines the x coordinate of the source
  3431. * @param y defines the y coordinate of the source
  3432. * @param z defines the z coordinate of the source
  3433. * @param result defines the Vector3 where to store the result
  3434. */
  3435. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3436. result.x = x;
  3437. result.y = y;
  3438. result.z = z;
  3439. };
  3440. /**
  3441. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3442. * @returns a new empty Vector3
  3443. */
  3444. Vector3.Zero = function () {
  3445. return new Vector3(0.0, 0.0, 0.0);
  3446. };
  3447. /**
  3448. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3449. * @returns a new unit Vector3
  3450. */
  3451. Vector3.One = function () {
  3452. return new Vector3(1.0, 1.0, 1.0);
  3453. };
  3454. /**
  3455. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3456. * @returns a new up Vector3
  3457. */
  3458. Vector3.Up = function () {
  3459. return new Vector3(0.0, 1.0, 0.0);
  3460. };
  3461. /**
  3462. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3463. * @returns a new down Vector3
  3464. */
  3465. Vector3.Down = function () {
  3466. return new Vector3(0.0, -1.0, 0.0);
  3467. };
  3468. /**
  3469. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3470. * @returns a new forward Vector3
  3471. */
  3472. Vector3.Forward = function () {
  3473. return new Vector3(0.0, 0.0, 1.0);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3477. * @returns a new forward Vector3
  3478. */
  3479. Vector3.Backward = function () {
  3480. return new Vector3(0.0, 0.0, -1.0);
  3481. };
  3482. /**
  3483. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3484. * @returns a new right Vector3
  3485. */
  3486. Vector3.Right = function () {
  3487. return new Vector3(1.0, 0.0, 0.0);
  3488. };
  3489. /**
  3490. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3491. * @returns a new left Vector3
  3492. */
  3493. Vector3.Left = function () {
  3494. return new Vector3(-1.0, 0.0, 0.0);
  3495. };
  3496. /**
  3497. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3498. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3499. * @param vector defines the Vector3 to transform
  3500. * @param transformation defines the transformation matrix
  3501. * @returns the transformed Vector3
  3502. */
  3503. Vector3.TransformCoordinates = function (vector, transformation) {
  3504. var result = Vector3.Zero();
  3505. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3506. return result;
  3507. };
  3508. /**
  3509. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3510. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3511. * @param vector defines the Vector3 to transform
  3512. * @param transformation defines the transformation matrix
  3513. * @param result defines the Vector3 where to store the result
  3514. */
  3515. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3516. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3517. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3518. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3519. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3520. result.x = x / w;
  3521. result.y = y / w;
  3522. result.z = z / w;
  3523. };
  3524. /**
  3525. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3526. * This method computes tranformed coordinates only, not transformed direction vectors
  3527. * @param x define the x coordinate of the source vector
  3528. * @param y define the y coordinate of the source vector
  3529. * @param z define the z coordinate of the source vector
  3530. * @param transformation defines the transformation matrix
  3531. * @param result defines the Vector3 where to store the result
  3532. */
  3533. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3534. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3535. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3536. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3537. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3538. result.x = rx / rw;
  3539. result.y = ry / rw;
  3540. result.z = rz / rw;
  3541. };
  3542. /**
  3543. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3544. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3545. * @param vector defines the Vector3 to transform
  3546. * @param transformation defines the transformation matrix
  3547. * @returns the new Vector3
  3548. */
  3549. Vector3.TransformNormal = function (vector, transformation) {
  3550. var result = Vector3.Zero();
  3551. Vector3.TransformNormalToRef(vector, transformation, result);
  3552. return result;
  3553. };
  3554. /**
  3555. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3556. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3557. * @param vector defines the Vector3 to transform
  3558. * @param transformation defines the transformation matrix
  3559. * @param result defines the Vector3 where to store the result
  3560. */
  3561. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3562. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3563. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3564. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3565. result.x = x;
  3566. result.y = y;
  3567. result.z = z;
  3568. };
  3569. /**
  3570. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3571. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3572. * @param x define the x coordinate of the source vector
  3573. * @param y define the y coordinate of the source vector
  3574. * @param z define the z coordinate of the source vector
  3575. * @param transformation defines the transformation matrix
  3576. * @param result defines the Vector3 where to store the result
  3577. */
  3578. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3579. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3580. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3581. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3582. };
  3583. /**
  3584. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3585. * @param value1 defines the first control point
  3586. * @param value2 defines the second control point
  3587. * @param value3 defines the third control point
  3588. * @param value4 defines the fourth control point
  3589. * @param amount defines the amount on the spline to use
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3593. var squared = amount * amount;
  3594. var cubed = amount * squared;
  3595. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3596. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3597. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3598. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3599. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3600. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3601. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3602. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3603. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3604. return new Vector3(x, y, z);
  3605. };
  3606. /**
  3607. * 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"
  3608. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3609. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3610. * @param value defines the current value
  3611. * @param min defines the lower range value
  3612. * @param max defines the upper range value
  3613. * @returns the new Vector3
  3614. */
  3615. Vector3.Clamp = function (value, min, max) {
  3616. var x = value.x;
  3617. x = (x > max.x) ? max.x : x;
  3618. x = (x < min.x) ? min.x : x;
  3619. var y = value.y;
  3620. y = (y > max.y) ? max.y : y;
  3621. y = (y < min.y) ? min.y : y;
  3622. var z = value.z;
  3623. z = (z > max.z) ? max.z : z;
  3624. z = (z < min.z) ? min.z : z;
  3625. return new Vector3(x, y, z);
  3626. };
  3627. /**
  3628. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3629. * @param value1 defines the first control point
  3630. * @param tangent1 defines the first tangent vector
  3631. * @param value2 defines the second control point
  3632. * @param tangent2 defines the second tangent vector
  3633. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3634. * @returns the new Vector3
  3635. */
  3636. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3637. var squared = amount * amount;
  3638. var cubed = amount * squared;
  3639. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3640. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3641. var part3 = (cubed - (2.0 * squared)) + amount;
  3642. var part4 = cubed - squared;
  3643. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3644. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3645. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3646. return new Vector3(x, y, z);
  3647. };
  3648. /**
  3649. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3650. * @param start defines the start value
  3651. * @param end defines the end value
  3652. * @param amount max defines amount between both (between 0 and 1)
  3653. * @returns the new Vector3
  3654. */
  3655. Vector3.Lerp = function (start, end, amount) {
  3656. var result = new Vector3(0, 0, 0);
  3657. Vector3.LerpToRef(start, end, amount, result);
  3658. return result;
  3659. };
  3660. /**
  3661. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3662. * @param start defines the start value
  3663. * @param end defines the end value
  3664. * @param amount max defines amount between both (between 0 and 1)
  3665. * @param result defines the Vector3 where to store the result
  3666. */
  3667. Vector3.LerpToRef = function (start, end, amount, result) {
  3668. result.x = start.x + ((end.x - start.x) * amount);
  3669. result.y = start.y + ((end.y - start.y) * amount);
  3670. result.z = start.z + ((end.z - start.z) * amount);
  3671. };
  3672. /**
  3673. * Returns the dot product (float) between the vectors "left" and "right"
  3674. * @param left defines the left operand
  3675. * @param right defines the right operand
  3676. * @returns the dot product
  3677. */
  3678. Vector3.Dot = function (left, right) {
  3679. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3680. };
  3681. /**
  3682. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3683. * The cross product is then orthogonal to both "left" and "right"
  3684. * @param left defines the left operand
  3685. * @param right defines the right operand
  3686. * @returns the cross product
  3687. */
  3688. Vector3.Cross = function (left, right) {
  3689. var result = Vector3.Zero();
  3690. Vector3.CrossToRef(left, right, result);
  3691. return result;
  3692. };
  3693. /**
  3694. * Sets the given vector "result" with the cross product of "left" and "right"
  3695. * The cross product is then orthogonal to both "left" and "right"
  3696. * @param left defines the left operand
  3697. * @param right defines the right operand
  3698. * @param result defines the Vector3 where to store the result
  3699. */
  3700. Vector3.CrossToRef = function (left, right, result) {
  3701. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3702. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3703. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3704. result.copyFrom(MathTmp.Vector3[0]);
  3705. };
  3706. /**
  3707. * Returns a new Vector3 as the normalization of the given vector
  3708. * @param vector defines the Vector3 to normalize
  3709. * @returns the new Vector3
  3710. */
  3711. Vector3.Normalize = function (vector) {
  3712. var result = Vector3.Zero();
  3713. Vector3.NormalizeToRef(vector, result);
  3714. return result;
  3715. };
  3716. /**
  3717. * Sets the given vector "result" with the normalization of the given first vector
  3718. * @param vector defines the Vector3 to normalize
  3719. * @param result defines the Vector3 where to store the result
  3720. */
  3721. Vector3.NormalizeToRef = function (vector, result) {
  3722. result.copyFrom(vector);
  3723. result.normalize();
  3724. };
  3725. /**
  3726. * Project a Vector3 onto screen space
  3727. * @param vector defines the Vector3 to project
  3728. * @param world defines the world matrix to use
  3729. * @param transform defines the transform (view x projection) matrix to use
  3730. * @param viewport defines the screen viewport to use
  3731. * @returns the new Vector3
  3732. */
  3733. Vector3.Project = function (vector, world, transform, viewport) {
  3734. var cw = viewport.width;
  3735. var ch = viewport.height;
  3736. var cx = viewport.x;
  3737. var cy = viewport.y;
  3738. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3739. 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);
  3740. var matrix = MathTmp.Matrix[0];
  3741. world.multiplyToRef(transform, matrix);
  3742. matrix.multiplyToRef(viewportMatrix, matrix);
  3743. return Vector3.TransformCoordinates(vector, matrix);
  3744. };
  3745. /**
  3746. * Unproject from screen space to object space
  3747. * @param source defines the screen space Vector3 to use
  3748. * @param viewportWidth defines the current width of the viewport
  3749. * @param viewportHeight defines the current height of the viewport
  3750. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3751. * @param transform defines the transform (view x projection) matrix to use
  3752. * @returns the new Vector3
  3753. */
  3754. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3755. var matrix = MathTmp.Matrix[0];
  3756. world.multiplyToRef(transform, matrix);
  3757. matrix.invert();
  3758. source.x = source.x / viewportWidth * 2 - 1;
  3759. source.y = -(source.y / viewportHeight * 2 - 1);
  3760. var vector = Vector3.TransformCoordinates(source, matrix);
  3761. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3762. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3763. vector = vector.scale(1.0 / num);
  3764. }
  3765. return vector;
  3766. };
  3767. /**
  3768. * Unproject from screen space to object space
  3769. * @param source defines the screen space Vector3 to use
  3770. * @param viewportWidth defines the current width of the viewport
  3771. * @param viewportHeight defines the current height of the viewport
  3772. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3773. * @param view defines the view matrix to use
  3774. * @param projection defines the projection matrix to use
  3775. * @returns the new Vector3
  3776. */
  3777. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3778. var result = Vector3.Zero();
  3779. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3780. return result;
  3781. };
  3782. /**
  3783. * Unproject from screen space to object space
  3784. * @param source defines the screen space Vector3 to use
  3785. * @param viewportWidth defines the current width of the viewport
  3786. * @param viewportHeight defines the current height of the viewport
  3787. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3788. * @param view defines the view matrix to use
  3789. * @param projection defines the projection matrix to use
  3790. * @param result defines the Vector3 where to store the result
  3791. */
  3792. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3793. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3794. };
  3795. /**
  3796. * Unproject from screen space to object space
  3797. * @param sourceX defines the screen space x coordinate to use
  3798. * @param sourceY defines the screen space y coordinate to use
  3799. * @param sourceZ defines the screen space z coordinate to use
  3800. * @param viewportWidth defines the current width of the viewport
  3801. * @param viewportHeight defines the current height of the viewport
  3802. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3803. * @param view defines the view matrix to use
  3804. * @param projection defines the projection matrix to use
  3805. * @param result defines the Vector3 where to store the result
  3806. */
  3807. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3808. var matrix = MathTmp.Matrix[0];
  3809. world.multiplyToRef(view, matrix);
  3810. matrix.multiplyToRef(projection, matrix);
  3811. matrix.invert();
  3812. var screenSource = MathTmp.Vector3[0];
  3813. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3814. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3815. screenSource.z = 2 * sourceZ - 1.0;
  3816. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3817. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3818. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3819. result.scaleInPlace(1.0 / num);
  3820. }
  3821. };
  3822. /**
  3823. * Gets the minimal coordinate values between two Vector3
  3824. * @param left defines the first operand
  3825. * @param right defines the second operand
  3826. * @returns the new Vector3
  3827. */
  3828. Vector3.Minimize = function (left, right) {
  3829. var min = left.clone();
  3830. min.minimizeInPlace(right);
  3831. return min;
  3832. };
  3833. /**
  3834. * Gets the maximal coordinate values between two Vector3
  3835. * @param left defines the first operand
  3836. * @param right defines the second operand
  3837. * @returns the new Vector3
  3838. */
  3839. Vector3.Maximize = function (left, right) {
  3840. var max = left.clone();
  3841. max.maximizeInPlace(right);
  3842. return max;
  3843. };
  3844. /**
  3845. * Returns the distance between the vectors "value1" and "value2"
  3846. * @param value1 defines the first operand
  3847. * @param value2 defines the second operand
  3848. * @returns the distance
  3849. */
  3850. Vector3.Distance = function (value1, value2) {
  3851. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3852. };
  3853. /**
  3854. * Returns the squared distance between the vectors "value1" and "value2"
  3855. * @param value1 defines the first operand
  3856. * @param value2 defines the second operand
  3857. * @returns the squared distance
  3858. */
  3859. Vector3.DistanceSquared = function (value1, value2) {
  3860. var x = value1.x - value2.x;
  3861. var y = value1.y - value2.y;
  3862. var z = value1.z - value2.z;
  3863. return (x * x) + (y * y) + (z * z);
  3864. };
  3865. /**
  3866. * Returns a new Vector3 located at the center between "value1" and "value2"
  3867. * @param value1 defines the first operand
  3868. * @param value2 defines the second operand
  3869. * @returns the new Vector3
  3870. */
  3871. Vector3.Center = function (value1, value2) {
  3872. var center = value1.add(value2);
  3873. center.scaleInPlace(0.5);
  3874. return center;
  3875. };
  3876. /**
  3877. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3878. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3879. * to something in order to rotate it from its local system to the given target system
  3880. * Note: axis1, axis2 and axis3 are normalized during this operation
  3881. * @param axis1 defines the first axis
  3882. * @param axis2 defines the second axis
  3883. * @param axis3 defines the third axis
  3884. * @returns a new Vector3
  3885. */
  3886. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3887. var rotation = Vector3.Zero();
  3888. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3889. return rotation;
  3890. };
  3891. /**
  3892. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3893. * @param axis1 defines the first axis
  3894. * @param axis2 defines the second axis
  3895. * @param axis3 defines the third axis
  3896. * @param ref defines the Vector3 where to store the result
  3897. */
  3898. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3899. var quat = MathTmp.Quaternion[0];
  3900. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3901. quat.toEulerAnglesToRef(ref);
  3902. };
  3903. return Vector3;
  3904. }());
  3905. BABYLON.Vector3 = Vector3;
  3906. //Vector4 class created for EulerAngle class conversion to Quaternion
  3907. var Vector4 = /** @class */ (function () {
  3908. /**
  3909. * Creates a Vector4 object from the given floats.
  3910. */
  3911. function Vector4(x, y, z, w) {
  3912. this.x = x;
  3913. this.y = y;
  3914. this.z = z;
  3915. this.w = w;
  3916. }
  3917. /**
  3918. * Returns the string with the Vector4 coordinates.
  3919. */
  3920. Vector4.prototype.toString = function () {
  3921. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3922. };
  3923. /**
  3924. * Returns the string "Vector4".
  3925. */
  3926. Vector4.prototype.getClassName = function () {
  3927. return "Vector4";
  3928. };
  3929. /**
  3930. * Returns the Vector4 hash code.
  3931. */
  3932. Vector4.prototype.getHashCode = function () {
  3933. var hash = this.x || 0;
  3934. hash = (hash * 397) ^ (this.y || 0);
  3935. hash = (hash * 397) ^ (this.z || 0);
  3936. hash = (hash * 397) ^ (this.w || 0);
  3937. return hash;
  3938. };
  3939. // Operators
  3940. /**
  3941. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3942. */
  3943. Vector4.prototype.asArray = function () {
  3944. var result = new Array();
  3945. this.toArray(result, 0);
  3946. return result;
  3947. };
  3948. /**
  3949. * Populates the given array from the given index with the Vector4 coordinates.
  3950. * Returns the Vector4.
  3951. */
  3952. Vector4.prototype.toArray = function (array, index) {
  3953. if (index === undefined) {
  3954. index = 0;
  3955. }
  3956. array[index] = this.x;
  3957. array[index + 1] = this.y;
  3958. array[index + 2] = this.z;
  3959. array[index + 3] = this.w;
  3960. return this;
  3961. };
  3962. /**
  3963. * Adds the given vector to the current Vector4.
  3964. * Returns the updated Vector4.
  3965. */
  3966. Vector4.prototype.addInPlace = function (otherVector) {
  3967. this.x += otherVector.x;
  3968. this.y += otherVector.y;
  3969. this.z += otherVector.z;
  3970. this.w += otherVector.w;
  3971. return this;
  3972. };
  3973. /**
  3974. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3975. */
  3976. Vector4.prototype.add = function (otherVector) {
  3977. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3978. };
  3979. /**
  3980. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3981. * Returns the current Vector4.
  3982. */
  3983. Vector4.prototype.addToRef = function (otherVector, result) {
  3984. result.x = this.x + otherVector.x;
  3985. result.y = this.y + otherVector.y;
  3986. result.z = this.z + otherVector.z;
  3987. result.w = this.w + otherVector.w;
  3988. return this;
  3989. };
  3990. /**
  3991. * Subtract in place the given vector from the current Vector4.
  3992. * Returns the updated Vector4.
  3993. */
  3994. Vector4.prototype.subtractInPlace = function (otherVector) {
  3995. this.x -= otherVector.x;
  3996. this.y -= otherVector.y;
  3997. this.z -= otherVector.z;
  3998. this.w -= otherVector.w;
  3999. return this;
  4000. };
  4001. /**
  4002. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4003. */
  4004. Vector4.prototype.subtract = function (otherVector) {
  4005. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4006. };
  4007. /**
  4008. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4009. * Returns the current Vector4.
  4010. */
  4011. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4012. result.x = this.x - otherVector.x;
  4013. result.y = this.y - otherVector.y;
  4014. result.z = this.z - otherVector.z;
  4015. result.w = this.w - otherVector.w;
  4016. return this;
  4017. };
  4018. /**
  4019. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4020. */
  4021. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4022. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4023. };
  4024. /**
  4025. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4026. * Returns the current Vector4.
  4027. */
  4028. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4029. result.x = this.x - x;
  4030. result.y = this.y - y;
  4031. result.z = this.z - z;
  4032. result.w = this.w - w;
  4033. return this;
  4034. };
  4035. /**
  4036. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4037. */
  4038. Vector4.prototype.negate = function () {
  4039. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4040. };
  4041. /**
  4042. * Multiplies the current Vector4 coordinates by scale (float).
  4043. * Returns the updated Vector4.
  4044. */
  4045. Vector4.prototype.scaleInPlace = function (scale) {
  4046. this.x *= scale;
  4047. this.y *= scale;
  4048. this.z *= scale;
  4049. this.w *= scale;
  4050. return this;
  4051. };
  4052. /**
  4053. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4054. */
  4055. Vector4.prototype.scale = function (scale) {
  4056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4057. };
  4058. /**
  4059. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4060. * Returns the current Vector4.
  4061. */
  4062. Vector4.prototype.scaleToRef = function (scale, result) {
  4063. result.x = this.x * scale;
  4064. result.y = this.y * scale;
  4065. result.z = this.z * scale;
  4066. result.w = this.w * scale;
  4067. return this;
  4068. };
  4069. /**
  4070. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4071. * @param scale defines the scale factor
  4072. * @param result defines the Vector4 object where to store the result
  4073. * @returns the unmodified current Vector4
  4074. */
  4075. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4076. result.x += this.x * scale;
  4077. result.y += this.y * scale;
  4078. result.z += this.z * scale;
  4079. result.w += this.w * scale;
  4080. return this;
  4081. };
  4082. /**
  4083. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4084. */
  4085. Vector4.prototype.equals = function (otherVector) {
  4086. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4087. };
  4088. /**
  4089. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4090. */
  4091. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4092. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4093. return otherVector
  4094. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4095. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4096. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4097. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4098. };
  4099. /**
  4100. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4101. */
  4102. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4103. return this.x === x && this.y === y && this.z === z && this.w === w;
  4104. };
  4105. /**
  4106. * Multiplies in place the current Vector4 by the given one.
  4107. * Returns the updated Vector4.
  4108. */
  4109. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4110. this.x *= otherVector.x;
  4111. this.y *= otherVector.y;
  4112. this.z *= otherVector.z;
  4113. this.w *= otherVector.w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4118. */
  4119. Vector4.prototype.multiply = function (otherVector) {
  4120. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4121. };
  4122. /**
  4123. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4124. * Returns the current Vector4.
  4125. */
  4126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4127. result.x = this.x * otherVector.x;
  4128. result.y = this.y * otherVector.y;
  4129. result.z = this.z * otherVector.z;
  4130. result.w = this.w * otherVector.w;
  4131. return this;
  4132. };
  4133. /**
  4134. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4135. */
  4136. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4137. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4138. };
  4139. /**
  4140. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4141. */
  4142. Vector4.prototype.divide = function (otherVector) {
  4143. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4144. };
  4145. /**
  4146. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4147. * Returns the current Vector4.
  4148. */
  4149. Vector4.prototype.divideToRef = function (otherVector, result) {
  4150. result.x = this.x / otherVector.x;
  4151. result.y = this.y / otherVector.y;
  4152. result.z = this.z / otherVector.z;
  4153. result.w = this.w / otherVector.w;
  4154. return this;
  4155. };
  4156. /**
  4157. * Divides the current Vector3 coordinates by the given ones.
  4158. * @returns the updated Vector3.
  4159. */
  4160. Vector4.prototype.divideInPlace = function (otherVector) {
  4161. return this.divideToRef(otherVector, this);
  4162. };
  4163. /**
  4164. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4165. * @param other defines the second operand
  4166. * @returns the current updated Vector4
  4167. */
  4168. Vector4.prototype.minimizeInPlace = function (other) {
  4169. if (other.x < this.x)
  4170. this.x = other.x;
  4171. if (other.y < this.y)
  4172. this.y = other.y;
  4173. if (other.z < this.z)
  4174. this.z = other.z;
  4175. if (other.w < this.w)
  4176. this.w = other.w;
  4177. return this;
  4178. };
  4179. /**
  4180. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4181. * @param other defines the second operand
  4182. * @returns the current updated Vector4
  4183. */
  4184. Vector4.prototype.maximizeInPlace = function (other) {
  4185. if (other.x > this.x)
  4186. this.x = other.x;
  4187. if (other.y > this.y)
  4188. this.y = other.y;
  4189. if (other.z > this.z)
  4190. this.z = other.z;
  4191. if (other.w > this.w)
  4192. this.w = other.w;
  4193. return this;
  4194. };
  4195. /**
  4196. * Gets a new Vector4 from current Vector4 floored values
  4197. * @returns a new Vector4
  4198. */
  4199. Vector4.prototype.floor = function () {
  4200. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4201. };
  4202. /**
  4203. * Gets a new Vector4 from current Vector3 floored values
  4204. * @returns a new Vector4
  4205. */
  4206. Vector4.prototype.fract = function () {
  4207. 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));
  4208. };
  4209. // Properties
  4210. /**
  4211. * Returns the Vector4 length (float).
  4212. */
  4213. Vector4.prototype.length = function () {
  4214. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4215. };
  4216. /**
  4217. * Returns the Vector4 squared length (float).
  4218. */
  4219. Vector4.prototype.lengthSquared = function () {
  4220. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4221. };
  4222. // Methods
  4223. /**
  4224. * Normalizes in place the Vector4.
  4225. * Returns the updated Vector4.
  4226. */
  4227. Vector4.prototype.normalize = function () {
  4228. var len = this.length();
  4229. if (len === 0)
  4230. return this;
  4231. var num = 1.0 / len;
  4232. this.x *= num;
  4233. this.y *= num;
  4234. this.z *= num;
  4235. this.w *= num;
  4236. return this;
  4237. };
  4238. /**
  4239. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4240. */
  4241. Vector4.prototype.toVector3 = function () {
  4242. return new Vector3(this.x, this.y, this.z);
  4243. };
  4244. /**
  4245. * Returns a new Vector4 copied from the current one.
  4246. */
  4247. Vector4.prototype.clone = function () {
  4248. return new Vector4(this.x, this.y, this.z, this.w);
  4249. };
  4250. /**
  4251. * Updates the current Vector4 with the given one coordinates.
  4252. * Returns the updated Vector4.
  4253. */
  4254. Vector4.prototype.copyFrom = function (source) {
  4255. this.x = source.x;
  4256. this.y = source.y;
  4257. this.z = source.z;
  4258. this.w = source.w;
  4259. return this;
  4260. };
  4261. /**
  4262. * Updates the current Vector4 coordinates with the given floats.
  4263. * Returns the updated Vector4.
  4264. */
  4265. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4266. this.x = x;
  4267. this.y = y;
  4268. this.z = z;
  4269. this.w = w;
  4270. return this;
  4271. };
  4272. /**
  4273. * Updates the current Vector4 coordinates with the given floats.
  4274. * Returns the updated Vector4.
  4275. */
  4276. Vector4.prototype.set = function (x, y, z, w) {
  4277. return this.copyFromFloats(x, y, z, w);
  4278. };
  4279. // Statics
  4280. /**
  4281. * Returns a new Vector4 set from the starting index of the given array.
  4282. */
  4283. Vector4.FromArray = function (array, offset) {
  4284. if (!offset) {
  4285. offset = 0;
  4286. }
  4287. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4288. };
  4289. /**
  4290. * Updates the given vector "result" from the starting index of the given array.
  4291. */
  4292. Vector4.FromArrayToRef = function (array, offset, result) {
  4293. result.x = array[offset];
  4294. result.y = array[offset + 1];
  4295. result.z = array[offset + 2];
  4296. result.w = array[offset + 3];
  4297. };
  4298. /**
  4299. * Updates the given vector "result" from the starting index of the given Float32Array.
  4300. */
  4301. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4302. Vector4.FromArrayToRef(array, offset, result);
  4303. };
  4304. /**
  4305. * Updates the given vector "result" coordinates from the given floats.
  4306. */
  4307. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4308. result.x = x;
  4309. result.y = y;
  4310. result.z = z;
  4311. result.w = w;
  4312. };
  4313. /**
  4314. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4315. */
  4316. Vector4.Zero = function () {
  4317. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4318. };
  4319. /**
  4320. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4321. */
  4322. Vector4.One = function () {
  4323. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4324. };
  4325. /**
  4326. * Returns a new normalized Vector4 from the given one.
  4327. */
  4328. Vector4.Normalize = function (vector) {
  4329. var result = Vector4.Zero();
  4330. Vector4.NormalizeToRef(vector, result);
  4331. return result;
  4332. };
  4333. /**
  4334. * Updates the given vector "result" from the normalization of the given one.
  4335. */
  4336. Vector4.NormalizeToRef = function (vector, result) {
  4337. result.copyFrom(vector);
  4338. result.normalize();
  4339. };
  4340. Vector4.Minimize = function (left, right) {
  4341. var min = left.clone();
  4342. min.minimizeInPlace(right);
  4343. return min;
  4344. };
  4345. Vector4.Maximize = function (left, right) {
  4346. var max = left.clone();
  4347. max.maximizeInPlace(right);
  4348. return max;
  4349. };
  4350. /**
  4351. * Returns the distance (float) between the vectors "value1" and "value2".
  4352. */
  4353. Vector4.Distance = function (value1, value2) {
  4354. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4355. };
  4356. /**
  4357. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4358. */
  4359. Vector4.DistanceSquared = function (value1, value2) {
  4360. var x = value1.x - value2.x;
  4361. var y = value1.y - value2.y;
  4362. var z = value1.z - value2.z;
  4363. var w = value1.w - value2.w;
  4364. return (x * x) + (y * y) + (z * z) + (w * w);
  4365. };
  4366. /**
  4367. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4368. */
  4369. Vector4.Center = function (value1, value2) {
  4370. var center = value1.add(value2);
  4371. center.scaleInPlace(0.5);
  4372. return center;
  4373. };
  4374. /**
  4375. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4376. * This methods computes transformed normalized direction vectors only.
  4377. */
  4378. Vector4.TransformNormal = function (vector, transformation) {
  4379. var result = Vector4.Zero();
  4380. Vector4.TransformNormalToRef(vector, transformation, result);
  4381. return result;
  4382. };
  4383. /**
  4384. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4385. * This methods computes transformed normalized direction vectors only.
  4386. */
  4387. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4388. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4389. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4390. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4391. result.x = x;
  4392. result.y = y;
  4393. result.z = z;
  4394. result.w = vector.w;
  4395. };
  4396. /**
  4397. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4398. * This methods computes transformed normalized direction vectors only.
  4399. */
  4400. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4401. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4402. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4403. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4404. result.w = w;
  4405. };
  4406. return Vector4;
  4407. }());
  4408. BABYLON.Vector4 = Vector4;
  4409. var Size = /** @class */ (function () {
  4410. /**
  4411. * Creates a Size object from the given width and height (floats).
  4412. */
  4413. function Size(width, height) {
  4414. this.width = width;
  4415. this.height = height;
  4416. }
  4417. // Returns a string with the Size width and height.
  4418. Size.prototype.toString = function () {
  4419. return "{W: " + this.width + ", H: " + this.height + "}";
  4420. };
  4421. /**
  4422. * Returns the string "Size"
  4423. */
  4424. Size.prototype.getClassName = function () {
  4425. return "Size";
  4426. };
  4427. /**
  4428. * Returns the Size hash code.
  4429. */
  4430. Size.prototype.getHashCode = function () {
  4431. var hash = this.width || 0;
  4432. hash = (hash * 397) ^ (this.height || 0);
  4433. return hash;
  4434. };
  4435. /**
  4436. * Updates the current size from the given one.
  4437. * Returns the updated Size.
  4438. */
  4439. Size.prototype.copyFrom = function (src) {
  4440. this.width = src.width;
  4441. this.height = src.height;
  4442. };
  4443. /**
  4444. * Updates in place the current Size from the given floats.
  4445. * Returns the updated Size.
  4446. */
  4447. Size.prototype.copyFromFloats = function (width, height) {
  4448. this.width = width;
  4449. this.height = height;
  4450. return this;
  4451. };
  4452. /**
  4453. * Updates in place the current Size from the given floats.
  4454. * Returns the updated Size.
  4455. */
  4456. Size.prototype.set = function (width, height) {
  4457. return this.copyFromFloats(width, height);
  4458. };
  4459. /**
  4460. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4461. */
  4462. Size.prototype.multiplyByFloats = function (w, h) {
  4463. return new Size(this.width * w, this.height * h);
  4464. };
  4465. /**
  4466. * Returns a new Size copied from the given one.
  4467. */
  4468. Size.prototype.clone = function () {
  4469. return new Size(this.width, this.height);
  4470. };
  4471. /**
  4472. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4473. */
  4474. Size.prototype.equals = function (other) {
  4475. if (!other) {
  4476. return false;
  4477. }
  4478. return (this.width === other.width) && (this.height === other.height);
  4479. };
  4480. Object.defineProperty(Size.prototype, "surface", {
  4481. /**
  4482. * Returns the surface of the Size : width * height (float).
  4483. */
  4484. get: function () {
  4485. return this.width * this.height;
  4486. },
  4487. enumerable: true,
  4488. configurable: true
  4489. });
  4490. /**
  4491. * Returns a new Size set to (0.0, 0.0)
  4492. */
  4493. Size.Zero = function () {
  4494. return new Size(0.0, 0.0);
  4495. };
  4496. /**
  4497. * Returns a new Size set as the addition result of the current Size and the given one.
  4498. */
  4499. Size.prototype.add = function (otherSize) {
  4500. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4501. return r;
  4502. };
  4503. /**
  4504. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4505. */
  4506. Size.prototype.subtract = function (otherSize) {
  4507. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4508. return r;
  4509. };
  4510. /**
  4511. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4512. */
  4513. Size.Lerp = function (start, end, amount) {
  4514. var w = start.width + ((end.width - start.width) * amount);
  4515. var h = start.height + ((end.height - start.height) * amount);
  4516. return new Size(w, h);
  4517. };
  4518. return Size;
  4519. }());
  4520. BABYLON.Size = Size;
  4521. /**
  4522. * Class used to store quaternion data
  4523. * @see https://en.wikipedia.org/wiki/Quaternion
  4524. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4525. */
  4526. var Quaternion = /** @class */ (function () {
  4527. /**
  4528. * Creates a new Quaternion from the given floats
  4529. * @param x defines the first component (0 by default)
  4530. * @param y defines the second component (0 by default)
  4531. * @param z defines the third component (0 by default)
  4532. * @param w defines the fourth component (1.0 by default)
  4533. */
  4534. function Quaternion(
  4535. /** defines the first component (0 by default) */
  4536. x,
  4537. /** defines the second component (0 by default) */
  4538. y,
  4539. /** defines the third component (0 by default) */
  4540. z,
  4541. /** defines the fourth component (1.0 by default) */
  4542. w) {
  4543. if (x === void 0) { x = 0.0; }
  4544. if (y === void 0) { y = 0.0; }
  4545. if (z === void 0) { z = 0.0; }
  4546. if (w === void 0) { w = 1.0; }
  4547. this.x = x;
  4548. this.y = y;
  4549. this.z = z;
  4550. this.w = w;
  4551. }
  4552. /**
  4553. * Gets a string representation for the current quaternion
  4554. * @returns a string with the Quaternion coordinates
  4555. */
  4556. Quaternion.prototype.toString = function () {
  4557. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4558. };
  4559. /**
  4560. * Gets the class name of the quaternion
  4561. * @returns the string "Quaternion"
  4562. */
  4563. Quaternion.prototype.getClassName = function () {
  4564. return "Quaternion";
  4565. };
  4566. /**
  4567. * Gets a hash code for this quaternion
  4568. * @returns the quaternion hash code
  4569. */
  4570. Quaternion.prototype.getHashCode = function () {
  4571. var hash = this.x || 0;
  4572. hash = (hash * 397) ^ (this.y || 0);
  4573. hash = (hash * 397) ^ (this.z || 0);
  4574. hash = (hash * 397) ^ (this.w || 0);
  4575. return hash;
  4576. };
  4577. /**
  4578. * Copy the quaternion to an array
  4579. * @returns a new array populated with 4 elements from the quaternion coordinates
  4580. */
  4581. Quaternion.prototype.asArray = function () {
  4582. return [this.x, this.y, this.z, this.w];
  4583. };
  4584. /**
  4585. * Check if two quaternions are equals
  4586. * @param otherQuaternion defines the second operand
  4587. * @return true if the current quaternion and the given one coordinates are strictly equals
  4588. */
  4589. Quaternion.prototype.equals = function (otherQuaternion) {
  4590. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4591. };
  4592. /**
  4593. * Clone the current quaternion
  4594. * @returns a new quaternion copied from the current one
  4595. */
  4596. Quaternion.prototype.clone = function () {
  4597. return new Quaternion(this.x, this.y, this.z, this.w);
  4598. };
  4599. /**
  4600. * Copy a quaternion to the current one
  4601. * @param other defines the other quaternion
  4602. * @returns the updated current quaternion
  4603. */
  4604. Quaternion.prototype.copyFrom = function (other) {
  4605. this.x = other.x;
  4606. this.y = other.y;
  4607. this.z = other.z;
  4608. this.w = other.w;
  4609. return this;
  4610. };
  4611. /**
  4612. * Updates the current quaternion with the given float coordinates
  4613. * @param x defines the x coordinate
  4614. * @param y defines the y coordinate
  4615. * @param z defines the z coordinate
  4616. * @param w defines the w coordinate
  4617. * @returns the updated current quaternion
  4618. */
  4619. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4620. this.x = x;
  4621. this.y = y;
  4622. this.z = z;
  4623. this.w = w;
  4624. return this;
  4625. };
  4626. /**
  4627. * Updates the current quaternion from the given float coordinates
  4628. * @param x defines the x coordinate
  4629. * @param y defines the y coordinate
  4630. * @param z defines the z coordinate
  4631. * @param w defines the w coordinate
  4632. * @returns the updated current quaternion
  4633. */
  4634. Quaternion.prototype.set = function (x, y, z, w) {
  4635. return this.copyFromFloats(x, y, z, w);
  4636. };
  4637. /**
  4638. * Adds two quaternions
  4639. * @param other defines the second operand
  4640. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4641. */
  4642. Quaternion.prototype.add = function (other) {
  4643. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4644. };
  4645. /**
  4646. * Add a quaternion to the current one
  4647. * @param other defines the quaternion to add
  4648. * @returns the current quaternion
  4649. */
  4650. Quaternion.prototype.addInPlace = function (other) {
  4651. this.x += other.x;
  4652. this.y += other.y;
  4653. this.z += other.z;
  4654. this.w += other.w;
  4655. return this;
  4656. };
  4657. /**
  4658. * Subtract two quaternions
  4659. * @param other defines the second operand
  4660. * @returns a new quaternion as the subtraction result of the given one from the current one
  4661. */
  4662. Quaternion.prototype.subtract = function (other) {
  4663. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4664. };
  4665. /**
  4666. * Multiplies the current quaternion by a scale factor
  4667. * @param value defines the scale factor
  4668. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4669. */
  4670. Quaternion.prototype.scale = function (value) {
  4671. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4672. };
  4673. /**
  4674. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4675. * @param scale defines the scale factor
  4676. * @param result defines the Quaternion object where to store the result
  4677. * @returns the unmodified current quaternion
  4678. */
  4679. Quaternion.prototype.scaleToRef = function (scale, result) {
  4680. result.x = this.x * scale;
  4681. result.y = this.y * scale;
  4682. result.z = this.z * scale;
  4683. result.w = this.w * scale;
  4684. return this;
  4685. };
  4686. /**
  4687. * Multiplies in place the current quaternion by a scale factor
  4688. * @param value defines the scale factor
  4689. * @returns the current modified quaternion
  4690. */
  4691. Quaternion.prototype.scaleInPlace = function (value) {
  4692. this.x *= value;
  4693. this.y *= value;
  4694. this.z *= value;
  4695. this.w *= value;
  4696. return this;
  4697. };
  4698. /**
  4699. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4700. * @param scale defines the scale factor
  4701. * @param result defines the Quaternion object where to store the result
  4702. * @returns the unmodified current quaternion
  4703. */
  4704. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4705. result.x += this.x * scale;
  4706. result.y += this.y * scale;
  4707. result.z += this.z * scale;
  4708. result.w += this.w * scale;
  4709. return this;
  4710. };
  4711. /**
  4712. * Multiplies two quaternions
  4713. * @param q1 defines the second operand
  4714. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4715. */
  4716. Quaternion.prototype.multiply = function (q1) {
  4717. var result = new Quaternion(0, 0, 0, 1.0);
  4718. this.multiplyToRef(q1, result);
  4719. return result;
  4720. };
  4721. /**
  4722. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4723. * @param q1 defines the second operand
  4724. * @param result defines the target quaternion
  4725. * @returns the current quaternion
  4726. */
  4727. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4728. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4729. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4730. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4731. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4732. result.copyFromFloats(x, y, z, w);
  4733. return this;
  4734. };
  4735. /**
  4736. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4737. * @param q1 defines the second operand
  4738. * @returns the currentupdated quaternion
  4739. */
  4740. Quaternion.prototype.multiplyInPlace = function (q1) {
  4741. this.multiplyToRef(q1, this);
  4742. return this;
  4743. };
  4744. /**
  4745. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4746. * @param ref defines the target quaternion
  4747. * @returns the current quaternion
  4748. */
  4749. Quaternion.prototype.conjugateToRef = function (ref) {
  4750. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4751. return this;
  4752. };
  4753. /**
  4754. * Conjugates in place (1-q) the current quaternion
  4755. * @returns the current updated quaternion
  4756. */
  4757. Quaternion.prototype.conjugateInPlace = function () {
  4758. this.x *= -1;
  4759. this.y *= -1;
  4760. this.z *= -1;
  4761. return this;
  4762. };
  4763. /**
  4764. * Conjugates in place (1-q) the current quaternion
  4765. * @returns a new quaternion
  4766. */
  4767. Quaternion.prototype.conjugate = function () {
  4768. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4769. return result;
  4770. };
  4771. /**
  4772. * Gets length of current quaternion
  4773. * @returns the quaternion length (float)
  4774. */
  4775. Quaternion.prototype.length = function () {
  4776. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4777. };
  4778. /**
  4779. * Normalize in place the current quaternion
  4780. * @returns the current updated quaternion
  4781. */
  4782. Quaternion.prototype.normalize = function () {
  4783. var length = 1.0 / this.length();
  4784. this.x *= length;
  4785. this.y *= length;
  4786. this.z *= length;
  4787. this.w *= length;
  4788. return this;
  4789. };
  4790. /**
  4791. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4792. * @param order is a reserved parameter and is ignore for now
  4793. * @returns a new Vector3 containing the Euler angles
  4794. */
  4795. Quaternion.prototype.toEulerAngles = function (order) {
  4796. if (order === void 0) { order = "YZX"; }
  4797. var result = Vector3.Zero();
  4798. this.toEulerAnglesToRef(result, order);
  4799. return result;
  4800. };
  4801. /**
  4802. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4803. * @param result defines the vector which will be filled with the Euler angles
  4804. * @param order is a reserved parameter and is ignore for now
  4805. * @returns the current unchanged quaternion
  4806. */
  4807. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4808. if (order === void 0) { order = "YZX"; }
  4809. var qz = this.z;
  4810. var qx = this.x;
  4811. var qy = this.y;
  4812. var qw = this.w;
  4813. var sqw = qw * qw;
  4814. var sqz = qz * qz;
  4815. var sqx = qx * qx;
  4816. var sqy = qy * qy;
  4817. var zAxisY = qy * qz - qx * qw;
  4818. var limit = .4999999;
  4819. if (zAxisY < -limit) {
  4820. result.y = 2 * Math.atan2(qy, qw);
  4821. result.x = Math.PI / 2;
  4822. result.z = 0;
  4823. }
  4824. else if (zAxisY > limit) {
  4825. result.y = 2 * Math.atan2(qy, qw);
  4826. result.x = -Math.PI / 2;
  4827. result.z = 0;
  4828. }
  4829. else {
  4830. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4831. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4832. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4833. }
  4834. return this;
  4835. };
  4836. /**
  4837. * Updates the given rotation matrix with the current quaternion values
  4838. * @param result defines the target matrix
  4839. * @returns the current unchanged quaternion
  4840. */
  4841. Quaternion.prototype.toRotationMatrix = function (result) {
  4842. var xx = this.x * this.x;
  4843. var yy = this.y * this.y;
  4844. var zz = this.z * this.z;
  4845. var xy = this.x * this.y;
  4846. var zw = this.z * this.w;
  4847. var zx = this.z * this.x;
  4848. var yw = this.y * this.w;
  4849. var yz = this.y * this.z;
  4850. var xw = this.x * this.w;
  4851. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4852. result.m[1] = 2.0 * (xy + zw);
  4853. result.m[2] = 2.0 * (zx - yw);
  4854. result.m[3] = 0;
  4855. result.m[4] = 2.0 * (xy - zw);
  4856. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4857. result.m[6] = 2.0 * (yz + xw);
  4858. result.m[7] = 0;
  4859. result.m[8] = 2.0 * (zx + yw);
  4860. result.m[9] = 2.0 * (yz - xw);
  4861. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4862. result.m[11] = 0;
  4863. result.m[12] = 0;
  4864. result.m[13] = 0;
  4865. result.m[14] = 0;
  4866. result.m[15] = 1.0;
  4867. result._markAsUpdated();
  4868. return this;
  4869. };
  4870. /**
  4871. * Updates the current quaternion from the given rotation matrix values
  4872. * @param matrix defines the source matrix
  4873. * @returns the current updated quaternion
  4874. */
  4875. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4876. Quaternion.FromRotationMatrixToRef(matrix, this);
  4877. return this;
  4878. };
  4879. // Statics
  4880. /**
  4881. * Creates a new quaternion from a rotation matrix
  4882. * @param matrix defines the source matrix
  4883. * @returns a new quaternion created from the given rotation matrix values
  4884. */
  4885. Quaternion.FromRotationMatrix = function (matrix) {
  4886. var result = new Quaternion();
  4887. Quaternion.FromRotationMatrixToRef(matrix, result);
  4888. return result;
  4889. };
  4890. /**
  4891. * Updates the given quaternion with the given rotation matrix values
  4892. * @param matrix defines the source matrix
  4893. * @param result defines the target quaternion
  4894. */
  4895. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4896. var data = matrix.m;
  4897. var m11 = data[0], m12 = data[4], m13 = data[8];
  4898. var m21 = data[1], m22 = data[5], m23 = data[9];
  4899. var m31 = data[2], m32 = data[6], m33 = data[10];
  4900. var trace = m11 + m22 + m33;
  4901. var s;
  4902. if (trace > 0) {
  4903. s = 0.5 / Math.sqrt(trace + 1.0);
  4904. result.w = 0.25 / s;
  4905. result.x = (m32 - m23) * s;
  4906. result.y = (m13 - m31) * s;
  4907. result.z = (m21 - m12) * s;
  4908. }
  4909. else if (m11 > m22 && m11 > m33) {
  4910. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4911. result.w = (m32 - m23) / s;
  4912. result.x = 0.25 * s;
  4913. result.y = (m12 + m21) / s;
  4914. result.z = (m13 + m31) / s;
  4915. }
  4916. else if (m22 > m33) {
  4917. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4918. result.w = (m13 - m31) / s;
  4919. result.x = (m12 + m21) / s;
  4920. result.y = 0.25 * s;
  4921. result.z = (m23 + m32) / s;
  4922. }
  4923. else {
  4924. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4925. result.w = (m21 - m12) / s;
  4926. result.x = (m13 + m31) / s;
  4927. result.y = (m23 + m32) / s;
  4928. result.z = 0.25 * s;
  4929. }
  4930. };
  4931. /**
  4932. * Returns the dot product (float) between the quaternions "left" and "right"
  4933. * @param left defines the left operand
  4934. * @param right defines the right operand
  4935. * @returns the dot product
  4936. */
  4937. Quaternion.Dot = function (left, right) {
  4938. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4939. };
  4940. /**
  4941. * Checks if the two quaternions are close to each other
  4942. * @param quat0 defines the first quaternion to check
  4943. * @param quat1 defines the second quaternion to check
  4944. * @returns true if the two quaternions are close to each other
  4945. */
  4946. Quaternion.AreClose = function (quat0, quat1) {
  4947. var dot = Quaternion.Dot(quat0, quat1);
  4948. return dot >= 0;
  4949. };
  4950. /**
  4951. * Creates an empty quaternion
  4952. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4953. */
  4954. Quaternion.Zero = function () {
  4955. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4956. };
  4957. /**
  4958. * Inverse a given quaternion
  4959. * @param q defines the source quaternion
  4960. * @returns a new quaternion as the inverted current quaternion
  4961. */
  4962. Quaternion.Inverse = function (q) {
  4963. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4964. };
  4965. /**
  4966. * Creates an identity quaternion
  4967. * @returns the identity quaternion
  4968. */
  4969. Quaternion.Identity = function () {
  4970. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4971. };
  4972. /**
  4973. * Gets a boolean indicating if the given quaternion is identity
  4974. * @param quaternion defines the quaternion to check
  4975. * @returns true if the quaternion is identity
  4976. */
  4977. Quaternion.IsIdentity = function (quaternion) {
  4978. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4979. };
  4980. /**
  4981. * Creates a quaternion from a rotation around an axis
  4982. * @param axis defines the axis to use
  4983. * @param angle defines the angle to use
  4984. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4985. */
  4986. Quaternion.RotationAxis = function (axis, angle) {
  4987. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4988. };
  4989. /**
  4990. * Creates a rotation around an axis and stores it into the given quaternion
  4991. * @param axis defines the axis to use
  4992. * @param angle defines the angle to use
  4993. * @param result defines the target quaternion
  4994. * @returns the target quaternion
  4995. */
  4996. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4997. var sin = Math.sin(angle / 2);
  4998. axis.normalize();
  4999. result.w = Math.cos(angle / 2);
  5000. result.x = axis.x * sin;
  5001. result.y = axis.y * sin;
  5002. result.z = axis.z * sin;
  5003. return result;
  5004. };
  5005. /**
  5006. * Creates a new quaternion from data stored into an array
  5007. * @param array defines the data source
  5008. * @param offset defines the offset in the source array where the data starts
  5009. * @returns a new quaternion
  5010. */
  5011. Quaternion.FromArray = function (array, offset) {
  5012. if (!offset) {
  5013. offset = 0;
  5014. }
  5015. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5016. };
  5017. /**
  5018. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5019. * @param yaw defines the rotation around Y axis
  5020. * @param pitch defines the rotation around X axis
  5021. * @param roll defines the rotation around Z axis
  5022. * @returns the new quaternion
  5023. */
  5024. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5025. var q = new Quaternion();
  5026. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5027. return q;
  5028. };
  5029. /**
  5030. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5031. * @param yaw defines the rotation around Y axis
  5032. * @param pitch defines the rotation around X axis
  5033. * @param roll defines the rotation around Z axis
  5034. * @param result defines the target quaternion
  5035. */
  5036. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5037. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5038. var halfRoll = roll * 0.5;
  5039. var halfPitch = pitch * 0.5;
  5040. var halfYaw = yaw * 0.5;
  5041. var sinRoll = Math.sin(halfRoll);
  5042. var cosRoll = Math.cos(halfRoll);
  5043. var sinPitch = Math.sin(halfPitch);
  5044. var cosPitch = Math.cos(halfPitch);
  5045. var sinYaw = Math.sin(halfYaw);
  5046. var cosYaw = Math.cos(halfYaw);
  5047. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5048. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5049. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5050. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5051. };
  5052. /**
  5053. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5054. * @param alpha defines the rotation around first axis
  5055. * @param beta defines the rotation around second axis
  5056. * @param gamma defines the rotation around third axis
  5057. * @returns the new quaternion
  5058. */
  5059. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5060. var result = new Quaternion();
  5061. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5062. return result;
  5063. };
  5064. /**
  5065. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5066. * @param alpha defines the rotation around first axis
  5067. * @param beta defines the rotation around second axis
  5068. * @param gamma defines the rotation around third axis
  5069. * @param result defines the target quaternion
  5070. */
  5071. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5072. // Produces a quaternion from Euler angles in the z-x-z orientation
  5073. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5074. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5075. var halfBeta = beta * 0.5;
  5076. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5077. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5078. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5079. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5080. };
  5081. /**
  5082. * 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)
  5083. * @param axis1 defines the first axis
  5084. * @param axis2 defines the second axis
  5085. * @param axis3 defines the third axis
  5086. * @returns the new quaternion
  5087. */
  5088. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5089. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5090. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5091. return quat;
  5092. };
  5093. /**
  5094. * 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
  5095. * @param axis1 defines the first axis
  5096. * @param axis2 defines the second axis
  5097. * @param axis3 defines the third axis
  5098. * @param ref defines the target quaternion
  5099. */
  5100. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5101. var rotMat = MathTmp.Matrix[0];
  5102. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5103. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5104. };
  5105. /**
  5106. * Interpolates between two quaternions
  5107. * @param left defines first quaternion
  5108. * @param right defines second quaternion
  5109. * @param amount defines the gradient to use
  5110. * @returns the new interpolated quaternion
  5111. */
  5112. Quaternion.Slerp = function (left, right, amount) {
  5113. var result = Quaternion.Identity();
  5114. Quaternion.SlerpToRef(left, right, amount, result);
  5115. return result;
  5116. };
  5117. /**
  5118. * Interpolates between two quaternions and stores it into a target quaternion
  5119. * @param left defines first quaternion
  5120. * @param right defines second quaternion
  5121. * @param amount defines the gradient to use
  5122. * @param result defines the target quaternion
  5123. */
  5124. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5125. var num2;
  5126. var num3;
  5127. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5128. var flag = false;
  5129. if (num4 < 0) {
  5130. flag = true;
  5131. num4 = -num4;
  5132. }
  5133. if (num4 > 0.999999) {
  5134. num3 = 1 - amount;
  5135. num2 = flag ? -amount : amount;
  5136. }
  5137. else {
  5138. var num5 = Math.acos(num4);
  5139. var num6 = (1.0 / Math.sin(num5));
  5140. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5141. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5142. }
  5143. result.x = (num3 * left.x) + (num2 * right.x);
  5144. result.y = (num3 * left.y) + (num2 * right.y);
  5145. result.z = (num3 * left.z) + (num2 * right.z);
  5146. result.w = (num3 * left.w) + (num2 * right.w);
  5147. };
  5148. /**
  5149. * Interpolate between two quaternions using Hermite interpolation
  5150. * @param value1 defines first quaternion
  5151. * @param tangent1 defines the incoming tangent
  5152. * @param value2 defines second quaternion
  5153. * @param tangent2 defines the outgoing tangent
  5154. * @param amount defines the target quaternion
  5155. * @returns the new interpolated quaternion
  5156. */
  5157. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5158. var squared = amount * amount;
  5159. var cubed = amount * squared;
  5160. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5161. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5162. var part3 = (cubed - (2.0 * squared)) + amount;
  5163. var part4 = cubed - squared;
  5164. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5165. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5166. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5167. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5168. return new Quaternion(x, y, z, w);
  5169. };
  5170. return Quaternion;
  5171. }());
  5172. BABYLON.Quaternion = Quaternion;
  5173. /**
  5174. * Class used to store matrix data (4x4)
  5175. */
  5176. var Matrix = /** @class */ (function () {
  5177. /**
  5178. * Creates an empty matrix (filled with zeros)
  5179. */
  5180. function Matrix() {
  5181. this._isIdentity = false;
  5182. this._isIdentityDirty = true;
  5183. /**
  5184. * Gets or sets the internal data of the matrix
  5185. */
  5186. this.m = new Float32Array(16);
  5187. this._markAsUpdated();
  5188. }
  5189. /** @hidden */
  5190. Matrix.prototype._markAsUpdated = function () {
  5191. this.updateFlag = Matrix._updateFlagSeed++;
  5192. this._isIdentityDirty = true;
  5193. };
  5194. // Properties
  5195. /**
  5196. * Check if the current matrix is indentity
  5197. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5198. * @returns true is the matrix is the identity matrix
  5199. */
  5200. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5201. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5202. if (this._isIdentityDirty) {
  5203. this._isIdentityDirty = false;
  5204. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5205. this._isIdentity = false;
  5206. }
  5207. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5208. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5209. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5210. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5211. this._isIdentity = false;
  5212. }
  5213. else {
  5214. this._isIdentity = true;
  5215. }
  5216. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5217. this._isIdentity = false;
  5218. }
  5219. }
  5220. return this._isIdentity;
  5221. };
  5222. /**
  5223. * Gets the determinant of the matrix
  5224. * @returns the matrix determinant
  5225. */
  5226. Matrix.prototype.determinant = function () {
  5227. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5228. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5229. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5230. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5231. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5232. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5233. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5234. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5235. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5236. };
  5237. // Methods
  5238. /**
  5239. * Returns the matrix as a Float32Array
  5240. * @returns the matrix underlying array
  5241. */
  5242. Matrix.prototype.toArray = function () {
  5243. return this.m;
  5244. };
  5245. /**
  5246. * Returns the matrix as a Float32Array
  5247. * @returns the matrix underlying array.
  5248. */
  5249. Matrix.prototype.asArray = function () {
  5250. return this.toArray();
  5251. };
  5252. /**
  5253. * Inverts the current matrix in place
  5254. * @returns the current inverted matrix
  5255. */
  5256. Matrix.prototype.invert = function () {
  5257. this.invertToRef(this);
  5258. return this;
  5259. };
  5260. /**
  5261. * Sets all the matrix elements to zero
  5262. * @returns the current matrix
  5263. */
  5264. Matrix.prototype.reset = function () {
  5265. for (var index = 0; index < 16; index++) {
  5266. this.m[index] = 0.0;
  5267. }
  5268. this._markAsUpdated();
  5269. return this;
  5270. };
  5271. /**
  5272. * Adds the current matrix with a second one
  5273. * @param other defines the matrix to add
  5274. * @returns a new matrix as the addition of the current matrix and the given one
  5275. */
  5276. Matrix.prototype.add = function (other) {
  5277. var result = new Matrix();
  5278. this.addToRef(other, result);
  5279. return result;
  5280. };
  5281. /**
  5282. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5283. * @param other defines the matrix to add
  5284. * @param result defines the target matrix
  5285. * @returns the current matrix
  5286. */
  5287. Matrix.prototype.addToRef = function (other, result) {
  5288. for (var index = 0; index < 16; index++) {
  5289. result.m[index] = this.m[index] + other.m[index];
  5290. }
  5291. result._markAsUpdated();
  5292. return this;
  5293. };
  5294. /**
  5295. * Adds in place the given matrix to the current matrix
  5296. * @param other defines the second operand
  5297. * @returns the current updated matrix
  5298. */
  5299. Matrix.prototype.addToSelf = function (other) {
  5300. for (var index = 0; index < 16; index++) {
  5301. this.m[index] += other.m[index];
  5302. }
  5303. this._markAsUpdated();
  5304. return this;
  5305. };
  5306. /**
  5307. * Sets the given matrix to the current inverted Matrix
  5308. * @param other defines the target matrix
  5309. * @returns the unmodified current matrix
  5310. */
  5311. Matrix.prototype.invertToRef = function (other) {
  5312. var l1 = this.m[0];
  5313. var l2 = this.m[1];
  5314. var l3 = this.m[2];
  5315. var l4 = this.m[3];
  5316. var l5 = this.m[4];
  5317. var l6 = this.m[5];
  5318. var l7 = this.m[6];
  5319. var l8 = this.m[7];
  5320. var l9 = this.m[8];
  5321. var l10 = this.m[9];
  5322. var l11 = this.m[10];
  5323. var l12 = this.m[11];
  5324. var l13 = this.m[12];
  5325. var l14 = this.m[13];
  5326. var l15 = this.m[14];
  5327. var l16 = this.m[15];
  5328. var l17 = (l11 * l16) - (l12 * l15);
  5329. var l18 = (l10 * l16) - (l12 * l14);
  5330. var l19 = (l10 * l15) - (l11 * l14);
  5331. var l20 = (l9 * l16) - (l12 * l13);
  5332. var l21 = (l9 * l15) - (l11 * l13);
  5333. var l22 = (l9 * l14) - (l10 * l13);
  5334. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5335. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5336. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5337. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5338. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5339. var l28 = (l7 * l16) - (l8 * l15);
  5340. var l29 = (l6 * l16) - (l8 * l14);
  5341. var l30 = (l6 * l15) - (l7 * l14);
  5342. var l31 = (l5 * l16) - (l8 * l13);
  5343. var l32 = (l5 * l15) - (l7 * l13);
  5344. var l33 = (l5 * l14) - (l6 * l13);
  5345. var l34 = (l7 * l12) - (l8 * l11);
  5346. var l35 = (l6 * l12) - (l8 * l10);
  5347. var l36 = (l6 * l11) - (l7 * l10);
  5348. var l37 = (l5 * l12) - (l8 * l9);
  5349. var l38 = (l5 * l11) - (l7 * l9);
  5350. var l39 = (l5 * l10) - (l6 * l9);
  5351. other.m[0] = l23 * l27;
  5352. other.m[4] = l24 * l27;
  5353. other.m[8] = l25 * l27;
  5354. other.m[12] = l26 * l27;
  5355. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5356. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5357. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5358. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5359. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5360. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5361. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5362. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5363. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5364. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5365. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5366. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5367. other._markAsUpdated();
  5368. return this;
  5369. };
  5370. /**
  5371. * Inserts the translation vector (using 3 floats) in the current matrix
  5372. * @param x defines the 1st component of the translation
  5373. * @param y defines the 2nd component of the translation
  5374. * @param z defines the 3rd component of the translation
  5375. * @returns the current updated matrix
  5376. */
  5377. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5378. this.m[12] = x;
  5379. this.m[13] = y;
  5380. this.m[14] = z;
  5381. this._markAsUpdated();
  5382. return this;
  5383. };
  5384. /**
  5385. * Inserts the translation vector in the current matrix
  5386. * @param vector3 defines the translation to insert
  5387. * @returns the current updated matrix
  5388. */
  5389. Matrix.prototype.setTranslation = function (vector3) {
  5390. this.m[12] = vector3.x;
  5391. this.m[13] = vector3.y;
  5392. this.m[14] = vector3.z;
  5393. this._markAsUpdated();
  5394. return this;
  5395. };
  5396. /**
  5397. * Gets the translation value of the current matrix
  5398. * @returns a new Vector3 as the extracted translation from the matrix
  5399. */
  5400. Matrix.prototype.getTranslation = function () {
  5401. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5402. };
  5403. /**
  5404. * Fill a Vector3 with the extracted translation from the matrix
  5405. * @param result defines the Vector3 where to store the translation
  5406. * @returns the current matrix
  5407. */
  5408. Matrix.prototype.getTranslationToRef = function (result) {
  5409. result.x = this.m[12];
  5410. result.y = this.m[13];
  5411. result.z = this.m[14];
  5412. return this;
  5413. };
  5414. /**
  5415. * Remove rotation and scaling part from the matrix
  5416. * @returns the updated matrix
  5417. */
  5418. Matrix.prototype.removeRotationAndScaling = function () {
  5419. this.setRowFromFloats(0, 1, 0, 0, 0);
  5420. this.setRowFromFloats(1, 0, 1, 0, 0);
  5421. this.setRowFromFloats(2, 0, 0, 1, 0);
  5422. return this;
  5423. };
  5424. /**
  5425. * Multiply two matrices
  5426. * @param other defines the second operand
  5427. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5428. */
  5429. Matrix.prototype.multiply = function (other) {
  5430. var result = new Matrix();
  5431. this.multiplyToRef(other, result);
  5432. return result;
  5433. };
  5434. /**
  5435. * Copy the current matrix from the given one
  5436. * @param other defines the source matrix
  5437. * @returns the current updated matrix
  5438. */
  5439. Matrix.prototype.copyFrom = function (other) {
  5440. for (var index = 0; index < 16; index++) {
  5441. this.m[index] = other.m[index];
  5442. }
  5443. this._markAsUpdated();
  5444. return this;
  5445. };
  5446. /**
  5447. * Populates the given array from the starting index with the current matrix values
  5448. * @param array defines the target array
  5449. * @param offset defines the offset in the target array where to start storing values
  5450. * @returns the current matrix
  5451. */
  5452. Matrix.prototype.copyToArray = function (array, offset) {
  5453. if (offset === void 0) { offset = 0; }
  5454. for (var index = 0; index < 16; index++) {
  5455. array[offset + index] = this.m[index];
  5456. }
  5457. return this;
  5458. };
  5459. /**
  5460. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5461. * @param other defines the second operand
  5462. * @param result defines the matrix where to store the multiplication
  5463. * @returns the current matrix
  5464. */
  5465. Matrix.prototype.multiplyToRef = function (other, result) {
  5466. this.multiplyToArray(other, result.m, 0);
  5467. result._markAsUpdated();
  5468. return this;
  5469. };
  5470. /**
  5471. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5472. * @param other defines the second operand
  5473. * @param result defines the array where to store the multiplication
  5474. * @param offset defines the offset in the target array where to start storing values
  5475. * @returns the current matrix
  5476. */
  5477. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5478. var tm0 = this.m[0];
  5479. var tm1 = this.m[1];
  5480. var tm2 = this.m[2];
  5481. var tm3 = this.m[3];
  5482. var tm4 = this.m[4];
  5483. var tm5 = this.m[5];
  5484. var tm6 = this.m[6];
  5485. var tm7 = this.m[7];
  5486. var tm8 = this.m[8];
  5487. var tm9 = this.m[9];
  5488. var tm10 = this.m[10];
  5489. var tm11 = this.m[11];
  5490. var tm12 = this.m[12];
  5491. var tm13 = this.m[13];
  5492. var tm14 = this.m[14];
  5493. var tm15 = this.m[15];
  5494. var om0 = other.m[0];
  5495. var om1 = other.m[1];
  5496. var om2 = other.m[2];
  5497. var om3 = other.m[3];
  5498. var om4 = other.m[4];
  5499. var om5 = other.m[5];
  5500. var om6 = other.m[6];
  5501. var om7 = other.m[7];
  5502. var om8 = other.m[8];
  5503. var om9 = other.m[9];
  5504. var om10 = other.m[10];
  5505. var om11 = other.m[11];
  5506. var om12 = other.m[12];
  5507. var om13 = other.m[13];
  5508. var om14 = other.m[14];
  5509. var om15 = other.m[15];
  5510. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5511. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5512. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5513. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5514. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5515. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5516. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5517. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5518. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5519. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5520. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5521. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5522. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5523. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5524. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5525. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5526. return this;
  5527. };
  5528. /**
  5529. * Check equality between this matrix and a second one
  5530. * @param value defines the second matrix to compare
  5531. * @returns true is the current matrix and the given one values are strictly equal
  5532. */
  5533. Matrix.prototype.equals = function (value) {
  5534. return value &&
  5535. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5536. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5537. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5538. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5539. };
  5540. /**
  5541. * Clone the current matrix
  5542. * @returns a new matrix from the current matrix
  5543. */
  5544. Matrix.prototype.clone = function () {
  5545. 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]);
  5546. };
  5547. /**
  5548. * Returns the name of the current matrix class
  5549. * @returns the string "Matrix"
  5550. */
  5551. Matrix.prototype.getClassName = function () {
  5552. return "Matrix";
  5553. };
  5554. /**
  5555. * Gets the hash code of the current matrix
  5556. * @returns the hash code
  5557. */
  5558. Matrix.prototype.getHashCode = function () {
  5559. var hash = this.m[0] || 0;
  5560. for (var i = 1; i < 16; i++) {
  5561. hash = (hash * 397) ^ (this.m[i] || 0);
  5562. }
  5563. return hash;
  5564. };
  5565. /**
  5566. * Decomposes the current Matrix into a translation, rotation and scaling components
  5567. * @param scale defines the scale vector3 given as a reference to update
  5568. * @param rotation defines the rotation quaternion given as a reference to update
  5569. * @param translation defines the translation vector3 given as a reference to update
  5570. * @returns true if operation was successful
  5571. */
  5572. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5573. if (translation) {
  5574. translation.x = this.m[12];
  5575. translation.y = this.m[13];
  5576. translation.z = this.m[14];
  5577. }
  5578. scale = scale || MathTmp.Vector3[0];
  5579. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5580. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5581. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5582. if (this.determinant() <= 0) {
  5583. scale.y *= -1;
  5584. }
  5585. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5586. if (rotation) {
  5587. rotation.x = 0;
  5588. rotation.y = 0;
  5589. rotation.z = 0;
  5590. rotation.w = 1;
  5591. }
  5592. return false;
  5593. }
  5594. if (rotation) {
  5595. 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]);
  5596. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5597. }
  5598. return true;
  5599. };
  5600. /**
  5601. * Gets specific row of the matrix
  5602. * @param index defines the number of the row to get
  5603. * @returns the index-th row of the current matrix as a new Vector4
  5604. */
  5605. Matrix.prototype.getRow = function (index) {
  5606. if (index < 0 || index > 3) {
  5607. return null;
  5608. }
  5609. var i = index * 4;
  5610. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5611. };
  5612. /**
  5613. * Sets the index-th row of the current matrix to the vector4 values
  5614. * @param index defines the number of the row to set
  5615. * @param row defines the target vector4
  5616. * @returns the updated current matrix
  5617. */
  5618. Matrix.prototype.setRow = function (index, row) {
  5619. if (index < 0 || index > 3) {
  5620. return this;
  5621. }
  5622. var i = index * 4;
  5623. this.m[i + 0] = row.x;
  5624. this.m[i + 1] = row.y;
  5625. this.m[i + 2] = row.z;
  5626. this.m[i + 3] = row.w;
  5627. this._markAsUpdated();
  5628. return this;
  5629. };
  5630. /**
  5631. * Compute the transpose of the matrix
  5632. * @returns the new transposed matrix
  5633. */
  5634. Matrix.prototype.transpose = function () {
  5635. return Matrix.Transpose(this);
  5636. };
  5637. /**
  5638. * Compute the transpose of the matrix and store it in a given matrix
  5639. * @param result defines the target matrix
  5640. * @returns the current matrix
  5641. */
  5642. Matrix.prototype.transposeToRef = function (result) {
  5643. Matrix.TransposeToRef(this, result);
  5644. return this;
  5645. };
  5646. /**
  5647. * Sets the index-th row of the current matrix with the given 4 x float values
  5648. * @param index defines the row index
  5649. * @param x defines the x component to set
  5650. * @param y defines the y component to set
  5651. * @param z defines the z component to set
  5652. * @param w defines the w component to set
  5653. * @returns the updated current matrix
  5654. */
  5655. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5656. if (index < 0 || index > 3) {
  5657. return this;
  5658. }
  5659. var i = index * 4;
  5660. this.m[i + 0] = x;
  5661. this.m[i + 1] = y;
  5662. this.m[i + 2] = z;
  5663. this.m[i + 3] = w;
  5664. this._markAsUpdated();
  5665. return this;
  5666. };
  5667. /**
  5668. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5669. * @param scale defines the scale factor
  5670. * @returns a new matrix
  5671. */
  5672. Matrix.prototype.scale = function (scale) {
  5673. var result = new Matrix();
  5674. this.scaleToRef(scale, result);
  5675. return result;
  5676. };
  5677. /**
  5678. * Scale the current matrix values by a factor to a given result matrix
  5679. * @param scale defines the scale factor
  5680. * @param result defines the matrix to store the result
  5681. * @returns the current matrix
  5682. */
  5683. Matrix.prototype.scaleToRef = function (scale, result) {
  5684. for (var index = 0; index < 16; index++) {
  5685. result.m[index] = this.m[index] * scale;
  5686. }
  5687. result._markAsUpdated();
  5688. return this;
  5689. };
  5690. /**
  5691. * Scale the current matrix values by a factor and add the result to a given matrix
  5692. * @param scale defines the scale factor
  5693. * @param result defines the Matrix to store the result
  5694. * @returns the current matrix
  5695. */
  5696. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5697. for (var index = 0; index < 16; index++) {
  5698. result.m[index] += this.m[index] * scale;
  5699. }
  5700. result._markAsUpdated();
  5701. return this;
  5702. };
  5703. /**
  5704. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5705. * @param ref matrix to store the result
  5706. */
  5707. Matrix.prototype.toNormalMatrix = function (ref) {
  5708. this.invertToRef(ref);
  5709. ref.transpose();
  5710. var m = ref.m;
  5711. 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);
  5712. };
  5713. /**
  5714. * Gets only rotation part of the current matrix
  5715. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5716. */
  5717. Matrix.prototype.getRotationMatrix = function () {
  5718. var result = Matrix.Identity();
  5719. this.getRotationMatrixToRef(result);
  5720. return result;
  5721. };
  5722. /**
  5723. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5724. * @param result defines the target matrix to store data to
  5725. * @returns the current matrix
  5726. */
  5727. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5728. var m = this.m;
  5729. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5730. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5731. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5732. if (this.determinant() <= 0) {
  5733. sy *= -1;
  5734. }
  5735. if (sx === 0 || sy === 0 || sz === 0) {
  5736. Matrix.IdentityToRef(result);
  5737. }
  5738. else {
  5739. 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);
  5740. }
  5741. return this;
  5742. };
  5743. // Statics
  5744. /**
  5745. * Creates a matrix from an array
  5746. * @param array defines the source array
  5747. * @param offset defines an offset in the source array
  5748. * @returns a new Matrix set from the starting index of the given array
  5749. */
  5750. Matrix.FromArray = function (array, offset) {
  5751. var result = new Matrix();
  5752. if (!offset) {
  5753. offset = 0;
  5754. }
  5755. Matrix.FromArrayToRef(array, offset, result);
  5756. return result;
  5757. };
  5758. /**
  5759. * Copy the content of an array into a given matrix
  5760. * @param array defines the source array
  5761. * @param offset defines an offset in the source array
  5762. * @param result defines the target matrix
  5763. */
  5764. Matrix.FromArrayToRef = function (array, offset, result) {
  5765. for (var index = 0; index < 16; index++) {
  5766. result.m[index] = array[index + offset];
  5767. }
  5768. result._markAsUpdated();
  5769. };
  5770. /**
  5771. * Stores an array into a matrix after having multiplied each component by a given factor
  5772. * @param array defines the source array
  5773. * @param offset defines the offset in the source array
  5774. * @param scale defines the scaling factor
  5775. * @param result defines the target matrix
  5776. */
  5777. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5778. for (var index = 0; index < 16; index++) {
  5779. result.m[index] = array[index + offset] * scale;
  5780. }
  5781. result._markAsUpdated();
  5782. };
  5783. /**
  5784. * Stores a list of values (16) inside a given matrix
  5785. * @param initialM11 defines 1st value of 1st row
  5786. * @param initialM12 defines 2nd value of 1st row
  5787. * @param initialM13 defines 3rd value of 1st row
  5788. * @param initialM14 defines 4th value of 1st row
  5789. * @param initialM21 defines 1st value of 2nd row
  5790. * @param initialM22 defines 2nd value of 2nd row
  5791. * @param initialM23 defines 3rd value of 2nd row
  5792. * @param initialM24 defines 4th value of 2nd row
  5793. * @param initialM31 defines 1st value of 3rd row
  5794. * @param initialM32 defines 2nd value of 3rd row
  5795. * @param initialM33 defines 3rd value of 3rd row
  5796. * @param initialM34 defines 4th value of 3rd row
  5797. * @param initialM41 defines 1st value of 4th row
  5798. * @param initialM42 defines 2nd value of 4th row
  5799. * @param initialM43 defines 3rd value of 4th row
  5800. * @param initialM44 defines 4th value of 4th row
  5801. * @param result defines the target matrix
  5802. */
  5803. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5804. result.m[0] = initialM11;
  5805. result.m[1] = initialM12;
  5806. result.m[2] = initialM13;
  5807. result.m[3] = initialM14;
  5808. result.m[4] = initialM21;
  5809. result.m[5] = initialM22;
  5810. result.m[6] = initialM23;
  5811. result.m[7] = initialM24;
  5812. result.m[8] = initialM31;
  5813. result.m[9] = initialM32;
  5814. result.m[10] = initialM33;
  5815. result.m[11] = initialM34;
  5816. result.m[12] = initialM41;
  5817. result.m[13] = initialM42;
  5818. result.m[14] = initialM43;
  5819. result.m[15] = initialM44;
  5820. result._markAsUpdated();
  5821. };
  5822. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5823. /**
  5824. * Gets an identity matrix that must not be updated
  5825. */
  5826. get: function () {
  5827. return Matrix._identityReadOnly;
  5828. },
  5829. enumerable: true,
  5830. configurable: true
  5831. });
  5832. /**
  5833. * Creates new matrix from a list of values (16)
  5834. * @param initialM11 defines 1st value of 1st row
  5835. * @param initialM12 defines 2nd value of 1st row
  5836. * @param initialM13 defines 3rd value of 1st row
  5837. * @param initialM14 defines 4th value of 1st row
  5838. * @param initialM21 defines 1st value of 2nd row
  5839. * @param initialM22 defines 2nd value of 2nd row
  5840. * @param initialM23 defines 3rd value of 2nd row
  5841. * @param initialM24 defines 4th value of 2nd row
  5842. * @param initialM31 defines 1st value of 3rd row
  5843. * @param initialM32 defines 2nd value of 3rd row
  5844. * @param initialM33 defines 3rd value of 3rd row
  5845. * @param initialM34 defines 4th value of 3rd row
  5846. * @param initialM41 defines 1st value of 4th row
  5847. * @param initialM42 defines 2nd value of 4th row
  5848. * @param initialM43 defines 3rd value of 4th row
  5849. * @param initialM44 defines 4th value of 4th row
  5850. * @returns the new matrix
  5851. */
  5852. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5853. var result = new Matrix();
  5854. result.m[0] = initialM11;
  5855. result.m[1] = initialM12;
  5856. result.m[2] = initialM13;
  5857. result.m[3] = initialM14;
  5858. result.m[4] = initialM21;
  5859. result.m[5] = initialM22;
  5860. result.m[6] = initialM23;
  5861. result.m[7] = initialM24;
  5862. result.m[8] = initialM31;
  5863. result.m[9] = initialM32;
  5864. result.m[10] = initialM33;
  5865. result.m[11] = initialM34;
  5866. result.m[12] = initialM41;
  5867. result.m[13] = initialM42;
  5868. result.m[14] = initialM43;
  5869. result.m[15] = initialM44;
  5870. return result;
  5871. };
  5872. /**
  5873. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5874. * @param scale defines the scale vector3
  5875. * @param rotation defines the rotation quaternion
  5876. * @param translation defines the translation vector3
  5877. * @returns a new matrix
  5878. */
  5879. Matrix.Compose = function (scale, rotation, translation) {
  5880. var result = Matrix.Identity();
  5881. Matrix.ComposeToRef(scale, rotation, translation, result);
  5882. return result;
  5883. };
  5884. /**
  5885. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5886. * @param scale defines the scale vector3
  5887. * @param rotation defines the rotation quaternion
  5888. * @param translation defines the translation vector3
  5889. * @param result defines the target matrix
  5890. */
  5891. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5892. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5893. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5894. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5895. result.setTranslation(translation);
  5896. };
  5897. /**
  5898. * Creates a new identity matrix
  5899. * @returns a new identity matrix
  5900. */
  5901. Matrix.Identity = function () {
  5902. 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);
  5903. };
  5904. /**
  5905. * Creates a new identity matrix and stores the result in a given matrix
  5906. * @param result defines the target matrix
  5907. */
  5908. Matrix.IdentityToRef = function (result) {
  5909. 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);
  5910. };
  5911. /**
  5912. * Creates a new zero matrix
  5913. * @returns a new zero matrix
  5914. */
  5915. Matrix.Zero = function () {
  5916. 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);
  5917. };
  5918. /**
  5919. * Creates a new rotation matrix for "angle" radians around the X axis
  5920. * @param angle defines the angle (in radians) to use
  5921. * @return the new matrix
  5922. */
  5923. Matrix.RotationX = function (angle) {
  5924. var result = new Matrix();
  5925. Matrix.RotationXToRef(angle, result);
  5926. return result;
  5927. };
  5928. /**
  5929. * Creates a new matrix as the invert of a given matrix
  5930. * @param source defines the source matrix
  5931. * @returns the new matrix
  5932. */
  5933. Matrix.Invert = function (source) {
  5934. var result = new Matrix();
  5935. source.invertToRef(result);
  5936. return result;
  5937. };
  5938. /**
  5939. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5940. * @param angle defines the angle (in radians) to use
  5941. * @param result defines the target matrix
  5942. */
  5943. Matrix.RotationXToRef = function (angle, result) {
  5944. var s = Math.sin(angle);
  5945. var c = Math.cos(angle);
  5946. result.m[0] = 1.0;
  5947. result.m[15] = 1.0;
  5948. result.m[5] = c;
  5949. result.m[10] = c;
  5950. result.m[9] = -s;
  5951. result.m[6] = s;
  5952. result.m[1] = 0.0;
  5953. result.m[2] = 0.0;
  5954. result.m[3] = 0.0;
  5955. result.m[4] = 0.0;
  5956. result.m[7] = 0.0;
  5957. result.m[8] = 0.0;
  5958. result.m[11] = 0.0;
  5959. result.m[12] = 0.0;
  5960. result.m[13] = 0.0;
  5961. result.m[14] = 0.0;
  5962. result._markAsUpdated();
  5963. };
  5964. /**
  5965. * Creates a new rotation matrix for "angle" radians around the Y axis
  5966. * @param angle defines the angle (in radians) to use
  5967. * @return the new matrix
  5968. */
  5969. Matrix.RotationY = function (angle) {
  5970. var result = new Matrix();
  5971. Matrix.RotationYToRef(angle, result);
  5972. return result;
  5973. };
  5974. /**
  5975. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5976. * @param angle defines the angle (in radians) to use
  5977. * @param result defines the target matrix
  5978. */
  5979. Matrix.RotationYToRef = function (angle, result) {
  5980. var s = Math.sin(angle);
  5981. var c = Math.cos(angle);
  5982. result.m[5] = 1.0;
  5983. result.m[15] = 1.0;
  5984. result.m[0] = c;
  5985. result.m[2] = -s;
  5986. result.m[8] = s;
  5987. result.m[10] = c;
  5988. result.m[1] = 0.0;
  5989. result.m[3] = 0.0;
  5990. result.m[4] = 0.0;
  5991. result.m[6] = 0.0;
  5992. result.m[7] = 0.0;
  5993. result.m[9] = 0.0;
  5994. result.m[11] = 0.0;
  5995. result.m[12] = 0.0;
  5996. result.m[13] = 0.0;
  5997. result.m[14] = 0.0;
  5998. result._markAsUpdated();
  5999. };
  6000. /**
  6001. * Creates a new rotation matrix for "angle" radians around the Z axis
  6002. * @param angle defines the angle (in radians) to use
  6003. * @return the new matrix
  6004. */
  6005. Matrix.RotationZ = function (angle) {
  6006. var result = new Matrix();
  6007. Matrix.RotationZToRef(angle, result);
  6008. return result;
  6009. };
  6010. /**
  6011. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6012. * @param angle defines the angle (in radians) to use
  6013. * @param result defines the target matrix
  6014. */
  6015. Matrix.RotationZToRef = function (angle, result) {
  6016. var s = Math.sin(angle);
  6017. var c = Math.cos(angle);
  6018. result.m[10] = 1.0;
  6019. result.m[15] = 1.0;
  6020. result.m[0] = c;
  6021. result.m[1] = s;
  6022. result.m[4] = -s;
  6023. result.m[5] = c;
  6024. result.m[2] = 0.0;
  6025. result.m[3] = 0.0;
  6026. result.m[6] = 0.0;
  6027. result.m[7] = 0.0;
  6028. result.m[8] = 0.0;
  6029. result.m[9] = 0.0;
  6030. result.m[11] = 0.0;
  6031. result.m[12] = 0.0;
  6032. result.m[13] = 0.0;
  6033. result.m[14] = 0.0;
  6034. result._markAsUpdated();
  6035. };
  6036. /**
  6037. * Creates a new rotation matrix for "angle" radians around the given axis
  6038. * @param axis defines the axis to use
  6039. * @param angle defines the angle (in radians) to use
  6040. * @return the new matrix
  6041. */
  6042. Matrix.RotationAxis = function (axis, angle) {
  6043. var result = Matrix.Zero();
  6044. Matrix.RotationAxisToRef(axis, angle, result);
  6045. return result;
  6046. };
  6047. /**
  6048. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6049. * @param axis defines the axis to use
  6050. * @param angle defines the angle (in radians) to use
  6051. * @param result defines the target matrix
  6052. */
  6053. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6054. var s = Math.sin(-angle);
  6055. var c = Math.cos(-angle);
  6056. var c1 = 1 - c;
  6057. axis.normalize();
  6058. result.m[0] = (axis.x * axis.x) * c1 + c;
  6059. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6060. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6061. result.m[3] = 0.0;
  6062. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6063. result.m[5] = (axis.y * axis.y) * c1 + c;
  6064. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6065. result.m[7] = 0.0;
  6066. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6067. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6068. result.m[10] = (axis.z * axis.z) * c1 + c;
  6069. result.m[11] = 0.0;
  6070. result.m[15] = 1.0;
  6071. result._markAsUpdated();
  6072. };
  6073. /**
  6074. * Creates a rotation matrix
  6075. * @param yaw defines the yaw angle in radians (Y axis)
  6076. * @param pitch defines the pitch angle in radians (X axis)
  6077. * @param roll defines the roll angle in radians (X axis)
  6078. * @returns the new rotation matrix
  6079. */
  6080. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6081. var result = new Matrix();
  6082. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6083. return result;
  6084. };
  6085. /**
  6086. * Creates a rotation matrix and stores it in a given matrix
  6087. * @param yaw defines the yaw angle in radians (Y axis)
  6088. * @param pitch defines the pitch angle in radians (X axis)
  6089. * @param roll defines the roll angle in radians (X axis)
  6090. * @param result defines the target matrix
  6091. */
  6092. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6093. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6094. this._tempQuaternion.toRotationMatrix(result);
  6095. };
  6096. /**
  6097. * Creates a scaling matrix
  6098. * @param x defines the scale factor on X axis
  6099. * @param y defines the scale factor on Y axis
  6100. * @param z defines the scale factor on Z axis
  6101. * @returns the new matrix
  6102. */
  6103. Matrix.Scaling = function (x, y, z) {
  6104. var result = Matrix.Zero();
  6105. Matrix.ScalingToRef(x, y, z, result);
  6106. return result;
  6107. };
  6108. /**
  6109. * Creates a scaling matrix and stores it in a given matrix
  6110. * @param x defines the scale factor on X axis
  6111. * @param y defines the scale factor on Y axis
  6112. * @param z defines the scale factor on Z axis
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.ScalingToRef = function (x, y, z, result) {
  6116. result.m[0] = x;
  6117. result.m[1] = 0.0;
  6118. result.m[2] = 0.0;
  6119. result.m[3] = 0.0;
  6120. result.m[4] = 0.0;
  6121. result.m[5] = y;
  6122. result.m[6] = 0.0;
  6123. result.m[7] = 0.0;
  6124. result.m[8] = 0.0;
  6125. result.m[9] = 0.0;
  6126. result.m[10] = z;
  6127. result.m[11] = 0.0;
  6128. result.m[12] = 0.0;
  6129. result.m[13] = 0.0;
  6130. result.m[14] = 0.0;
  6131. result.m[15] = 1.0;
  6132. result._markAsUpdated();
  6133. };
  6134. /**
  6135. * Creates a translation matrix
  6136. * @param x defines the translation on X axis
  6137. * @param y defines the translation on Y axis
  6138. * @param z defines the translationon Z axis
  6139. * @returns the new matrix
  6140. */
  6141. Matrix.Translation = function (x, y, z) {
  6142. var result = Matrix.Identity();
  6143. Matrix.TranslationToRef(x, y, z, result);
  6144. return result;
  6145. };
  6146. /**
  6147. * Creates a translation matrix and stores it in a given matrix
  6148. * @param x defines the translation on X axis
  6149. * @param y defines the translation on Y axis
  6150. * @param z defines the translationon Z axis
  6151. * @param result defines the target matrix
  6152. */
  6153. Matrix.TranslationToRef = function (x, y, z, result) {
  6154. 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);
  6155. };
  6156. /**
  6157. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6158. * @param startValue defines the start value
  6159. * @param endValue defines the end value
  6160. * @param gradient defines the gradient factor
  6161. * @returns the new matrix
  6162. */
  6163. Matrix.Lerp = function (startValue, endValue, gradient) {
  6164. var result = Matrix.Zero();
  6165. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6166. return result;
  6167. };
  6168. /**
  6169. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6170. * @param startValue defines the start value
  6171. * @param endValue defines the end value
  6172. * @param gradient defines the gradient factor
  6173. * @param result defines the Matrix object where to store data
  6174. */
  6175. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6176. for (var index = 0; index < 16; index++) {
  6177. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6178. }
  6179. result._markAsUpdated();
  6180. };
  6181. /**
  6182. * Builds a new matrix whose values are computed by:
  6183. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6184. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6185. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6186. * @param startValue defines the first matrix
  6187. * @param endValue defines the second matrix
  6188. * @param gradient defines the gradient between the two matrices
  6189. * @returns the new matrix
  6190. */
  6191. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6192. var result = Matrix.Zero();
  6193. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6194. return result;
  6195. };
  6196. /**
  6197. * Update a matrix to values which are computed by:
  6198. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6199. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6200. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6201. * @param startValue defines the first matrix
  6202. * @param endValue defines the second matrix
  6203. * @param gradient defines the gradient between the two matrices
  6204. * @param result defines the target matrix
  6205. */
  6206. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6207. var startScale = MathTmp.Vector3[0];
  6208. var startRotation = MathTmp.Quaternion[0];
  6209. var startTranslation = MathTmp.Vector3[1];
  6210. startValue.decompose(startScale, startRotation, startTranslation);
  6211. var endScale = MathTmp.Vector3[2];
  6212. var endRotation = MathTmp.Quaternion[1];
  6213. var endTranslation = MathTmp.Vector3[3];
  6214. endValue.decompose(endScale, endRotation, endTranslation);
  6215. var resultScale = MathTmp.Vector3[4];
  6216. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6217. var resultRotation = MathTmp.Quaternion[2];
  6218. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6219. var resultTranslation = MathTmp.Vector3[5];
  6220. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6221. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6222. };
  6223. /**
  6224. * 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"
  6225. * This function works in left handed mode
  6226. * @param eye defines the final position of the entity
  6227. * @param target defines where the entity should look at
  6228. * @param up defines the up vector for the entity
  6229. * @returns the new matrix
  6230. */
  6231. Matrix.LookAtLH = function (eye, target, up) {
  6232. var result = Matrix.Zero();
  6233. Matrix.LookAtLHToRef(eye, target, up, result);
  6234. return result;
  6235. };
  6236. /**
  6237. * 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".
  6238. * This function works in left handed mode
  6239. * @param eye defines the final position of the entity
  6240. * @param target defines where the entity should look at
  6241. * @param up defines the up vector for the entity
  6242. * @param result defines the target matrix
  6243. */
  6244. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6245. // Z axis
  6246. target.subtractToRef(eye, this._zAxis);
  6247. this._zAxis.normalize();
  6248. // X axis
  6249. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6250. if (this._xAxis.lengthSquared() === 0) {
  6251. this._xAxis.x = 1.0;
  6252. }
  6253. else {
  6254. this._xAxis.normalize();
  6255. }
  6256. // Y axis
  6257. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6258. this._yAxis.normalize();
  6259. // Eye angles
  6260. var ex = -Vector3.Dot(this._xAxis, eye);
  6261. var ey = -Vector3.Dot(this._yAxis, eye);
  6262. var ez = -Vector3.Dot(this._zAxis, eye);
  6263. 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);
  6264. };
  6265. /**
  6266. * 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"
  6267. * This function works in right handed mode
  6268. * @param eye defines the final position of the entity
  6269. * @param target defines where the entity should look at
  6270. * @param up defines the up vector for the entity
  6271. * @returns the new matrix
  6272. */
  6273. Matrix.LookAtRH = function (eye, target, up) {
  6274. var result = Matrix.Zero();
  6275. Matrix.LookAtRHToRef(eye, target, up, result);
  6276. return result;
  6277. };
  6278. /**
  6279. * 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".
  6280. * This function works in right handed mode
  6281. * @param eye defines the final position of the entity
  6282. * @param target defines where the entity should look at
  6283. * @param up defines the up vector for the entity
  6284. * @param result defines the target matrix
  6285. */
  6286. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6287. // Z axis
  6288. eye.subtractToRef(target, this._zAxis);
  6289. this._zAxis.normalize();
  6290. // X axis
  6291. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6292. if (this._xAxis.lengthSquared() === 0) {
  6293. this._xAxis.x = 1.0;
  6294. }
  6295. else {
  6296. this._xAxis.normalize();
  6297. }
  6298. // Y axis
  6299. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6300. this._yAxis.normalize();
  6301. // Eye angles
  6302. var ex = -Vector3.Dot(this._xAxis, eye);
  6303. var ey = -Vector3.Dot(this._yAxis, eye);
  6304. var ez = -Vector3.Dot(this._zAxis, eye);
  6305. 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);
  6306. };
  6307. /**
  6308. * Create a left-handed orthographic projection matrix
  6309. * @param width defines the viewport width
  6310. * @param height defines the viewport height
  6311. * @param znear defines the near clip plane
  6312. * @param zfar defines the far clip plane
  6313. * @returns a new matrix as a left-handed orthographic projection matrix
  6314. */
  6315. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6316. var matrix = Matrix.Zero();
  6317. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6318. return matrix;
  6319. };
  6320. /**
  6321. * Store a left-handed orthographic projection to a given matrix
  6322. * @param width defines the viewport width
  6323. * @param height defines the viewport height
  6324. * @param znear defines the near clip plane
  6325. * @param zfar defines the far clip plane
  6326. * @param result defines the target matrix
  6327. */
  6328. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6329. var n = znear;
  6330. var f = zfar;
  6331. var a = 2.0 / width;
  6332. var b = 2.0 / height;
  6333. var c = 2.0 / (f - n);
  6334. var d = -(f + n) / (f - n);
  6335. 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);
  6336. };
  6337. /**
  6338. * Create a left-handed orthographic projection matrix
  6339. * @param left defines the viewport left coordinate
  6340. * @param right defines the viewport right coordinate
  6341. * @param bottom defines the viewport bottom coordinate
  6342. * @param top defines the viewport top coordinate
  6343. * @param znear defines the near clip plane
  6344. * @param zfar defines the far clip plane
  6345. * @returns a new matrix as a left-handed orthographic projection matrix
  6346. */
  6347. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6348. var matrix = Matrix.Zero();
  6349. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6350. return matrix;
  6351. };
  6352. /**
  6353. * Stores a left-handed orthographic projection into a given matrix
  6354. * @param left defines the viewport left coordinate
  6355. * @param right defines the viewport right coordinate
  6356. * @param bottom defines the viewport bottom coordinate
  6357. * @param top defines the viewport top coordinate
  6358. * @param znear defines the near clip plane
  6359. * @param zfar defines the far clip plane
  6360. * @param result defines the target matrix
  6361. */
  6362. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6363. var n = znear;
  6364. var f = zfar;
  6365. var a = 2.0 / (right - left);
  6366. var b = 2.0 / (top - bottom);
  6367. var c = 2.0 / (f - n);
  6368. var d = -(f + n) / (f - n);
  6369. var i0 = (left + right) / (left - right);
  6370. var i1 = (top + bottom) / (bottom - top);
  6371. 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);
  6372. };
  6373. /**
  6374. * Creates a right-handed orthographic projection matrix
  6375. * @param left defines the viewport left coordinate
  6376. * @param right defines the viewport right coordinate
  6377. * @param bottom defines the viewport bottom coordinate
  6378. * @param top defines the viewport top coordinate
  6379. * @param znear defines the near clip plane
  6380. * @param zfar defines the far clip plane
  6381. * @returns a new matrix as a right-handed orthographic projection matrix
  6382. */
  6383. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6384. var matrix = Matrix.Zero();
  6385. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6386. return matrix;
  6387. };
  6388. /**
  6389. * Stores a right-handed orthographic projection into a given matrix
  6390. * @param left defines the viewport left coordinate
  6391. * @param right defines the viewport right coordinate
  6392. * @param bottom defines the viewport bottom coordinate
  6393. * @param top defines the viewport top coordinate
  6394. * @param znear defines the near clip plane
  6395. * @param zfar defines the far clip plane
  6396. * @param result defines the target matrix
  6397. */
  6398. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6399. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6400. result.m[10] *= -1.0;
  6401. };
  6402. /**
  6403. * Creates a left-handed perspective projection matrix
  6404. * @param width defines the viewport width
  6405. * @param height defines the viewport height
  6406. * @param znear defines the near clip plane
  6407. * @param zfar defines the far clip plane
  6408. * @returns a new matrix as a left-handed perspective projection matrix
  6409. */
  6410. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6411. var matrix = Matrix.Zero();
  6412. var n = znear;
  6413. var f = zfar;
  6414. var a = 2.0 * n / width;
  6415. var b = 2.0 * n / height;
  6416. var c = (f + n) / (f - n);
  6417. var d = -2.0 * f * n / (f - n);
  6418. 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);
  6419. return matrix;
  6420. };
  6421. /**
  6422. * Creates a left-handed perspective projection matrix
  6423. * @param fov defines the horizontal field of view
  6424. * @param aspect defines the aspect ratio
  6425. * @param znear defines the near clip plane
  6426. * @param zfar defines the far clip plane
  6427. * @returns a new matrix as a left-handed perspective projection matrix
  6428. */
  6429. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6430. var matrix = Matrix.Zero();
  6431. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6432. return matrix;
  6433. };
  6434. /**
  6435. * Stores a left-handed perspective projection into a given matrix
  6436. * @param fov defines the horizontal field of view
  6437. * @param aspect defines the aspect ratio
  6438. * @param znear defines the near clip plane
  6439. * @param zfar defines the far clip plane
  6440. * @param result defines the target matrix
  6441. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6442. */
  6443. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6444. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6445. var n = znear;
  6446. var f = zfar;
  6447. var t = 1.0 / (Math.tan(fov * 0.5));
  6448. var a = isVerticalFovFixed ? (t / aspect) : t;
  6449. var b = isVerticalFovFixed ? t : (t * aspect);
  6450. var c = (f + n) / (f - n);
  6451. var d = -2.0 * f * n / (f - n);
  6452. 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);
  6453. };
  6454. /**
  6455. * Creates a right-handed perspective projection matrix
  6456. * @param fov defines the horizontal field of view
  6457. * @param aspect defines the aspect ratio
  6458. * @param znear defines the near clip plane
  6459. * @param zfar defines the far clip plane
  6460. * @returns a new matrix as a right-handed perspective projection matrix
  6461. */
  6462. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6463. var matrix = Matrix.Zero();
  6464. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6465. return matrix;
  6466. };
  6467. /**
  6468. * Stores a right-handed perspective projection into a given matrix
  6469. * @param fov defines the horizontal field of view
  6470. * @param aspect defines the aspect ratio
  6471. * @param znear defines the near clip plane
  6472. * @param zfar defines the far clip plane
  6473. * @param result defines the target matrix
  6474. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6475. */
  6476. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6477. //alternatively this could be expressed as:
  6478. // m = PerspectiveFovLHToRef
  6479. // m[10] *= -1.0;
  6480. // m[11] *= -1.0;
  6481. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6482. var n = znear;
  6483. var f = zfar;
  6484. var t = 1.0 / (Math.tan(fov * 0.5));
  6485. var a = isVerticalFovFixed ? (t / aspect) : t;
  6486. var b = isVerticalFovFixed ? t : (t * aspect);
  6487. var c = -(f + n) / (f - n);
  6488. var d = -2 * f * n / (f - n);
  6489. 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);
  6490. };
  6491. /**
  6492. * Stores a perspective projection for WebVR info a given matrix
  6493. * @param fov defines the field of view
  6494. * @param znear defines the near clip plane
  6495. * @param zfar defines the far clip plane
  6496. * @param result defines the target matrix
  6497. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6498. */
  6499. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6500. if (rightHanded === void 0) { rightHanded = false; }
  6501. var rightHandedFactor = rightHanded ? -1 : 1;
  6502. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6503. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6504. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6505. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6506. var xScale = 2.0 / (leftTan + rightTan);
  6507. var yScale = 2.0 / (upTan + downTan);
  6508. result.m[0] = xScale;
  6509. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6510. result.m[5] = yScale;
  6511. result.m[6] = result.m[7] = 0.0;
  6512. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6513. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6514. result.m[10] = -zfar / (znear - zfar);
  6515. result.m[11] = 1.0 * rightHandedFactor;
  6516. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6517. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6518. result._markAsUpdated();
  6519. };
  6520. /**
  6521. * Computes a complete transformation matrix
  6522. * @param viewport defines the viewport to use
  6523. * @param world defines the world matrix
  6524. * @param view defines the view matrix
  6525. * @param projection defines the projection matrix
  6526. * @param zmin defines the near clip plane
  6527. * @param zmax defines the far clip plane
  6528. * @returns the transformation matrix
  6529. */
  6530. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6531. var cw = viewport.width;
  6532. var ch = viewport.height;
  6533. var cx = viewport.x;
  6534. var cy = viewport.y;
  6535. 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);
  6536. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6537. };
  6538. /**
  6539. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6540. * @param matrix defines the matrix to use
  6541. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6542. */
  6543. Matrix.GetAsMatrix2x2 = function (matrix) {
  6544. return new Float32Array([
  6545. matrix.m[0], matrix.m[1],
  6546. matrix.m[4], matrix.m[5]
  6547. ]);
  6548. };
  6549. /**
  6550. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6551. * @param matrix defines the matrix to use
  6552. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6553. */
  6554. Matrix.GetAsMatrix3x3 = function (matrix) {
  6555. return new Float32Array([
  6556. matrix.m[0], matrix.m[1], matrix.m[2],
  6557. matrix.m[4], matrix.m[5], matrix.m[6],
  6558. matrix.m[8], matrix.m[9], matrix.m[10]
  6559. ]);
  6560. };
  6561. /**
  6562. * Compute the transpose of a given matrix
  6563. * @param matrix defines the matrix to transpose
  6564. * @returns the new matrix
  6565. */
  6566. Matrix.Transpose = function (matrix) {
  6567. var result = new Matrix();
  6568. Matrix.TransposeToRef(matrix, result);
  6569. return result;
  6570. };
  6571. /**
  6572. * Compute the transpose of a matrix and store it in a target matrix
  6573. * @param matrix defines the matrix to transpose
  6574. * @param result defines the target matrix
  6575. */
  6576. Matrix.TransposeToRef = function (matrix, result) {
  6577. result.m[0] = matrix.m[0];
  6578. result.m[1] = matrix.m[4];
  6579. result.m[2] = matrix.m[8];
  6580. result.m[3] = matrix.m[12];
  6581. result.m[4] = matrix.m[1];
  6582. result.m[5] = matrix.m[5];
  6583. result.m[6] = matrix.m[9];
  6584. result.m[7] = matrix.m[13];
  6585. result.m[8] = matrix.m[2];
  6586. result.m[9] = matrix.m[6];
  6587. result.m[10] = matrix.m[10];
  6588. result.m[11] = matrix.m[14];
  6589. result.m[12] = matrix.m[3];
  6590. result.m[13] = matrix.m[7];
  6591. result.m[14] = matrix.m[11];
  6592. result.m[15] = matrix.m[15];
  6593. };
  6594. /**
  6595. * Computes a reflection matrix from a plane
  6596. * @param plane defines the reflection plane
  6597. * @returns a new matrix
  6598. */
  6599. Matrix.Reflection = function (plane) {
  6600. var matrix = new Matrix();
  6601. Matrix.ReflectionToRef(plane, matrix);
  6602. return matrix;
  6603. };
  6604. /**
  6605. * Computes a reflection matrix from a plane
  6606. * @param plane defines the reflection plane
  6607. * @param result defines the target matrix
  6608. */
  6609. Matrix.ReflectionToRef = function (plane, result) {
  6610. plane.normalize();
  6611. var x = plane.normal.x;
  6612. var y = plane.normal.y;
  6613. var z = plane.normal.z;
  6614. var temp = -2 * x;
  6615. var temp2 = -2 * y;
  6616. var temp3 = -2 * z;
  6617. result.m[0] = (temp * x) + 1;
  6618. result.m[1] = temp2 * x;
  6619. result.m[2] = temp3 * x;
  6620. result.m[3] = 0.0;
  6621. result.m[4] = temp * y;
  6622. result.m[5] = (temp2 * y) + 1;
  6623. result.m[6] = temp3 * y;
  6624. result.m[7] = 0.0;
  6625. result.m[8] = temp * z;
  6626. result.m[9] = temp2 * z;
  6627. result.m[10] = (temp3 * z) + 1;
  6628. result.m[11] = 0.0;
  6629. result.m[12] = temp * plane.d;
  6630. result.m[13] = temp2 * plane.d;
  6631. result.m[14] = temp3 * plane.d;
  6632. result.m[15] = 1.0;
  6633. result._markAsUpdated();
  6634. };
  6635. /**
  6636. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6637. * @param xaxis defines the value of the 1st axis
  6638. * @param yaxis defines the value of the 2nd axis
  6639. * @param zaxis defines the value of the 3rd axis
  6640. * @param result defines the target matrix
  6641. */
  6642. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6643. result.m[0] = xaxis.x;
  6644. result.m[1] = xaxis.y;
  6645. result.m[2] = xaxis.z;
  6646. result.m[3] = 0.0;
  6647. result.m[4] = yaxis.x;
  6648. result.m[5] = yaxis.y;
  6649. result.m[6] = yaxis.z;
  6650. result.m[7] = 0.0;
  6651. result.m[8] = zaxis.x;
  6652. result.m[9] = zaxis.y;
  6653. result.m[10] = zaxis.z;
  6654. result.m[11] = 0.0;
  6655. result.m[12] = 0.0;
  6656. result.m[13] = 0.0;
  6657. result.m[14] = 0.0;
  6658. result.m[15] = 1.0;
  6659. result._markAsUpdated();
  6660. };
  6661. /**
  6662. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6663. * @param quat defines the quaternion to use
  6664. * @param result defines the target matrix
  6665. */
  6666. Matrix.FromQuaternionToRef = function (quat, result) {
  6667. var xx = quat.x * quat.x;
  6668. var yy = quat.y * quat.y;
  6669. var zz = quat.z * quat.z;
  6670. var xy = quat.x * quat.y;
  6671. var zw = quat.z * quat.w;
  6672. var zx = quat.z * quat.x;
  6673. var yw = quat.y * quat.w;
  6674. var yz = quat.y * quat.z;
  6675. var xw = quat.x * quat.w;
  6676. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6677. result.m[1] = 2.0 * (xy + zw);
  6678. result.m[2] = 2.0 * (zx - yw);
  6679. result.m[3] = 0.0;
  6680. result.m[4] = 2.0 * (xy - zw);
  6681. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6682. result.m[6] = 2.0 * (yz + xw);
  6683. result.m[7] = 0.0;
  6684. result.m[8] = 2.0 * (zx + yw);
  6685. result.m[9] = 2.0 * (yz - xw);
  6686. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6687. result.m[11] = 0.0;
  6688. result.m[12] = 0.0;
  6689. result.m[13] = 0.0;
  6690. result.m[14] = 0.0;
  6691. result.m[15] = 1.0;
  6692. result._markAsUpdated();
  6693. };
  6694. Matrix._tempQuaternion = new Quaternion();
  6695. Matrix._xAxis = Vector3.Zero();
  6696. Matrix._yAxis = Vector3.Zero();
  6697. Matrix._zAxis = Vector3.Zero();
  6698. Matrix._updateFlagSeed = 0;
  6699. Matrix._identityReadOnly = Matrix.Identity();
  6700. return Matrix;
  6701. }());
  6702. BABYLON.Matrix = Matrix;
  6703. var Plane = /** @class */ (function () {
  6704. /**
  6705. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6706. */
  6707. function Plane(a, b, c, d) {
  6708. this.normal = new Vector3(a, b, c);
  6709. this.d = d;
  6710. }
  6711. /**
  6712. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6713. */
  6714. Plane.prototype.asArray = function () {
  6715. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6716. };
  6717. // Methods
  6718. /**
  6719. * Returns a new plane copied from the current Plane.
  6720. */
  6721. Plane.prototype.clone = function () {
  6722. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6723. };
  6724. /**
  6725. * Returns the string "Plane".
  6726. */
  6727. Plane.prototype.getClassName = function () {
  6728. return "Plane";
  6729. };
  6730. /**
  6731. * Returns the Plane hash code.
  6732. */
  6733. Plane.prototype.getHashCode = function () {
  6734. var hash = this.normal.getHashCode();
  6735. hash = (hash * 397) ^ (this.d || 0);
  6736. return hash;
  6737. };
  6738. /**
  6739. * Normalize the current Plane in place.
  6740. * Returns the updated Plane.
  6741. */
  6742. Plane.prototype.normalize = function () {
  6743. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6744. var magnitude = 0.0;
  6745. if (norm !== 0) {
  6746. magnitude = 1.0 / norm;
  6747. }
  6748. this.normal.x *= magnitude;
  6749. this.normal.y *= magnitude;
  6750. this.normal.z *= magnitude;
  6751. this.d *= magnitude;
  6752. return this;
  6753. };
  6754. /**
  6755. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6756. */
  6757. Plane.prototype.transform = function (transformation) {
  6758. var transposedMatrix = Matrix.Transpose(transformation);
  6759. var x = this.normal.x;
  6760. var y = this.normal.y;
  6761. var z = this.normal.z;
  6762. var d = this.d;
  6763. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6764. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6765. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6766. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6767. return new Plane(normalX, normalY, normalZ, finalD);
  6768. };
  6769. /**
  6770. * Returns the dot product (float) of the point coordinates and the plane normal.
  6771. */
  6772. Plane.prototype.dotCoordinate = function (point) {
  6773. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6774. };
  6775. /**
  6776. * Updates the current Plane from the plane defined by the three given points.
  6777. * Returns the updated Plane.
  6778. */
  6779. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6780. var x1 = point2.x - point1.x;
  6781. var y1 = point2.y - point1.y;
  6782. var z1 = point2.z - point1.z;
  6783. var x2 = point3.x - point1.x;
  6784. var y2 = point3.y - point1.y;
  6785. var z2 = point3.z - point1.z;
  6786. var yz = (y1 * z2) - (z1 * y2);
  6787. var xz = (z1 * x2) - (x1 * z2);
  6788. var xy = (x1 * y2) - (y1 * x2);
  6789. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6790. var invPyth;
  6791. if (pyth !== 0) {
  6792. invPyth = 1.0 / pyth;
  6793. }
  6794. else {
  6795. invPyth = 0.0;
  6796. }
  6797. this.normal.x = yz * invPyth;
  6798. this.normal.y = xz * invPyth;
  6799. this.normal.z = xy * invPyth;
  6800. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6801. return this;
  6802. };
  6803. /**
  6804. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6805. */
  6806. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6807. var dot = Vector3.Dot(this.normal, direction);
  6808. return (dot <= epsilon);
  6809. };
  6810. /**
  6811. * Returns the signed distance (float) from the given point to the Plane.
  6812. */
  6813. Plane.prototype.signedDistanceTo = function (point) {
  6814. return Vector3.Dot(point, this.normal) + this.d;
  6815. };
  6816. // Statics
  6817. /**
  6818. * Returns a new Plane from the given array.
  6819. */
  6820. Plane.FromArray = function (array) {
  6821. return new Plane(array[0], array[1], array[2], array[3]);
  6822. };
  6823. /**
  6824. * Returns a new Plane defined by the three given points.
  6825. */
  6826. Plane.FromPoints = function (point1, point2, point3) {
  6827. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6828. result.copyFromPoints(point1, point2, point3);
  6829. return result;
  6830. };
  6831. /**
  6832. * Returns a new Plane the normal vector to this plane at the given origin point.
  6833. * Note : the vector "normal" is updated because normalized.
  6834. */
  6835. Plane.FromPositionAndNormal = function (origin, normal) {
  6836. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6837. normal.normalize();
  6838. result.normal = normal;
  6839. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6840. return result;
  6841. };
  6842. /**
  6843. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6844. */
  6845. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6846. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6847. return Vector3.Dot(point, normal) + d;
  6848. };
  6849. return Plane;
  6850. }());
  6851. BABYLON.Plane = Plane;
  6852. /**
  6853. * Class used to represent a viewport on screen
  6854. */
  6855. var Viewport = /** @class */ (function () {
  6856. /**
  6857. * Creates a Viewport object located at (x, y) and sized (width, height)
  6858. * @param x defines viewport left coordinate
  6859. * @param y defines viewport top coordinate
  6860. * @param width defines the viewport width
  6861. * @param height defines the viewport height
  6862. */
  6863. function Viewport(
  6864. /** viewport left coordinate */
  6865. x,
  6866. /** viewport top coordinate */
  6867. y,
  6868. /**viewport width */
  6869. width,
  6870. /** viewport height */
  6871. height) {
  6872. this.x = x;
  6873. this.y = y;
  6874. this.width = width;
  6875. this.height = height;
  6876. }
  6877. /**
  6878. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  6879. * @param renderWidthOrEngine defines either an engine or the rendering width
  6880. * @param renderHeight defines the rendering height
  6881. * @returns a new Viewport
  6882. */
  6883. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6884. if (renderWidthOrEngine.getRenderWidth) {
  6885. var engine = renderWidthOrEngine;
  6886. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6887. }
  6888. var renderWidth = renderWidthOrEngine;
  6889. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6890. };
  6891. /**
  6892. * Returns a new Viewport copied from the current one
  6893. * @returns a new Viewport
  6894. */
  6895. Viewport.prototype.clone = function () {
  6896. return new Viewport(this.x, this.y, this.width, this.height);
  6897. };
  6898. return Viewport;
  6899. }());
  6900. BABYLON.Viewport = Viewport;
  6901. var Frustum = /** @class */ (function () {
  6902. function Frustum() {
  6903. }
  6904. /**
  6905. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6906. */
  6907. Frustum.GetPlanes = function (transform) {
  6908. var frustumPlanes = [];
  6909. for (var index = 0; index < 6; index++) {
  6910. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6911. }
  6912. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6913. return frustumPlanes;
  6914. };
  6915. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6916. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6917. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6918. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6919. frustumPlane.d = transform.m[15] + transform.m[14];
  6920. frustumPlane.normalize();
  6921. };
  6922. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6923. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6924. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6925. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6926. frustumPlane.d = transform.m[15] - transform.m[14];
  6927. frustumPlane.normalize();
  6928. };
  6929. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6930. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6931. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6932. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6933. frustumPlane.d = transform.m[15] + transform.m[12];
  6934. frustumPlane.normalize();
  6935. };
  6936. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6937. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6938. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6939. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6940. frustumPlane.d = transform.m[15] - transform.m[12];
  6941. frustumPlane.normalize();
  6942. };
  6943. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6944. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6945. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6946. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6947. frustumPlane.d = transform.m[15] - transform.m[13];
  6948. frustumPlane.normalize();
  6949. };
  6950. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6951. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6952. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6953. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6954. frustumPlane.d = transform.m[15] + transform.m[13];
  6955. frustumPlane.normalize();
  6956. };
  6957. /**
  6958. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6959. */
  6960. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6961. // Near
  6962. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6963. // Far
  6964. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6965. // Left
  6966. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6967. // Right
  6968. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6969. // Top
  6970. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6971. // Bottom
  6972. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6973. };
  6974. return Frustum;
  6975. }());
  6976. BABYLON.Frustum = Frustum;
  6977. /** Defines supported spaces */
  6978. var Space;
  6979. (function (Space) {
  6980. /** Local (object) space */
  6981. Space[Space["LOCAL"] = 0] = "LOCAL";
  6982. /** World space */
  6983. Space[Space["WORLD"] = 1] = "WORLD";
  6984. /** Bone space */
  6985. Space[Space["BONE"] = 2] = "BONE";
  6986. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6987. /** Defines the 3 main axes */
  6988. var Axis = /** @class */ (function () {
  6989. function Axis() {
  6990. }
  6991. /** X axis */
  6992. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6993. /** Y axis */
  6994. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6995. /** Z axis */
  6996. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6997. return Axis;
  6998. }());
  6999. BABYLON.Axis = Axis;
  7000. ;
  7001. /** Class used to represent a Bezier curve */
  7002. var BezierCurve = /** @class */ (function () {
  7003. function BezierCurve() {
  7004. }
  7005. /**
  7006. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7007. * @param t defines the time
  7008. * @param x1 defines the left coordinate on X axis
  7009. * @param y1 defines the left coordinate on Y axis
  7010. * @param x2 defines the right coordinate on X axis
  7011. * @param y2 defines the right coordinate on Y axis
  7012. * @returns the interpolated value
  7013. */
  7014. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7015. // Extract X (which is equal to time here)
  7016. var f0 = 1 - 3 * x2 + 3 * x1;
  7017. var f1 = 3 * x2 - 6 * x1;
  7018. var f2 = 3 * x1;
  7019. var refinedT = t;
  7020. for (var i = 0; i < 5; i++) {
  7021. var refinedT2 = refinedT * refinedT;
  7022. var refinedT3 = refinedT2 * refinedT;
  7023. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7024. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7025. refinedT -= (x - t) * slope;
  7026. refinedT = Math.min(1, Math.max(0, refinedT));
  7027. }
  7028. // Resolve cubic bezier for the given x
  7029. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7030. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7031. Math.pow(refinedT, 3);
  7032. };
  7033. return BezierCurve;
  7034. }());
  7035. BABYLON.BezierCurve = BezierCurve;
  7036. /**
  7037. * Defines potential orientation for back face culling
  7038. */
  7039. var Orientation;
  7040. (function (Orientation) {
  7041. /**
  7042. * Clockwise
  7043. */
  7044. Orientation[Orientation["CW"] = 0] = "CW";
  7045. /** Counter clockwise */
  7046. Orientation[Orientation["CCW"] = 1] = "CCW";
  7047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7048. /**
  7049. * Defines angle representation
  7050. */
  7051. var Angle = /** @class */ (function () {
  7052. /**
  7053. * Creates an Angle object of "radians" radians (float).
  7054. */
  7055. function Angle(radians) {
  7056. this._radians = radians;
  7057. if (this._radians < 0.0)
  7058. this._radians += (2.0 * Math.PI);
  7059. }
  7060. /**
  7061. * Get value in degrees
  7062. * @returns the Angle value in degrees (float)
  7063. */
  7064. Angle.prototype.degrees = function () {
  7065. return this._radians * 180.0 / Math.PI;
  7066. };
  7067. /**
  7068. * Get value in radians
  7069. * @returns the Angle value in radians (float)
  7070. */
  7071. Angle.prototype.radians = function () {
  7072. return this._radians;
  7073. };
  7074. /**
  7075. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7076. * @param a defines first vector
  7077. * @param b defines second vector
  7078. * @returns a new Angle
  7079. */
  7080. Angle.BetweenTwoPoints = function (a, b) {
  7081. var delta = b.subtract(a);
  7082. var theta = Math.atan2(delta.y, delta.x);
  7083. return new Angle(theta);
  7084. };
  7085. /**
  7086. * Gets a new Angle object from the given float in radians
  7087. * @param radians defines the angle value in radians
  7088. * @returns a new Angle
  7089. */
  7090. Angle.FromRadians = function (radians) {
  7091. return new Angle(radians);
  7092. };
  7093. /**
  7094. * Gets a new Angle object from the given float in degrees
  7095. * @param degrees defines the angle value in degrees
  7096. * @returns a new Angle
  7097. */
  7098. Angle.FromDegrees = function (degrees) {
  7099. return new Angle(degrees * Math.PI / 180.0);
  7100. };
  7101. return Angle;
  7102. }());
  7103. BABYLON.Angle = Angle;
  7104. /**
  7105. * This represents an arc in a 2d space.
  7106. */
  7107. var Arc2 = /** @class */ (function () {
  7108. /**
  7109. * Creates an Arc object from the three given points : start, middle and end.
  7110. * @param startPoint Defines the start point of the arc
  7111. * @param midPoint Defines the midlle point of the arc
  7112. * @param endPoint Defines the end point of the arc
  7113. */
  7114. function Arc2(
  7115. /** Defines the start point of the arc */
  7116. startPoint,
  7117. /** Defines the mid point of the arc */
  7118. midPoint,
  7119. /** Defines the end point of the arc */
  7120. endPoint) {
  7121. this.startPoint = startPoint;
  7122. this.midPoint = midPoint;
  7123. this.endPoint = endPoint;
  7124. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7125. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7126. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7127. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7128. 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);
  7129. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7130. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7131. var a1 = this.startAngle.degrees();
  7132. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7133. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7134. // angles correction
  7135. if (a2 - a1 > +180.0)
  7136. a2 -= 360.0;
  7137. if (a2 - a1 < -180.0)
  7138. a2 += 360.0;
  7139. if (a3 - a2 > +180.0)
  7140. a3 -= 360.0;
  7141. if (a3 - a2 < -180.0)
  7142. a3 += 360.0;
  7143. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7144. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7145. }
  7146. return Arc2;
  7147. }());
  7148. BABYLON.Arc2 = Arc2;
  7149. var Path2 = /** @class */ (function () {
  7150. /**
  7151. * Creates a Path2 object from the starting 2D coordinates x and y.
  7152. */
  7153. function Path2(x, y) {
  7154. this._points = new Array();
  7155. this._length = 0.0;
  7156. this.closed = false;
  7157. this._points.push(new Vector2(x, y));
  7158. }
  7159. /**
  7160. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7161. * Returns the updated Path2.
  7162. */
  7163. Path2.prototype.addLineTo = function (x, y) {
  7164. if (this.closed) {
  7165. return this;
  7166. }
  7167. var newPoint = new Vector2(x, y);
  7168. var previousPoint = this._points[this._points.length - 1];
  7169. this._points.push(newPoint);
  7170. this._length += newPoint.subtract(previousPoint).length();
  7171. return this;
  7172. };
  7173. /**
  7174. * 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.
  7175. * Returns the updated Path2.
  7176. */
  7177. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7178. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7179. if (this.closed) {
  7180. return this;
  7181. }
  7182. var startPoint = this._points[this._points.length - 1];
  7183. var midPoint = new Vector2(midX, midY);
  7184. var endPoint = new Vector2(endX, endY);
  7185. var arc = new Arc2(startPoint, midPoint, endPoint);
  7186. var increment = arc.angle.radians() / numberOfSegments;
  7187. if (arc.orientation === Orientation.CW)
  7188. increment *= -1;
  7189. var currentAngle = arc.startAngle.radians() + increment;
  7190. for (var i = 0; i < numberOfSegments; i++) {
  7191. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7192. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7193. this.addLineTo(x, y);
  7194. currentAngle += increment;
  7195. }
  7196. return this;
  7197. };
  7198. /**
  7199. * Closes the Path2.
  7200. * Returns the Path2.
  7201. */
  7202. Path2.prototype.close = function () {
  7203. this.closed = true;
  7204. return this;
  7205. };
  7206. /**
  7207. * Returns the Path2 total length (float).
  7208. */
  7209. Path2.prototype.length = function () {
  7210. var result = this._length;
  7211. if (!this.closed) {
  7212. var lastPoint = this._points[this._points.length - 1];
  7213. var firstPoint = this._points[0];
  7214. result += (firstPoint.subtract(lastPoint).length());
  7215. }
  7216. return result;
  7217. };
  7218. /**
  7219. * Returns the Path2 internal array of points.
  7220. */
  7221. Path2.prototype.getPoints = function () {
  7222. return this._points;
  7223. };
  7224. /**
  7225. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7226. */
  7227. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7228. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7229. return Vector2.Zero();
  7230. }
  7231. var lengthPosition = normalizedLengthPosition * this.length();
  7232. var previousOffset = 0;
  7233. for (var i = 0; i < this._points.length; i++) {
  7234. var j = (i + 1) % this._points.length;
  7235. var a = this._points[i];
  7236. var b = this._points[j];
  7237. var bToA = b.subtract(a);
  7238. var nextOffset = (bToA.length() + previousOffset);
  7239. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7240. var dir = bToA.normalize();
  7241. var localOffset = lengthPosition - previousOffset;
  7242. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7243. }
  7244. previousOffset = nextOffset;
  7245. }
  7246. return Vector2.Zero();
  7247. };
  7248. /**
  7249. * Returns a new Path2 starting at the coordinates (x, y).
  7250. */
  7251. Path2.StartingAt = function (x, y) {
  7252. return new Path2(x, y);
  7253. };
  7254. return Path2;
  7255. }());
  7256. BABYLON.Path2 = Path2;
  7257. var Path3D = /** @class */ (function () {
  7258. /**
  7259. * new Path3D(path, normal, raw)
  7260. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7261. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7262. * path : an array of Vector3, the curve axis of the Path3D
  7263. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7264. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7265. */
  7266. function Path3D(path, firstNormal, raw) {
  7267. if (firstNormal === void 0) { firstNormal = null; }
  7268. this.path = path;
  7269. this._curve = new Array();
  7270. this._distances = new Array();
  7271. this._tangents = new Array();
  7272. this._normals = new Array();
  7273. this._binormals = new Array();
  7274. for (var p = 0; p < path.length; p++) {
  7275. this._curve[p] = path[p].clone(); // hard copy
  7276. }
  7277. this._raw = raw || false;
  7278. this._compute(firstNormal);
  7279. }
  7280. /**
  7281. * Returns the Path3D array of successive Vector3 designing its curve.
  7282. */
  7283. Path3D.prototype.getCurve = function () {
  7284. return this._curve;
  7285. };
  7286. /**
  7287. * Returns an array populated with tangent vectors on each Path3D curve point.
  7288. */
  7289. Path3D.prototype.getTangents = function () {
  7290. return this._tangents;
  7291. };
  7292. /**
  7293. * Returns an array populated with normal vectors on each Path3D curve point.
  7294. */
  7295. Path3D.prototype.getNormals = function () {
  7296. return this._normals;
  7297. };
  7298. /**
  7299. * Returns an array populated with binormal vectors on each Path3D curve point.
  7300. */
  7301. Path3D.prototype.getBinormals = function () {
  7302. return this._binormals;
  7303. };
  7304. /**
  7305. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7306. */
  7307. Path3D.prototype.getDistances = function () {
  7308. return this._distances;
  7309. };
  7310. /**
  7311. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7312. * Returns the same object updated.
  7313. */
  7314. Path3D.prototype.update = function (path, firstNormal) {
  7315. if (firstNormal === void 0) { firstNormal = null; }
  7316. for (var p = 0; p < path.length; p++) {
  7317. this._curve[p].x = path[p].x;
  7318. this._curve[p].y = path[p].y;
  7319. this._curve[p].z = path[p].z;
  7320. }
  7321. this._compute(firstNormal);
  7322. return this;
  7323. };
  7324. // private function compute() : computes tangents, normals and binormals
  7325. Path3D.prototype._compute = function (firstNormal) {
  7326. var l = this._curve.length;
  7327. // first and last tangents
  7328. this._tangents[0] = this._getFirstNonNullVector(0);
  7329. if (!this._raw) {
  7330. this._tangents[0].normalize();
  7331. }
  7332. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7333. if (!this._raw) {
  7334. this._tangents[l - 1].normalize();
  7335. }
  7336. // normals and binormals at first point : arbitrary vector with _normalVector()
  7337. var tg0 = this._tangents[0];
  7338. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7339. this._normals[0] = pp0;
  7340. if (!this._raw) {
  7341. this._normals[0].normalize();
  7342. }
  7343. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7344. if (!this._raw) {
  7345. this._binormals[0].normalize();
  7346. }
  7347. this._distances[0] = 0.0;
  7348. // normals and binormals : next points
  7349. var prev; // previous vector (segment)
  7350. var cur; // current vector (segment)
  7351. var curTang; // current tangent
  7352. // previous normal
  7353. var prevBinor; // previous binormal
  7354. for (var i = 1; i < l; i++) {
  7355. // tangents
  7356. prev = this._getLastNonNullVector(i);
  7357. if (i < l - 1) {
  7358. cur = this._getFirstNonNullVector(i);
  7359. this._tangents[i] = prev.add(cur);
  7360. this._tangents[i].normalize();
  7361. }
  7362. this._distances[i] = this._distances[i - 1] + prev.length();
  7363. // normals and binormals
  7364. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7365. curTang = this._tangents[i];
  7366. prevBinor = this._binormals[i - 1];
  7367. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7368. if (!this._raw) {
  7369. this._normals[i].normalize();
  7370. }
  7371. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7372. if (!this._raw) {
  7373. this._binormals[i].normalize();
  7374. }
  7375. }
  7376. };
  7377. // private function getFirstNonNullVector(index)
  7378. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7379. Path3D.prototype._getFirstNonNullVector = function (index) {
  7380. var i = 1;
  7381. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7382. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7383. i++;
  7384. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7385. }
  7386. return nNVector;
  7387. };
  7388. // private function getLastNonNullVector(index)
  7389. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7390. Path3D.prototype._getLastNonNullVector = function (index) {
  7391. var i = 1;
  7392. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7393. while (nLVector.length() === 0 && index > i + 1) {
  7394. i++;
  7395. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7396. }
  7397. return nLVector;
  7398. };
  7399. // private function normalVector(v0, vt, va) :
  7400. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7401. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7402. Path3D.prototype._normalVector = function (v0, vt, va) {
  7403. var normal0;
  7404. var tgl = vt.length();
  7405. if (tgl === 0.0) {
  7406. tgl = 1.0;
  7407. }
  7408. if (va === undefined || va === null) {
  7409. var point;
  7410. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7411. point = new Vector3(0.0, -1.0, 0.0);
  7412. }
  7413. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7414. point = new Vector3(1.0, 0.0, 0.0);
  7415. }
  7416. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7417. point = new Vector3(0.0, 0.0, 1.0);
  7418. }
  7419. else {
  7420. point = Vector3.Zero();
  7421. }
  7422. normal0 = Vector3.Cross(vt, point);
  7423. }
  7424. else {
  7425. normal0 = Vector3.Cross(vt, va);
  7426. Vector3.CrossToRef(normal0, vt, normal0);
  7427. }
  7428. normal0.normalize();
  7429. return normal0;
  7430. };
  7431. return Path3D;
  7432. }());
  7433. BABYLON.Path3D = Path3D;
  7434. var Curve3 = /** @class */ (function () {
  7435. /**
  7436. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7437. * A Curve3 is designed from a series of successive Vector3.
  7438. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7439. */
  7440. function Curve3(points) {
  7441. this._length = 0.0;
  7442. this._points = points;
  7443. this._length = this._computeLength(points);
  7444. }
  7445. /**
  7446. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7447. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7448. * @param v1 (Vector3) the control point
  7449. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7450. * @param nbPoints (integer) the wanted number of points in the curve
  7451. */
  7452. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7453. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7454. var bez = new Array();
  7455. var equation = function (t, val0, val1, val2) {
  7456. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7457. return res;
  7458. };
  7459. for (var i = 0; i <= nbPoints; i++) {
  7460. 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)));
  7461. }
  7462. return new Curve3(bez);
  7463. };
  7464. /**
  7465. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7466. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7467. * @param v1 (Vector3) the first control point
  7468. * @param v2 (Vector3) the second control point
  7469. * @param v3 (Vector3) the end point of the Cubic Bezier
  7470. * @param nbPoints (integer) the wanted number of points in the curve
  7471. */
  7472. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7473. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7474. var bez = new Array();
  7475. var equation = function (t, val0, val1, val2, val3) {
  7476. 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;
  7477. return res;
  7478. };
  7479. for (var i = 0; i <= nbPoints; i++) {
  7480. 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)));
  7481. }
  7482. return new Curve3(bez);
  7483. };
  7484. /**
  7485. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7486. * @param p1 (Vector3) the origin point of the Hermite Spline
  7487. * @param t1 (Vector3) the tangent vector at the origin point
  7488. * @param p2 (Vector3) the end point of the Hermite Spline
  7489. * @param t2 (Vector3) the tangent vector at the end point
  7490. * @param nbPoints (integer) the wanted number of points in the curve
  7491. */
  7492. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7493. var hermite = new Array();
  7494. var step = 1.0 / nbPoints;
  7495. for (var i = 0; i <= nbPoints; i++) {
  7496. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7497. }
  7498. return new Curve3(hermite);
  7499. };
  7500. /**
  7501. * Returns a Curve3 object along a CatmullRom Spline curve :
  7502. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7503. * @param nbPoints (integer) the wanted number of points between each curve control points
  7504. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7505. */
  7506. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7507. var catmullRom = new Array();
  7508. var step = 1.0 / nbPoints;
  7509. var amount = 0.0;
  7510. if (closed) {
  7511. var pointsCount = points.length;
  7512. for (var i = 0; i < pointsCount; i++) {
  7513. amount = 0;
  7514. for (var c = 0; c < nbPoints; c++) {
  7515. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7516. amount += step;
  7517. }
  7518. }
  7519. catmullRom.push(catmullRom[0]);
  7520. }
  7521. else {
  7522. var totalPoints = new Array();
  7523. totalPoints.push(points[0].clone());
  7524. Array.prototype.push.apply(totalPoints, points);
  7525. totalPoints.push(points[points.length - 1].clone());
  7526. for (var i = 0; i < totalPoints.length - 3; i++) {
  7527. amount = 0;
  7528. for (var c = 0; c < nbPoints; c++) {
  7529. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7530. amount += step;
  7531. }
  7532. }
  7533. i--;
  7534. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7535. }
  7536. return new Curve3(catmullRom);
  7537. };
  7538. /**
  7539. * Returns the Curve3 stored array of successive Vector3
  7540. */
  7541. Curve3.prototype.getPoints = function () {
  7542. return this._points;
  7543. };
  7544. /**
  7545. * Returns the computed length (float) of the curve.
  7546. */
  7547. Curve3.prototype.length = function () {
  7548. return this._length;
  7549. };
  7550. /**
  7551. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7552. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7553. * curveA and curveB keep unchanged.
  7554. */
  7555. Curve3.prototype.continue = function (curve) {
  7556. var lastPoint = this._points[this._points.length - 1];
  7557. var continuedPoints = this._points.slice();
  7558. var curvePoints = curve.getPoints();
  7559. for (var i = 1; i < curvePoints.length; i++) {
  7560. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7561. }
  7562. var continuedCurve = new Curve3(continuedPoints);
  7563. return continuedCurve;
  7564. };
  7565. Curve3.prototype._computeLength = function (path) {
  7566. var l = 0;
  7567. for (var i = 1; i < path.length; i++) {
  7568. l += (path[i].subtract(path[i - 1])).length();
  7569. }
  7570. return l;
  7571. };
  7572. return Curve3;
  7573. }());
  7574. BABYLON.Curve3 = Curve3;
  7575. // Vertex formats
  7576. var PositionNormalVertex = /** @class */ (function () {
  7577. function PositionNormalVertex(position, normal) {
  7578. if (position === void 0) { position = Vector3.Zero(); }
  7579. if (normal === void 0) { normal = Vector3.Up(); }
  7580. this.position = position;
  7581. this.normal = normal;
  7582. }
  7583. PositionNormalVertex.prototype.clone = function () {
  7584. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7585. };
  7586. return PositionNormalVertex;
  7587. }());
  7588. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7589. var PositionNormalTextureVertex = /** @class */ (function () {
  7590. function PositionNormalTextureVertex(position, normal, uv) {
  7591. if (position === void 0) { position = Vector3.Zero(); }
  7592. if (normal === void 0) { normal = Vector3.Up(); }
  7593. if (uv === void 0) { uv = Vector2.Zero(); }
  7594. this.position = position;
  7595. this.normal = normal;
  7596. this.uv = uv;
  7597. }
  7598. PositionNormalTextureVertex.prototype.clone = function () {
  7599. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7600. };
  7601. return PositionNormalTextureVertex;
  7602. }());
  7603. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7604. // Temporary pre-allocated objects for engine internal use
  7605. // usage in any internal function :
  7606. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7607. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7608. var Tmp = /** @class */ (function () {
  7609. function Tmp() {
  7610. }
  7611. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7612. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7613. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7614. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7615. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7616. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7617. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7618. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7619. Matrix.Zero(), Matrix.Zero(),
  7620. Matrix.Zero(), Matrix.Zero(),
  7621. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7622. return Tmp;
  7623. }());
  7624. BABYLON.Tmp = Tmp;
  7625. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7626. var MathTmp = /** @class */ (function () {
  7627. function MathTmp() {
  7628. }
  7629. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7630. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7631. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7632. return MathTmp;
  7633. }());
  7634. })(BABYLON || (BABYLON = {}));
  7635. //# sourceMappingURL=babylon.math.js.map
  7636. var BABYLON;
  7637. (function (BABYLON) {
  7638. var Scalar = /** @class */ (function () {
  7639. function Scalar() {
  7640. }
  7641. /**
  7642. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7643. */
  7644. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7645. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7646. var num = a - b;
  7647. return -epsilon <= num && num <= epsilon;
  7648. };
  7649. /**
  7650. * Returns a string : the upper case translation of the number i to hexadecimal.
  7651. */
  7652. Scalar.ToHex = function (i) {
  7653. var str = i.toString(16);
  7654. if (i <= 15) {
  7655. return ("0" + str).toUpperCase();
  7656. }
  7657. return str.toUpperCase();
  7658. };
  7659. /**
  7660. * Returns -1 if value is negative and +1 is value is positive.
  7661. * Returns the value itself if it's equal to zero.
  7662. */
  7663. Scalar.Sign = function (value) {
  7664. value = +value; // convert to a number
  7665. if (value === 0 || isNaN(value))
  7666. return value;
  7667. return value > 0 ? 1 : -1;
  7668. };
  7669. /**
  7670. * Returns the value itself if it's between min and max.
  7671. * Returns min if the value is lower than min.
  7672. * Returns max if the value is greater than max.
  7673. */
  7674. Scalar.Clamp = function (value, min, max) {
  7675. if (min === void 0) { min = 0; }
  7676. if (max === void 0) { max = 1; }
  7677. return Math.min(max, Math.max(min, value));
  7678. };
  7679. /**
  7680. * Returns the log2 of value.
  7681. */
  7682. Scalar.Log2 = function (value) {
  7683. return Math.log(value) * Math.LOG2E;
  7684. };
  7685. /**
  7686. * Loops the value, so that it is never larger than length and never smaller than 0.
  7687. *
  7688. * This is similar to the modulo operator but it works with floating point numbers.
  7689. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7690. * With t = 5 and length = 2.5, the result would be 0.0.
  7691. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7692. */
  7693. Scalar.Repeat = function (value, length) {
  7694. return value - Math.floor(value / length) * length;
  7695. };
  7696. /**
  7697. * Normalize the value between 0.0 and 1.0 using min and max values
  7698. */
  7699. Scalar.Normalize = function (value, min, max) {
  7700. return (value - min) / (max - min);
  7701. };
  7702. /**
  7703. * Denormalize the value from 0.0 and 1.0 using min and max values
  7704. */
  7705. Scalar.Denormalize = function (normalized, min, max) {
  7706. return (normalized * (max - min) + min);
  7707. };
  7708. /**
  7709. * Calculates the shortest difference between two given angles given in degrees.
  7710. */
  7711. Scalar.DeltaAngle = function (current, target) {
  7712. var num = Scalar.Repeat(target - current, 360.0);
  7713. if (num > 180.0) {
  7714. num -= 360.0;
  7715. }
  7716. return num;
  7717. };
  7718. /**
  7719. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7720. *
  7721. * The returned value will move back and forth between 0 and length
  7722. */
  7723. Scalar.PingPong = function (tx, length) {
  7724. var t = Scalar.Repeat(tx, length * 2.0);
  7725. return length - Math.abs(t - length);
  7726. };
  7727. /**
  7728. * Interpolates between min and max with smoothing at the limits.
  7729. *
  7730. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7731. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7732. */
  7733. Scalar.SmoothStep = function (from, to, tx) {
  7734. var t = Scalar.Clamp(tx);
  7735. t = -2.0 * t * t * t + 3.0 * t * t;
  7736. return to * t + from * (1.0 - t);
  7737. };
  7738. /**
  7739. * Moves a value current towards target.
  7740. *
  7741. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7742. * Negative values of maxDelta pushes the value away from target.
  7743. */
  7744. Scalar.MoveTowards = function (current, target, maxDelta) {
  7745. var result = 0;
  7746. if (Math.abs(target - current) <= maxDelta) {
  7747. result = target;
  7748. }
  7749. else {
  7750. result = current + Scalar.Sign(target - current) * maxDelta;
  7751. }
  7752. return result;
  7753. };
  7754. /**
  7755. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7756. *
  7757. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7758. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7759. */
  7760. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7761. var num = Scalar.DeltaAngle(current, target);
  7762. var result = 0;
  7763. if (-maxDelta < num && num < maxDelta) {
  7764. result = target;
  7765. }
  7766. else {
  7767. target = current + num;
  7768. result = Scalar.MoveTowards(current, target, maxDelta);
  7769. }
  7770. return result;
  7771. };
  7772. /**
  7773. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7774. */
  7775. Scalar.Lerp = function (start, end, amount) {
  7776. return start + ((end - start) * amount);
  7777. };
  7778. /**
  7779. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7780. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7781. */
  7782. Scalar.LerpAngle = function (start, end, amount) {
  7783. var num = Scalar.Repeat(end - start, 360.0);
  7784. if (num > 180.0) {
  7785. num -= 360.0;
  7786. }
  7787. return start + num * Scalar.Clamp(amount);
  7788. };
  7789. /**
  7790. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7791. */
  7792. Scalar.InverseLerp = function (a, b, value) {
  7793. var result = 0;
  7794. if (a != b) {
  7795. result = Scalar.Clamp((value - a) / (b - a));
  7796. }
  7797. else {
  7798. result = 0.0;
  7799. }
  7800. return result;
  7801. };
  7802. /**
  7803. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7804. */
  7805. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7806. var squared = amount * amount;
  7807. var cubed = amount * squared;
  7808. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7809. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7810. var part3 = (cubed - (2.0 * squared)) + amount;
  7811. var part4 = cubed - squared;
  7812. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7813. };
  7814. /**
  7815. * Returns a random float number between and min and max values
  7816. */
  7817. Scalar.RandomRange = function (min, max) {
  7818. if (min === max)
  7819. return min;
  7820. return ((Math.random() * (max - min)) + min);
  7821. };
  7822. /**
  7823. * This function returns percentage of a number in a given range.
  7824. *
  7825. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7826. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7827. */
  7828. Scalar.RangeToPercent = function (number, min, max) {
  7829. return ((number - min) / (max - min));
  7830. };
  7831. /**
  7832. * This function returns number that corresponds to the percentage in a given range.
  7833. *
  7834. * PercentToRange(0.34,0,100) will return 34.
  7835. */
  7836. Scalar.PercentToRange = function (percent, min, max) {
  7837. return ((max - min) * percent + min);
  7838. };
  7839. /**
  7840. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7841. * @param angle The angle to normalize in radian.
  7842. * @return The converted angle.
  7843. */
  7844. Scalar.NormalizeRadians = function (angle) {
  7845. // More precise but slower version kept for reference.
  7846. // angle = angle % Tools.TwoPi;
  7847. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7848. //if (angle > Math.PI) {
  7849. // angle -= Tools.TwoPi;
  7850. //}
  7851. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7852. return angle;
  7853. };
  7854. /**
  7855. * Two pi constants convenient for computation.
  7856. */
  7857. Scalar.TwoPi = Math.PI * 2;
  7858. return Scalar;
  7859. }());
  7860. BABYLON.Scalar = Scalar;
  7861. })(BABYLON || (BABYLON = {}));
  7862. //# sourceMappingURL=babylon.math.scalar.js.map
  7863. //# sourceMappingURL=babylon.mixins.js.map
  7864. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7865. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7866. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7867. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7868. //# sourceMappingURL=babylon.webgl2.js.map
  7869. var BABYLON;
  7870. (function (BABYLON) {
  7871. var __decoratorInitialStore = {};
  7872. var __mergedStore = {};
  7873. var _copySource = function (creationFunction, source, instanciate) {
  7874. var destination = creationFunction();
  7875. // Tags
  7876. if (BABYLON.Tags) {
  7877. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7878. }
  7879. var classStore = getMergedStore(destination);
  7880. // Properties
  7881. for (var property in classStore) {
  7882. var propertyDescriptor = classStore[property];
  7883. var sourceProperty = source[property];
  7884. var propertyType = propertyDescriptor.type;
  7885. if (sourceProperty !== undefined && sourceProperty !== null) {
  7886. switch (propertyType) {
  7887. case 0: // Value
  7888. case 6: // Mesh reference
  7889. case 11: // Camera reference
  7890. destination[property] = sourceProperty;
  7891. break;
  7892. case 1: // Texture
  7893. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7894. break;
  7895. case 2: // Color3
  7896. case 3: // FresnelParameters
  7897. case 4: // Vector2
  7898. case 5: // Vector3
  7899. case 7: // Color Curves
  7900. case 10: // Quaternion
  7901. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7902. break;
  7903. }
  7904. }
  7905. }
  7906. return destination;
  7907. };
  7908. function getDirectStore(target) {
  7909. var classKey = target.getClassName();
  7910. if (!__decoratorInitialStore[classKey]) {
  7911. __decoratorInitialStore[classKey] = {};
  7912. }
  7913. return __decoratorInitialStore[classKey];
  7914. }
  7915. /**
  7916. * Return the list of properties flagged as serializable
  7917. * @param target: host object
  7918. */
  7919. function getMergedStore(target) {
  7920. var classKey = target.getClassName();
  7921. if (__mergedStore[classKey]) {
  7922. return __mergedStore[classKey];
  7923. }
  7924. __mergedStore[classKey] = {};
  7925. var store = __mergedStore[classKey];
  7926. var currentTarget = target;
  7927. var currentKey = classKey;
  7928. while (currentKey) {
  7929. var initialStore = __decoratorInitialStore[currentKey];
  7930. for (var property in initialStore) {
  7931. store[property] = initialStore[property];
  7932. }
  7933. var parent_1 = void 0;
  7934. var done = false;
  7935. do {
  7936. parent_1 = Object.getPrototypeOf(currentTarget);
  7937. if (!parent_1.getClassName) {
  7938. done = true;
  7939. break;
  7940. }
  7941. if (parent_1.getClassName() !== currentKey) {
  7942. break;
  7943. }
  7944. currentTarget = parent_1;
  7945. } while (parent_1);
  7946. if (done) {
  7947. break;
  7948. }
  7949. currentKey = parent_1.getClassName();
  7950. currentTarget = parent_1;
  7951. }
  7952. return store;
  7953. }
  7954. function generateSerializableMember(type, sourceName) {
  7955. return function (target, propertyKey) {
  7956. var classStore = getDirectStore(target);
  7957. if (!classStore[propertyKey]) {
  7958. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7959. }
  7960. };
  7961. }
  7962. function generateExpandMember(setCallback, targetKey) {
  7963. if (targetKey === void 0) { targetKey = null; }
  7964. return function (target, propertyKey) {
  7965. var key = targetKey || ("_" + propertyKey);
  7966. Object.defineProperty(target, propertyKey, {
  7967. get: function () {
  7968. return this[key];
  7969. },
  7970. set: function (value) {
  7971. if (this[key] === value) {
  7972. return;
  7973. }
  7974. this[key] = value;
  7975. target[setCallback].apply(this);
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. };
  7981. }
  7982. function expandToProperty(callback, targetKey) {
  7983. if (targetKey === void 0) { targetKey = null; }
  7984. return generateExpandMember(callback, targetKey);
  7985. }
  7986. BABYLON.expandToProperty = expandToProperty;
  7987. function serialize(sourceName) {
  7988. return generateSerializableMember(0, sourceName); // value member
  7989. }
  7990. BABYLON.serialize = serialize;
  7991. function serializeAsTexture(sourceName) {
  7992. return generateSerializableMember(1, sourceName); // texture member
  7993. }
  7994. BABYLON.serializeAsTexture = serializeAsTexture;
  7995. function serializeAsColor3(sourceName) {
  7996. return generateSerializableMember(2, sourceName); // color3 member
  7997. }
  7998. BABYLON.serializeAsColor3 = serializeAsColor3;
  7999. function serializeAsFresnelParameters(sourceName) {
  8000. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8001. }
  8002. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8003. function serializeAsVector2(sourceName) {
  8004. return generateSerializableMember(4, sourceName); // vector2 member
  8005. }
  8006. BABYLON.serializeAsVector2 = serializeAsVector2;
  8007. function serializeAsVector3(sourceName) {
  8008. return generateSerializableMember(5, sourceName); // vector3 member
  8009. }
  8010. BABYLON.serializeAsVector3 = serializeAsVector3;
  8011. function serializeAsMeshReference(sourceName) {
  8012. return generateSerializableMember(6, sourceName); // mesh reference member
  8013. }
  8014. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8015. function serializeAsColorCurves(sourceName) {
  8016. return generateSerializableMember(7, sourceName); // color curves
  8017. }
  8018. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8019. function serializeAsColor4(sourceName) {
  8020. return generateSerializableMember(8, sourceName); // color 4
  8021. }
  8022. BABYLON.serializeAsColor4 = serializeAsColor4;
  8023. function serializeAsImageProcessingConfiguration(sourceName) {
  8024. return generateSerializableMember(9, sourceName); // image processing
  8025. }
  8026. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8027. function serializeAsQuaternion(sourceName) {
  8028. return generateSerializableMember(10, sourceName); // quaternion member
  8029. }
  8030. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8031. /**
  8032. * Decorator used to define property that can be serialized as reference to a camera
  8033. * @param sourceName defines the name of the property to decorate
  8034. */
  8035. function serializeAsCameraReference(sourceName) {
  8036. return generateSerializableMember(11, sourceName); // camera reference member
  8037. }
  8038. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8039. var SerializationHelper = /** @class */ (function () {
  8040. function SerializationHelper() {
  8041. }
  8042. SerializationHelper.Serialize = function (entity, serializationObject) {
  8043. if (!serializationObject) {
  8044. serializationObject = {};
  8045. }
  8046. // Tags
  8047. if (BABYLON.Tags) {
  8048. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8049. }
  8050. var serializedProperties = getMergedStore(entity);
  8051. // Properties
  8052. for (var property in serializedProperties) {
  8053. var propertyDescriptor = serializedProperties[property];
  8054. var targetPropertyName = propertyDescriptor.sourceName || property;
  8055. var propertyType = propertyDescriptor.type;
  8056. var sourceProperty = entity[property];
  8057. if (sourceProperty !== undefined && sourceProperty !== null) {
  8058. switch (propertyType) {
  8059. case 0: // Value
  8060. serializationObject[targetPropertyName] = sourceProperty;
  8061. break;
  8062. case 1: // Texture
  8063. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8064. break;
  8065. case 2: // Color3
  8066. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8067. break;
  8068. case 3: // FresnelParameters
  8069. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8070. break;
  8071. case 4: // Vector2
  8072. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8073. break;
  8074. case 5: // Vector3
  8075. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8076. break;
  8077. case 6: // Mesh reference
  8078. serializationObject[targetPropertyName] = sourceProperty.id;
  8079. break;
  8080. case 7: // Color Curves
  8081. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8082. break;
  8083. case 8: // Color 4
  8084. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8085. break;
  8086. case 9: // Image Processing
  8087. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8088. break;
  8089. case 10: // Quaternion
  8090. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8091. break;
  8092. case 11: // Camera reference
  8093. serializationObject[targetPropertyName] = sourceProperty.id;
  8094. break;
  8095. }
  8096. }
  8097. }
  8098. return serializationObject;
  8099. };
  8100. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8101. if (rootUrl === void 0) { rootUrl = null; }
  8102. var destination = creationFunction();
  8103. if (!rootUrl) {
  8104. rootUrl = "";
  8105. }
  8106. // Tags
  8107. if (BABYLON.Tags) {
  8108. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8109. }
  8110. var classStore = getMergedStore(destination);
  8111. // Properties
  8112. for (var property in classStore) {
  8113. var propertyDescriptor = classStore[property];
  8114. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8115. var propertyType = propertyDescriptor.type;
  8116. if (sourceProperty !== undefined && sourceProperty !== null) {
  8117. var dest = destination;
  8118. switch (propertyType) {
  8119. case 0: // Value
  8120. dest[property] = sourceProperty;
  8121. break;
  8122. case 1: // Texture
  8123. if (scene) {
  8124. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8125. }
  8126. break;
  8127. case 2: // Color3
  8128. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8129. break;
  8130. case 3: // FresnelParameters
  8131. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8132. break;
  8133. case 4: // Vector2
  8134. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8135. break;
  8136. case 5: // Vector3
  8137. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8138. break;
  8139. case 6: // Mesh reference
  8140. if (scene) {
  8141. dest[property] = scene.getLastMeshByID(sourceProperty);
  8142. }
  8143. break;
  8144. case 7: // Color Curves
  8145. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8146. break;
  8147. case 8: // Color 4
  8148. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8149. break;
  8150. case 9: // Image Processing
  8151. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8152. break;
  8153. case 10: // Quaternion
  8154. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8155. break;
  8156. case 11: // Camera reference
  8157. if (scene) {
  8158. dest[property] = scene.getCameraByID(sourceProperty);
  8159. }
  8160. break;
  8161. }
  8162. }
  8163. }
  8164. return destination;
  8165. };
  8166. SerializationHelper.Clone = function (creationFunction, source) {
  8167. return _copySource(creationFunction, source, false);
  8168. };
  8169. SerializationHelper.Instanciate = function (creationFunction, source) {
  8170. return _copySource(creationFunction, source, true);
  8171. };
  8172. return SerializationHelper;
  8173. }());
  8174. BABYLON.SerializationHelper = SerializationHelper;
  8175. })(BABYLON || (BABYLON = {}));
  8176. //# sourceMappingURL=babylon.decorators.js.map
  8177. var BABYLON;
  8178. (function (BABYLON) {
  8179. /**
  8180. * Wrapper class for promise with external resolve and reject.
  8181. */
  8182. var Deferred = /** @class */ (function () {
  8183. /**
  8184. * Constructor for this deferred object.
  8185. */
  8186. function Deferred() {
  8187. var _this = this;
  8188. this.promise = new Promise(function (resolve, reject) {
  8189. _this._resolve = resolve;
  8190. _this._reject = reject;
  8191. });
  8192. }
  8193. Object.defineProperty(Deferred.prototype, "resolve", {
  8194. /**
  8195. * The resolve method of the promise associated with this deferred object.
  8196. */
  8197. get: function () {
  8198. return this._resolve;
  8199. },
  8200. enumerable: true,
  8201. configurable: true
  8202. });
  8203. Object.defineProperty(Deferred.prototype, "reject", {
  8204. /**
  8205. * The reject method of the promise associated with this deferred object.
  8206. */
  8207. get: function () {
  8208. return this._reject;
  8209. },
  8210. enumerable: true,
  8211. configurable: true
  8212. });
  8213. return Deferred;
  8214. }());
  8215. BABYLON.Deferred = Deferred;
  8216. })(BABYLON || (BABYLON = {}));
  8217. //# sourceMappingURL=babylon.deferred.js.map
  8218. var BABYLON;
  8219. (function (BABYLON) {
  8220. /**
  8221. * A class serves as a medium between the observable and its observers
  8222. */
  8223. var EventState = /** @class */ (function () {
  8224. /**
  8225. * Create a new EventState
  8226. * @param mask defines the mask associated with this state
  8227. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8228. * @param target defines the original target of the state
  8229. * @param currentTarget defines the current target of the state
  8230. */
  8231. function EventState(mask, skipNextObservers, target, currentTarget) {
  8232. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8233. this.initalize(mask, skipNextObservers, target, currentTarget);
  8234. }
  8235. /**
  8236. * Initialize the current event state
  8237. * @param mask defines the mask associated with this state
  8238. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8239. * @param target defines the original target of the state
  8240. * @param currentTarget defines the current target of the state
  8241. * @returns the current event state
  8242. */
  8243. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8244. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8245. this.mask = mask;
  8246. this.skipNextObservers = skipNextObservers;
  8247. this.target = target;
  8248. this.currentTarget = currentTarget;
  8249. return this;
  8250. };
  8251. return EventState;
  8252. }());
  8253. BABYLON.EventState = EventState;
  8254. /**
  8255. * Represent an Observer registered to a given Observable object.
  8256. */
  8257. var Observer = /** @class */ (function () {
  8258. /**
  8259. * Creates a new observer
  8260. * @param callback defines the callback to call when the observer is notified
  8261. * @param mask defines the mask of the observer (used to filter notifications)
  8262. * @param scope defines the current scope used to restore the JS context
  8263. */
  8264. function Observer(
  8265. /**
  8266. * Defines the callback to call when the observer is notified
  8267. */
  8268. callback,
  8269. /**
  8270. * Defines the mask of the observer (used to filter notifications)
  8271. */
  8272. mask,
  8273. /**
  8274. * Defines the current scope used to restore the JS context
  8275. */
  8276. scope) {
  8277. if (scope === void 0) { scope = null; }
  8278. this.callback = callback;
  8279. this.mask = mask;
  8280. this.scope = scope;
  8281. /** @hidden */
  8282. this._willBeUnregistered = false;
  8283. /**
  8284. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8285. */
  8286. this.unregisterOnNextCall = false;
  8287. }
  8288. return Observer;
  8289. }());
  8290. BABYLON.Observer = Observer;
  8291. /**
  8292. * Represent a list of observers registered to multiple Observables object.
  8293. */
  8294. var MultiObserver = /** @class */ (function () {
  8295. function MultiObserver() {
  8296. }
  8297. /**
  8298. * Release associated resources
  8299. */
  8300. MultiObserver.prototype.dispose = function () {
  8301. if (this._observers && this._observables) {
  8302. for (var index = 0; index < this._observers.length; index++) {
  8303. this._observables[index].remove(this._observers[index]);
  8304. }
  8305. }
  8306. this._observers = null;
  8307. this._observables = null;
  8308. };
  8309. /**
  8310. * Raise a callback when one of the observable will notify
  8311. * @param observables defines a list of observables to watch
  8312. * @param callback defines the callback to call on notification
  8313. * @param mask defines the mask used to filter notifications
  8314. * @param scope defines the current scope used to restore the JS context
  8315. * @returns the new MultiObserver
  8316. */
  8317. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8318. if (mask === void 0) { mask = -1; }
  8319. if (scope === void 0) { scope = null; }
  8320. var result = new MultiObserver();
  8321. result._observers = new Array();
  8322. result._observables = observables;
  8323. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8324. var observable = observables_1[_i];
  8325. var observer = observable.add(callback, mask, false, scope);
  8326. if (observer) {
  8327. result._observers.push(observer);
  8328. }
  8329. }
  8330. return result;
  8331. };
  8332. return MultiObserver;
  8333. }());
  8334. BABYLON.MultiObserver = MultiObserver;
  8335. /**
  8336. * The Observable class is a simple implementation of the Observable pattern.
  8337. *
  8338. * 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.
  8339. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8340. * 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).
  8341. * 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.
  8342. */
  8343. var Observable = /** @class */ (function () {
  8344. /**
  8345. * Creates a new observable
  8346. * @param onObserverAdded defines a callback to call when a new observer is added
  8347. */
  8348. function Observable(onObserverAdded) {
  8349. this._observers = new Array();
  8350. this._eventState = new EventState(0);
  8351. if (onObserverAdded) {
  8352. this._onObserverAdded = onObserverAdded;
  8353. }
  8354. }
  8355. /**
  8356. * Create a new Observer with the specified callback
  8357. * @param callback the callback that will be executed for that Observer
  8358. * @param mask the mask used to filter observers
  8359. * @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.
  8360. * @param scope optional scope for the callback to be called from
  8361. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8362. * @returns the new observer created for the callback
  8363. */
  8364. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8365. if (mask === void 0) { mask = -1; }
  8366. if (insertFirst === void 0) { insertFirst = false; }
  8367. if (scope === void 0) { scope = null; }
  8368. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8369. if (!callback) {
  8370. return null;
  8371. }
  8372. var observer = new Observer(callback, mask, scope);
  8373. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8374. if (insertFirst) {
  8375. this._observers.unshift(observer);
  8376. }
  8377. else {
  8378. this._observers.push(observer);
  8379. }
  8380. if (this._onObserverAdded) {
  8381. this._onObserverAdded(observer);
  8382. }
  8383. return observer;
  8384. };
  8385. /**
  8386. * Create a new Observer with the specified callback and unregisters after the next notification
  8387. * @param callback the callback that will be executed for that Observer
  8388. * @returns the new observer created for the callback
  8389. */
  8390. Observable.prototype.addOnce = function (callback) {
  8391. return this.add(callback, undefined, undefined, undefined, true);
  8392. };
  8393. /**
  8394. * Remove an Observer from the Observable object
  8395. * @param observer the instance of the Observer to remove
  8396. * @returns false if it doesn't belong to this Observable
  8397. */
  8398. Observable.prototype.remove = function (observer) {
  8399. if (!observer) {
  8400. return false;
  8401. }
  8402. var index = this._observers.indexOf(observer);
  8403. if (index !== -1) {
  8404. this._deferUnregister(observer);
  8405. return true;
  8406. }
  8407. return false;
  8408. };
  8409. /**
  8410. * Remove a callback from the Observable object
  8411. * @param callback the callback to remove
  8412. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8413. * @returns false if it doesn't belong to this Observable
  8414. */
  8415. Observable.prototype.removeCallback = function (callback, scope) {
  8416. for (var index = 0; index < this._observers.length; index++) {
  8417. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8418. this._deferUnregister(this._observers[index]);
  8419. return true;
  8420. }
  8421. }
  8422. return false;
  8423. };
  8424. Observable.prototype._deferUnregister = function (observer) {
  8425. var _this = this;
  8426. observer.unregisterOnNextCall = false;
  8427. observer._willBeUnregistered = true;
  8428. BABYLON.Tools.SetImmediate(function () {
  8429. _this._remove(observer);
  8430. });
  8431. };
  8432. // This should only be called when not iterating over _observers to avoid callback skipping.
  8433. // Removes an observer from the _observer Array.
  8434. Observable.prototype._remove = function (observer) {
  8435. if (!observer) {
  8436. return false;
  8437. }
  8438. var index = this._observers.indexOf(observer);
  8439. if (index !== -1) {
  8440. this._observers.splice(index, 1);
  8441. return true;
  8442. }
  8443. return false;
  8444. };
  8445. /**
  8446. * Notify all Observers by calling their respective callback with the given data
  8447. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8448. * @param eventData defines the data to send to all observers
  8449. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8450. * @param target defines the original target of the state
  8451. * @param currentTarget defines the current target of the state
  8452. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8453. */
  8454. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8455. if (mask === void 0) { mask = -1; }
  8456. if (!this._observers.length) {
  8457. return true;
  8458. }
  8459. var state = this._eventState;
  8460. state.mask = mask;
  8461. state.target = target;
  8462. state.currentTarget = currentTarget;
  8463. state.skipNextObservers = false;
  8464. state.lastReturnValue = eventData;
  8465. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8466. var obs = _a[_i];
  8467. if (obs._willBeUnregistered) {
  8468. continue;
  8469. }
  8470. if (obs.mask & mask) {
  8471. if (obs.scope) {
  8472. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8473. }
  8474. else {
  8475. state.lastReturnValue = obs.callback(eventData, state);
  8476. }
  8477. if (obs.unregisterOnNextCall) {
  8478. this._deferUnregister(obs);
  8479. }
  8480. }
  8481. if (state.skipNextObservers) {
  8482. return false;
  8483. }
  8484. }
  8485. return true;
  8486. };
  8487. /**
  8488. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8489. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8490. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8491. * and it is crucial that all callbacks will be executed.
  8492. * The order of the callbacks is kept, callbacks are not executed parallel.
  8493. *
  8494. * @param eventData The data to be sent to each callback
  8495. * @param mask is used to filter observers defaults to -1
  8496. * @param target defines the callback target (see EventState)
  8497. * @param currentTarget defines he current object in the bubbling phase
  8498. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8499. */
  8500. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8501. var _this = this;
  8502. if (mask === void 0) { mask = -1; }
  8503. // create an empty promise
  8504. var p = Promise.resolve(eventData);
  8505. // no observers? return this promise.
  8506. if (!this._observers.length) {
  8507. return p;
  8508. }
  8509. var state = this._eventState;
  8510. state.mask = mask;
  8511. state.target = target;
  8512. state.currentTarget = currentTarget;
  8513. state.skipNextObservers = false;
  8514. // execute one callback after another (not using Promise.all, the order is important)
  8515. this._observers.forEach(function (obs) {
  8516. if (state.skipNextObservers) {
  8517. return;
  8518. }
  8519. if (obs._willBeUnregistered) {
  8520. return;
  8521. }
  8522. if (obs.mask & mask) {
  8523. if (obs.scope) {
  8524. p = p.then(function (lastReturnedValue) {
  8525. state.lastReturnValue = lastReturnedValue;
  8526. return obs.callback.apply(obs.scope, [eventData, state]);
  8527. });
  8528. }
  8529. else {
  8530. p = p.then(function (lastReturnedValue) {
  8531. state.lastReturnValue = lastReturnedValue;
  8532. return obs.callback(eventData, state);
  8533. });
  8534. }
  8535. if (obs.unregisterOnNextCall) {
  8536. _this._deferUnregister(obs);
  8537. }
  8538. }
  8539. });
  8540. // return the eventData
  8541. return p.then(function () { return eventData; });
  8542. };
  8543. /**
  8544. * Notify a specific observer
  8545. * @param observer defines the observer to notify
  8546. * @param eventData defines the data to be sent to each callback
  8547. * @param mask is used to filter observers defaults to -1
  8548. */
  8549. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8550. if (mask === void 0) { mask = -1; }
  8551. var state = this._eventState;
  8552. state.mask = mask;
  8553. state.skipNextObservers = false;
  8554. observer.callback(eventData, state);
  8555. };
  8556. /**
  8557. * Gets a boolean indicating if the observable has at least one observer
  8558. * @returns true is the Observable has at least one Observer registered
  8559. */
  8560. Observable.prototype.hasObservers = function () {
  8561. return this._observers.length > 0;
  8562. };
  8563. /**
  8564. * Clear the list of observers
  8565. */
  8566. Observable.prototype.clear = function () {
  8567. this._observers = new Array();
  8568. this._onObserverAdded = null;
  8569. };
  8570. /**
  8571. * Clone the current observable
  8572. * @returns a new observable
  8573. */
  8574. Observable.prototype.clone = function () {
  8575. var result = new Observable();
  8576. result._observers = this._observers.slice(0);
  8577. return result;
  8578. };
  8579. /**
  8580. * Does this observable handles observer registered with a given mask
  8581. * @param mask defines the mask to be tested
  8582. * @return whether or not one observer registered with the given mask is handeled
  8583. **/
  8584. Observable.prototype.hasSpecificMask = function (mask) {
  8585. if (mask === void 0) { mask = -1; }
  8586. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8587. var obs = _a[_i];
  8588. if (obs.mask & mask || obs.mask === mask) {
  8589. return true;
  8590. }
  8591. }
  8592. return false;
  8593. };
  8594. return Observable;
  8595. }());
  8596. BABYLON.Observable = Observable;
  8597. })(BABYLON || (BABYLON = {}));
  8598. //# sourceMappingURL=babylon.observable.js.map
  8599. var BABYLON;
  8600. (function (BABYLON) {
  8601. /**
  8602. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8603. */
  8604. var SmartArray = /** @class */ (function () {
  8605. /**
  8606. * Instantiates a Smart Array.
  8607. * @param capacity defines the default capacity of the array.
  8608. */
  8609. function SmartArray(capacity) {
  8610. /**
  8611. * The active length of the array.
  8612. */
  8613. this.length = 0;
  8614. this.data = new Array(capacity);
  8615. this._id = SmartArray._GlobalId++;
  8616. }
  8617. /**
  8618. * Pushes a value at the end of the active data.
  8619. * @param value defines the object to push in the array.
  8620. */
  8621. SmartArray.prototype.push = function (value) {
  8622. this.data[this.length++] = value;
  8623. if (this.length > this.data.length) {
  8624. this.data.length *= 2;
  8625. }
  8626. };
  8627. /**
  8628. * Iterates over the active data and apply the lambda to them.
  8629. * @param func defines the action to apply on each value.
  8630. */
  8631. SmartArray.prototype.forEach = function (func) {
  8632. for (var index = 0; index < this.length; index++) {
  8633. func(this.data[index]);
  8634. }
  8635. };
  8636. /**
  8637. * Sorts the full sets of data.
  8638. * @param compareFn defines the comparison function to apply.
  8639. */
  8640. SmartArray.prototype.sort = function (compareFn) {
  8641. this.data.sort(compareFn);
  8642. };
  8643. /**
  8644. * Resets the active data to an empty array.
  8645. */
  8646. SmartArray.prototype.reset = function () {
  8647. this.length = 0;
  8648. };
  8649. /**
  8650. * Releases all the data from the array as well as the array.
  8651. */
  8652. SmartArray.prototype.dispose = function () {
  8653. this.reset();
  8654. if (this.data) {
  8655. this.data.length = 0;
  8656. this.data = [];
  8657. }
  8658. };
  8659. /**
  8660. * Concats the active data with a given array.
  8661. * @param array defines the data to concatenate with.
  8662. */
  8663. SmartArray.prototype.concat = function (array) {
  8664. if (array.length === 0) {
  8665. return;
  8666. }
  8667. if (this.length + array.length > this.data.length) {
  8668. this.data.length = (this.length + array.length) * 2;
  8669. }
  8670. for (var index = 0; index < array.length; index++) {
  8671. this.data[this.length++] = (array.data || array)[index];
  8672. }
  8673. };
  8674. /**
  8675. * Returns the position of a value in the active data.
  8676. * @param value defines the value to find the index for
  8677. * @returns the index if found in the active data otherwise -1
  8678. */
  8679. SmartArray.prototype.indexOf = function (value) {
  8680. var position = this.data.indexOf(value);
  8681. if (position >= this.length) {
  8682. return -1;
  8683. }
  8684. return position;
  8685. };
  8686. /**
  8687. * Returns whether an element is part of the active data.
  8688. * @param value defines the value to look for
  8689. * @returns true if found in the active data otherwise false
  8690. */
  8691. SmartArray.prototype.contains = function (value) {
  8692. return this.indexOf(value) !== -1;
  8693. };
  8694. // Statics
  8695. SmartArray._GlobalId = 0;
  8696. return SmartArray;
  8697. }());
  8698. BABYLON.SmartArray = SmartArray;
  8699. /**
  8700. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8701. * The data in this array can only be present once
  8702. */
  8703. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8704. __extends(SmartArrayNoDuplicate, _super);
  8705. function SmartArrayNoDuplicate() {
  8706. var _this = _super !== null && _super.apply(this, arguments) || this;
  8707. _this._duplicateId = 0;
  8708. return _this;
  8709. }
  8710. /**
  8711. * Pushes a value at the end of the active data.
  8712. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8713. * @param value defines the object to push in the array.
  8714. */
  8715. SmartArrayNoDuplicate.prototype.push = function (value) {
  8716. _super.prototype.push.call(this, value);
  8717. if (!value.__smartArrayFlags) {
  8718. value.__smartArrayFlags = {};
  8719. }
  8720. value.__smartArrayFlags[this._id] = this._duplicateId;
  8721. };
  8722. /**
  8723. * Pushes a value at the end of the active data.
  8724. * If the data is already present, it won t be added again
  8725. * @param value defines the object to push in the array.
  8726. * @returns true if added false if it was already present
  8727. */
  8728. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8729. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8730. return false;
  8731. }
  8732. this.push(value);
  8733. return true;
  8734. };
  8735. /**
  8736. * Resets the active data to an empty array.
  8737. */
  8738. SmartArrayNoDuplicate.prototype.reset = function () {
  8739. _super.prototype.reset.call(this);
  8740. this._duplicateId++;
  8741. };
  8742. /**
  8743. * Concats the active data with a given array.
  8744. * This ensures no dupplicate will be present in the result.
  8745. * @param array defines the data to concatenate with.
  8746. */
  8747. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8748. if (array.length === 0) {
  8749. return;
  8750. }
  8751. if (this.length + array.length > this.data.length) {
  8752. this.data.length = (this.length + array.length) * 2;
  8753. }
  8754. for (var index = 0; index < array.length; index++) {
  8755. var item = (array.data || array)[index];
  8756. this.pushNoDuplicate(item);
  8757. }
  8758. };
  8759. return SmartArrayNoDuplicate;
  8760. }(SmartArray));
  8761. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8762. })(BABYLON || (BABYLON = {}));
  8763. //# sourceMappingURL=babylon.smartArray.js.map
  8764. var BABYLON;
  8765. (function (BABYLON) {
  8766. /** Class used to store color4 gradient */
  8767. var ColorGradient = /** @class */ (function () {
  8768. function ColorGradient() {
  8769. }
  8770. /**
  8771. * Will get a color picked randomly between color1 and color2.
  8772. * If color2 is undefined then color1 will be used
  8773. * @param result defines the target Color4 to store the result in
  8774. */
  8775. ColorGradient.prototype.getColorToRef = function (result) {
  8776. if (!this.color2) {
  8777. result.copyFrom(this.color1);
  8778. return;
  8779. }
  8780. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8781. };
  8782. return ColorGradient;
  8783. }());
  8784. BABYLON.ColorGradient = ColorGradient;
  8785. /** Class used to store color 3 gradient */
  8786. var Color3Gradient = /** @class */ (function () {
  8787. function Color3Gradient() {
  8788. }
  8789. return Color3Gradient;
  8790. }());
  8791. BABYLON.Color3Gradient = Color3Gradient;
  8792. /** Class used to store factor gradient */
  8793. var FactorGradient = /** @class */ (function () {
  8794. function FactorGradient() {
  8795. }
  8796. /**
  8797. * Will get a number picked randomly between factor1 and factor2.
  8798. * If factor2 is undefined then factor1 will be used
  8799. * @returns the picked number
  8800. */
  8801. FactorGradient.prototype.getFactor = function () {
  8802. if (this.factor2 === undefined) {
  8803. return this.factor1;
  8804. }
  8805. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8806. };
  8807. return FactorGradient;
  8808. }());
  8809. BABYLON.FactorGradient = FactorGradient;
  8810. /**
  8811. * Application error to support additional information when loading a file
  8812. */
  8813. var LoadFileError = /** @class */ (function (_super) {
  8814. __extends(LoadFileError, _super);
  8815. /**
  8816. * Creates a new LoadFileError
  8817. * @param message defines the message of the error
  8818. * @param request defines the optional XHR request
  8819. */
  8820. function LoadFileError(message, request) {
  8821. var _this = _super.call(this, message) || this;
  8822. _this.request = request;
  8823. _this.name = "LoadFileError";
  8824. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8825. return _this;
  8826. }
  8827. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8828. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8829. // Polyfill for Object.setPrototypeOf if necessary.
  8830. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8831. return LoadFileError;
  8832. }(Error));
  8833. BABYLON.LoadFileError = LoadFileError;
  8834. /**
  8835. * Class used to define a retry strategy when error happens while loading assets
  8836. */
  8837. var RetryStrategy = /** @class */ (function () {
  8838. function RetryStrategy() {
  8839. }
  8840. /**
  8841. * Function used to defines an exponential back off strategy
  8842. * @param maxRetries defines the maximum number of retries (3 by default)
  8843. * @param baseInterval defines the interval between retries
  8844. * @returns the strategy function to use
  8845. */
  8846. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8847. if (maxRetries === void 0) { maxRetries = 3; }
  8848. if (baseInterval === void 0) { baseInterval = 500; }
  8849. return function (url, request, retryIndex) {
  8850. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8851. return -1;
  8852. }
  8853. return Math.pow(2, retryIndex) * baseInterval;
  8854. };
  8855. };
  8856. return RetryStrategy;
  8857. }());
  8858. BABYLON.RetryStrategy = RetryStrategy;
  8859. // Screenshots
  8860. var screenshotCanvas;
  8861. var cloneValue = function (source, destinationObject) {
  8862. if (!source)
  8863. return null;
  8864. if (source instanceof BABYLON.Mesh) {
  8865. return null;
  8866. }
  8867. if (source instanceof BABYLON.SubMesh) {
  8868. return source.clone(destinationObject);
  8869. }
  8870. else if (source.clone) {
  8871. return source.clone();
  8872. }
  8873. return null;
  8874. };
  8875. /**
  8876. * Class containing a set of static utilities functions
  8877. */
  8878. var Tools = /** @class */ (function () {
  8879. function Tools() {
  8880. }
  8881. /**
  8882. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8883. * @param u defines the coordinate on X axis
  8884. * @param v defines the coordinate on Y axis
  8885. * @param width defines the width of the source data
  8886. * @param height defines the height of the source data
  8887. * @param pixels defines the source byte array
  8888. * @param color defines the output color
  8889. */
  8890. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8891. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8892. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8893. var position = (wrappedU + wrappedV * width) * 4;
  8894. color.r = pixels[position] / 255;
  8895. color.g = pixels[position + 1] / 255;
  8896. color.b = pixels[position + 2] / 255;
  8897. color.a = pixels[position + 3] / 255;
  8898. };
  8899. /**
  8900. * Interpolates between a and b via alpha
  8901. * @param a The lower value (returned when alpha = 0)
  8902. * @param b The upper value (returned when alpha = 1)
  8903. * @param alpha The interpolation-factor
  8904. * @return The mixed value
  8905. */
  8906. Tools.Mix = function (a, b, alpha) {
  8907. return a * (1 - alpha) + b * alpha;
  8908. };
  8909. /**
  8910. * Tries to instantiate a new object from a given class name
  8911. * @param className defines the class name to instantiate
  8912. * @returns the new object or null if the system was not able to do the instantiation
  8913. */
  8914. Tools.Instantiate = function (className) {
  8915. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8916. return Tools.RegisteredExternalClasses[className];
  8917. }
  8918. var arr = className.split(".");
  8919. var fn = (window || this);
  8920. for (var i = 0, len = arr.length; i < len; i++) {
  8921. fn = fn[arr[i]];
  8922. }
  8923. if (typeof fn !== "function") {
  8924. return null;
  8925. }
  8926. return fn;
  8927. };
  8928. /**
  8929. * Provides a slice function that will work even on IE
  8930. * @param data defines the array to slice
  8931. * @param start defines the start of the data (optional)
  8932. * @param end defines the end of the data (optional)
  8933. * @returns the new sliced array
  8934. */
  8935. Tools.Slice = function (data, start, end) {
  8936. if (data.slice) {
  8937. return data.slice(start, end);
  8938. }
  8939. return Array.prototype.slice.call(data, start, end);
  8940. };
  8941. /**
  8942. * Polyfill for setImmediate
  8943. * @param action defines the action to execute after the current execution block
  8944. */
  8945. Tools.SetImmediate = function (action) {
  8946. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8947. window.setImmediate(action);
  8948. }
  8949. else {
  8950. setTimeout(action, 1);
  8951. }
  8952. };
  8953. /**
  8954. * Function indicating if a number is an exponent of 2
  8955. * @param value defines the value to test
  8956. * @returns true if the value is an exponent of 2
  8957. */
  8958. Tools.IsExponentOfTwo = function (value) {
  8959. var count = 1;
  8960. do {
  8961. count *= 2;
  8962. } while (count < value);
  8963. return count === value;
  8964. };
  8965. /**
  8966. * Returns the nearest 32-bit single precision float representation of a Number
  8967. * @param value A Number. If the parameter is of a different type, it will get converted
  8968. * to a number or to NaN if it cannot be converted
  8969. * @returns number
  8970. */
  8971. Tools.FloatRound = function (value) {
  8972. if (Math.fround) {
  8973. return Math.fround(value);
  8974. }
  8975. return (Tools._tmpFloatArray[0] = value);
  8976. };
  8977. /**
  8978. * Find the next highest power of two.
  8979. * @param x Number to start search from.
  8980. * @return Next highest power of two.
  8981. */
  8982. Tools.CeilingPOT = function (x) {
  8983. x--;
  8984. x |= x >> 1;
  8985. x |= x >> 2;
  8986. x |= x >> 4;
  8987. x |= x >> 8;
  8988. x |= x >> 16;
  8989. x++;
  8990. return x;
  8991. };
  8992. /**
  8993. * Find the next lowest power of two.
  8994. * @param x Number to start search from.
  8995. * @return Next lowest power of two.
  8996. */
  8997. Tools.FloorPOT = function (x) {
  8998. x = x | (x >> 1);
  8999. x = x | (x >> 2);
  9000. x = x | (x >> 4);
  9001. x = x | (x >> 8);
  9002. x = x | (x >> 16);
  9003. return x - (x >> 1);
  9004. };
  9005. /**
  9006. * Find the nearest power of two.
  9007. * @param x Number to start search from.
  9008. * @return Next nearest power of two.
  9009. */
  9010. Tools.NearestPOT = function (x) {
  9011. var c = Tools.CeilingPOT(x);
  9012. var f = Tools.FloorPOT(x);
  9013. return (c - x) > (x - f) ? f : c;
  9014. };
  9015. /**
  9016. * Get the closest exponent of two
  9017. * @param value defines the value to approximate
  9018. * @param max defines the maximum value to return
  9019. * @param mode defines how to define the closest value
  9020. * @returns closest exponent of two of the given value
  9021. */
  9022. Tools.GetExponentOfTwo = function (value, max, mode) {
  9023. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9024. var pot;
  9025. switch (mode) {
  9026. case BABYLON.Engine.SCALEMODE_FLOOR:
  9027. pot = Tools.FloorPOT(value);
  9028. break;
  9029. case BABYLON.Engine.SCALEMODE_NEAREST:
  9030. pot = Tools.NearestPOT(value);
  9031. break;
  9032. case BABYLON.Engine.SCALEMODE_CEILING:
  9033. default:
  9034. pot = Tools.CeilingPOT(value);
  9035. break;
  9036. }
  9037. return Math.min(pot, max);
  9038. };
  9039. /**
  9040. * Extracts the filename from a path
  9041. * @param path defines the path to use
  9042. * @returns the filename
  9043. */
  9044. Tools.GetFilename = function (path) {
  9045. var index = path.lastIndexOf("/");
  9046. if (index < 0)
  9047. return path;
  9048. return path.substring(index + 1);
  9049. };
  9050. /**
  9051. * Extracts the "folder" part of a path (everything before the filename).
  9052. * @param uri The URI to extract the info from
  9053. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9054. * @returns The "folder" part of the path
  9055. */
  9056. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9057. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9058. var index = uri.lastIndexOf("/");
  9059. if (index < 0) {
  9060. if (returnUnchangedIfNoSlash) {
  9061. return uri;
  9062. }
  9063. return "";
  9064. }
  9065. return uri.substring(0, index + 1);
  9066. };
  9067. /**
  9068. * Extracts text content from a DOM element hierarchy
  9069. * @param element defines the root element
  9070. * @returns a string
  9071. */
  9072. Tools.GetDOMTextContent = function (element) {
  9073. var result = "";
  9074. var child = element.firstChild;
  9075. while (child) {
  9076. if (child.nodeType === 3) {
  9077. result += child.textContent;
  9078. }
  9079. child = child.nextSibling;
  9080. }
  9081. return result;
  9082. };
  9083. /**
  9084. * Convert an angle in radians to degrees
  9085. * @param angle defines the angle to convert
  9086. * @returns the angle in degrees
  9087. */
  9088. Tools.ToDegrees = function (angle) {
  9089. return angle * 180 / Math.PI;
  9090. };
  9091. /**
  9092. * Convert an angle in degrees to radians
  9093. * @param angle defines the angle to convert
  9094. * @returns the angle in radians
  9095. */
  9096. Tools.ToRadians = function (angle) {
  9097. return angle * Math.PI / 180;
  9098. };
  9099. /**
  9100. * Encode a buffer to a base64 string
  9101. * @param buffer defines the buffer to encode
  9102. * @returns the encoded string
  9103. */
  9104. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9105. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9106. var output = "";
  9107. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9108. var i = 0;
  9109. var bytes = new Uint8Array(buffer);
  9110. while (i < bytes.length) {
  9111. chr1 = bytes[i++];
  9112. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9113. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9114. enc1 = chr1 >> 2;
  9115. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9116. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9117. enc4 = chr3 & 63;
  9118. if (isNaN(chr2)) {
  9119. enc3 = enc4 = 64;
  9120. }
  9121. else if (isNaN(chr3)) {
  9122. enc4 = 64;
  9123. }
  9124. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9125. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9126. }
  9127. return "data:image/png;base64," + output;
  9128. };
  9129. /**
  9130. * Extracts minimum and maximum values from a list of indexed positions
  9131. * @param positions defines the positions to use
  9132. * @param indices defines the indices to the positions
  9133. * @param indexStart defines the start index
  9134. * @param indexCount defines the end index
  9135. * @param bias defines bias value to add to the result
  9136. * @return minimum and maximum values
  9137. */
  9138. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9139. if (bias === void 0) { bias = null; }
  9140. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9141. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9142. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9143. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  9144. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9145. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9146. }
  9147. if (bias) {
  9148. minimum.x -= minimum.x * bias.x + bias.y;
  9149. minimum.y -= minimum.y * bias.x + bias.y;
  9150. minimum.z -= minimum.z * bias.x + bias.y;
  9151. maximum.x += maximum.x * bias.x + bias.y;
  9152. maximum.y += maximum.y * bias.x + bias.y;
  9153. maximum.z += maximum.z * bias.x + bias.y;
  9154. }
  9155. return {
  9156. minimum: minimum,
  9157. maximum: maximum
  9158. };
  9159. };
  9160. /**
  9161. * Extracts minimum and maximum values from a list of positions
  9162. * @param positions defines the positions to use
  9163. * @param start defines the start index in the positions array
  9164. * @param count defines the number of positions to handle
  9165. * @param bias defines bias value to add to the result
  9166. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9167. * @return minimum and maximum values
  9168. */
  9169. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9170. if (bias === void 0) { bias = null; }
  9171. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9172. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9173. if (!stride) {
  9174. stride = 3;
  9175. }
  9176. for (var index = start; index < start + count; index++) {
  9177. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9178. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9179. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9180. }
  9181. if (bias) {
  9182. minimum.x -= minimum.x * bias.x + bias.y;
  9183. minimum.y -= minimum.y * bias.x + bias.y;
  9184. minimum.z -= minimum.z * bias.x + bias.y;
  9185. maximum.x += maximum.x * bias.x + bias.y;
  9186. maximum.y += maximum.y * bias.x + bias.y;
  9187. maximum.z += maximum.z * bias.x + bias.y;
  9188. }
  9189. return {
  9190. minimum: minimum,
  9191. maximum: maximum
  9192. };
  9193. };
  9194. /**
  9195. * Returns an array if obj is not an array
  9196. * @param obj defines the object to evaluate as an array
  9197. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9198. * @returns either obj directly if obj is an array or a new array containing obj
  9199. */
  9200. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9201. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9202. return null;
  9203. return Array.isArray(obj) ? obj : [obj];
  9204. };
  9205. /**
  9206. * Gets the pointer prefix to use
  9207. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9208. */
  9209. Tools.GetPointerPrefix = function () {
  9210. var eventPrefix = "pointer";
  9211. // Check if pointer events are supported
  9212. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9213. eventPrefix = "mouse";
  9214. }
  9215. return eventPrefix;
  9216. };
  9217. /**
  9218. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9219. * @param func - the function to be called
  9220. * @param requester - the object that will request the next frame. Falls back to window.
  9221. * @returns frame number
  9222. */
  9223. Tools.QueueNewFrame = function (func, requester) {
  9224. if (!Tools.IsWindowObjectExist()) {
  9225. return setTimeout(func, 16);
  9226. }
  9227. if (!requester) {
  9228. requester = window;
  9229. }
  9230. if (requester.requestAnimationFrame) {
  9231. return requester.requestAnimationFrame(func);
  9232. }
  9233. else if (requester.msRequestAnimationFrame) {
  9234. return requester.msRequestAnimationFrame(func);
  9235. }
  9236. else if (requester.webkitRequestAnimationFrame) {
  9237. return requester.webkitRequestAnimationFrame(func);
  9238. }
  9239. else if (requester.mozRequestAnimationFrame) {
  9240. return requester.mozRequestAnimationFrame(func);
  9241. }
  9242. else if (requester.oRequestAnimationFrame) {
  9243. return requester.oRequestAnimationFrame(func);
  9244. }
  9245. else {
  9246. return window.setTimeout(func, 16);
  9247. }
  9248. };
  9249. /**
  9250. * Ask the browser to promote the current element to fullscreen rendering mode
  9251. * @param element defines the DOM element to promote
  9252. */
  9253. Tools.RequestFullscreen = function (element) {
  9254. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9255. if (!requestFunction)
  9256. return;
  9257. requestFunction.call(element);
  9258. };
  9259. /**
  9260. * Asks the browser to exit fullscreen mode
  9261. */
  9262. Tools.ExitFullscreen = function () {
  9263. if (document.exitFullscreen) {
  9264. document.exitFullscreen();
  9265. }
  9266. else if (document.mozCancelFullScreen) {
  9267. document.mozCancelFullScreen();
  9268. }
  9269. else if (document.webkitCancelFullScreen) {
  9270. document.webkitCancelFullScreen();
  9271. }
  9272. else if (document.msCancelFullScreen) {
  9273. document.msCancelFullScreen();
  9274. }
  9275. };
  9276. /**
  9277. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9278. * @param url define the url we are trying
  9279. * @param element define the dom element where to configure the cors policy
  9280. */
  9281. Tools.SetCorsBehavior = function (url, element) {
  9282. if (url && url.indexOf("data:") === 0) {
  9283. return;
  9284. }
  9285. if (Tools.CorsBehavior) {
  9286. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9287. element.crossOrigin = Tools.CorsBehavior;
  9288. }
  9289. else {
  9290. var result = Tools.CorsBehavior(url);
  9291. if (result) {
  9292. element.crossOrigin = result;
  9293. }
  9294. }
  9295. }
  9296. };
  9297. // External files
  9298. /**
  9299. * Removes unwanted characters from an url
  9300. * @param url defines the url to clean
  9301. * @returns the cleaned url
  9302. */
  9303. Tools.CleanUrl = function (url) {
  9304. url = url.replace(/#/mg, "%23");
  9305. return url;
  9306. };
  9307. /**
  9308. * Loads an image as an HTMLImageElement.
  9309. * @param input url string, ArrayBuffer, or Blob to load
  9310. * @param onLoad callback called when the image successfully loads
  9311. * @param onError callback called when the image fails to load
  9312. * @param database database for caching
  9313. * @returns the HTMLImageElement of the loaded image
  9314. */
  9315. Tools.LoadImage = function (input, onLoad, onError, database) {
  9316. var url;
  9317. var usingObjectURL = false;
  9318. if (input instanceof ArrayBuffer) {
  9319. url = URL.createObjectURL(new Blob([input]));
  9320. usingObjectURL = true;
  9321. }
  9322. else if (input instanceof Blob) {
  9323. url = URL.createObjectURL(input);
  9324. usingObjectURL = true;
  9325. }
  9326. else {
  9327. url = Tools.CleanUrl(input);
  9328. url = Tools.PreprocessUrl(input);
  9329. }
  9330. var img = new Image();
  9331. Tools.SetCorsBehavior(url, img);
  9332. var loadHandler = function () {
  9333. if (usingObjectURL && img.src) {
  9334. URL.revokeObjectURL(img.src);
  9335. }
  9336. img.removeEventListener("load", loadHandler);
  9337. img.removeEventListener("error", errorHandler);
  9338. onLoad(img);
  9339. };
  9340. var errorHandler = function (err) {
  9341. if (usingObjectURL && img.src) {
  9342. URL.revokeObjectURL(img.src);
  9343. }
  9344. img.removeEventListener("load", loadHandler);
  9345. img.removeEventListener("error", errorHandler);
  9346. Tools.Error("Error while trying to load image: " + input);
  9347. if (onError) {
  9348. onError("Error while trying to load image: " + input, err);
  9349. }
  9350. };
  9351. img.addEventListener("load", loadHandler);
  9352. img.addEventListener("error", errorHandler);
  9353. var noIndexedDB = function () {
  9354. img.src = url;
  9355. };
  9356. var loadFromIndexedDB = function () {
  9357. if (database) {
  9358. database.loadImageFromDB(url, img);
  9359. }
  9360. };
  9361. //ANY database to do!
  9362. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9363. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9364. }
  9365. else {
  9366. if (url.indexOf("file:") !== -1) {
  9367. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9368. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9369. try {
  9370. var blobURL;
  9371. try {
  9372. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9373. }
  9374. catch (ex) {
  9375. // Chrome doesn't support oneTimeOnly parameter
  9376. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9377. }
  9378. img.src = blobURL;
  9379. usingObjectURL = true;
  9380. }
  9381. catch (e) {
  9382. img.src = "";
  9383. }
  9384. return img;
  9385. }
  9386. }
  9387. noIndexedDB();
  9388. }
  9389. return img;
  9390. };
  9391. /**
  9392. * Loads a file
  9393. * @param url url string, ArrayBuffer, or Blob to load
  9394. * @param onSuccess callback called when the file successfully loads
  9395. * @param onProgress callback called while file is loading (if the server supports this mode)
  9396. * @param database database for caching
  9397. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9398. * @param onError callback called when the file fails to load
  9399. * @returns a file request object
  9400. */
  9401. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9402. url = Tools.CleanUrl(url);
  9403. url = Tools.PreprocessUrl(url);
  9404. // If file and file input are set
  9405. if (url.indexOf("file:") !== -1) {
  9406. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9407. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9408. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9409. }
  9410. }
  9411. var loadUrl = Tools.BaseUrl + url;
  9412. var aborted = false;
  9413. var fileRequest = {
  9414. onCompleteObservable: new BABYLON.Observable(),
  9415. abort: function () { return aborted = true; },
  9416. };
  9417. var requestFile = function () {
  9418. var request = new XMLHttpRequest();
  9419. var retryHandle = null;
  9420. fileRequest.abort = function () {
  9421. aborted = true;
  9422. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9423. request.abort();
  9424. }
  9425. if (retryHandle !== null) {
  9426. clearTimeout(retryHandle);
  9427. retryHandle = null;
  9428. }
  9429. };
  9430. var retryLoop = function (retryIndex) {
  9431. request.open('GET', loadUrl, true);
  9432. if (useArrayBuffer) {
  9433. request.responseType = "arraybuffer";
  9434. }
  9435. if (onProgress) {
  9436. request.addEventListener("progress", onProgress);
  9437. }
  9438. var onLoadEnd = function () {
  9439. request.removeEventListener("loadend", onLoadEnd);
  9440. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9441. fileRequest.onCompleteObservable.clear();
  9442. };
  9443. request.addEventListener("loadend", onLoadEnd);
  9444. var onReadyStateChange = function () {
  9445. if (aborted) {
  9446. return;
  9447. }
  9448. // In case of undefined state in some browsers.
  9449. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9450. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9451. request.removeEventListener("readystatechange", onReadyStateChange);
  9452. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9453. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9454. return;
  9455. }
  9456. var retryStrategy = Tools.DefaultRetryStrategy;
  9457. if (retryStrategy) {
  9458. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9459. if (waitTime !== -1) {
  9460. // Prevent the request from completing for retry.
  9461. request.removeEventListener("loadend", onLoadEnd);
  9462. request = new XMLHttpRequest();
  9463. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9464. return;
  9465. }
  9466. }
  9467. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9468. if (onError) {
  9469. onError(request, e);
  9470. }
  9471. else {
  9472. throw e;
  9473. }
  9474. }
  9475. };
  9476. request.addEventListener("readystatechange", onReadyStateChange);
  9477. request.send();
  9478. };
  9479. retryLoop(0);
  9480. };
  9481. // Caching all files
  9482. if (database && database.enableSceneOffline) {
  9483. var noIndexedDB_1 = function (request) {
  9484. if (request && request.status > 400) {
  9485. if (onError) {
  9486. onError(request);
  9487. }
  9488. }
  9489. else {
  9490. if (!aborted) {
  9491. requestFile();
  9492. }
  9493. }
  9494. };
  9495. var loadFromIndexedDB = function () {
  9496. // TODO: database needs to support aborting and should return a IFileRequest
  9497. if (aborted) {
  9498. return;
  9499. }
  9500. if (database) {
  9501. database.loadFileFromDB(url, function (data) {
  9502. if (!aborted) {
  9503. onSuccess(data);
  9504. }
  9505. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9506. }, onProgress ? function (event) {
  9507. if (!aborted) {
  9508. onProgress(event);
  9509. }
  9510. } : undefined, noIndexedDB_1, useArrayBuffer);
  9511. }
  9512. };
  9513. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9514. }
  9515. else {
  9516. requestFile();
  9517. }
  9518. return fileRequest;
  9519. };
  9520. /**
  9521. * Load a script (identified by an url). When the url returns, the
  9522. * content of this file is added into a new script element, attached to the DOM (body element)
  9523. * @param scriptUrl defines the url of the script to laod
  9524. * @param onSuccess defines the callback called when the script is loaded
  9525. * @param onError defines the callback to call if an error occurs
  9526. */
  9527. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9528. if (!Tools.IsWindowObjectExist()) {
  9529. return;
  9530. }
  9531. var head = document.getElementsByTagName('head')[0];
  9532. var script = document.createElement('script');
  9533. script.type = 'text/javascript';
  9534. script.src = scriptUrl;
  9535. script.onload = function () {
  9536. if (onSuccess) {
  9537. onSuccess();
  9538. }
  9539. };
  9540. script.onerror = function (e) {
  9541. if (onError) {
  9542. onError("Unable to load script '" + scriptUrl + "'", e);
  9543. }
  9544. };
  9545. head.appendChild(script);
  9546. };
  9547. /**
  9548. * Loads a file from a blob
  9549. * @param fileToLoad defines the blob to use
  9550. * @param callback defines the callback to call when data is loaded
  9551. * @param progressCallback defines the callback to call during loading process
  9552. * @returns a file request object
  9553. */
  9554. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9555. var reader = new FileReader();
  9556. var request = {
  9557. onCompleteObservable: new BABYLON.Observable(),
  9558. abort: function () { return reader.abort(); },
  9559. };
  9560. reader.onloadend = function (e) {
  9561. request.onCompleteObservable.notifyObservers(request);
  9562. };
  9563. reader.onload = function (e) {
  9564. //target doesn't have result from ts 1.3
  9565. callback(e.target['result']);
  9566. };
  9567. reader.onprogress = progressCallback;
  9568. reader.readAsDataURL(fileToLoad);
  9569. return request;
  9570. };
  9571. /**
  9572. * Loads a file
  9573. * @param fileToLoad defines the file to load
  9574. * @param callback defines the callback to call when data is loaded
  9575. * @param progressCallBack defines the callback to call during loading process
  9576. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  9577. * @returns a file request object
  9578. */
  9579. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9580. var reader = new FileReader();
  9581. var request = {
  9582. onCompleteObservable: new BABYLON.Observable(),
  9583. abort: function () { return reader.abort(); },
  9584. };
  9585. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9586. reader.onerror = function (e) {
  9587. Tools.Log("Error while reading file: " + fileToLoad.name);
  9588. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9589. };
  9590. reader.onload = function (e) {
  9591. //target doesn't have result from ts 1.3
  9592. callback(e.target['result']);
  9593. };
  9594. if (progressCallBack) {
  9595. reader.onprogress = progressCallBack;
  9596. }
  9597. if (!useArrayBuffer) {
  9598. // Asynchronous read
  9599. reader.readAsText(fileToLoad);
  9600. }
  9601. else {
  9602. reader.readAsArrayBuffer(fileToLoad);
  9603. }
  9604. return request;
  9605. };
  9606. /**
  9607. * Creates a data url from a given string content
  9608. * @param content defines the content to convert
  9609. * @returns the new data url link
  9610. */
  9611. Tools.FileAsURL = function (content) {
  9612. var fileBlob = new Blob([content]);
  9613. var url = window.URL || window.webkitURL;
  9614. var link = url.createObjectURL(fileBlob);
  9615. return link;
  9616. };
  9617. /**
  9618. * Format the given number to a specific decimal format
  9619. * @param value defines the number to format
  9620. * @param decimals defines the number of decimals to use
  9621. * @returns the formatted string
  9622. */
  9623. Tools.Format = function (value, decimals) {
  9624. if (decimals === void 0) { decimals = 2; }
  9625. return value.toFixed(decimals);
  9626. };
  9627. /**
  9628. * Checks if a given vector is inside a specific range
  9629. * @param v defines the vector to test
  9630. * @param min defines the minimum range
  9631. * @param max defines the maximum range
  9632. */
  9633. Tools.CheckExtends = function (v, min, max) {
  9634. if (v.x < min.x)
  9635. min.x = v.x;
  9636. if (v.y < min.y)
  9637. min.y = v.y;
  9638. if (v.z < min.z)
  9639. min.z = v.z;
  9640. if (v.x > max.x)
  9641. max.x = v.x;
  9642. if (v.y > max.y)
  9643. max.y = v.y;
  9644. if (v.z > max.z)
  9645. max.z = v.z;
  9646. };
  9647. /**
  9648. * Tries to copy an object by duplicating every property
  9649. * @param source defines the source object
  9650. * @param destination defines the target object
  9651. * @param doNotCopyList defines a list of properties to avoid
  9652. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  9653. */
  9654. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9655. for (var prop in source) {
  9656. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9657. continue;
  9658. }
  9659. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9660. continue;
  9661. }
  9662. var sourceValue = source[prop];
  9663. var typeOfSourceValue = typeof sourceValue;
  9664. if (typeOfSourceValue === "function") {
  9665. continue;
  9666. }
  9667. try {
  9668. if (typeOfSourceValue === "object") {
  9669. if (sourceValue instanceof Array) {
  9670. destination[prop] = [];
  9671. if (sourceValue.length > 0) {
  9672. if (typeof sourceValue[0] == "object") {
  9673. for (var index = 0; index < sourceValue.length; index++) {
  9674. var clonedValue = cloneValue(sourceValue[index], destination);
  9675. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9676. destination[prop].push(clonedValue);
  9677. }
  9678. }
  9679. }
  9680. else {
  9681. destination[prop] = sourceValue.slice(0);
  9682. }
  9683. }
  9684. }
  9685. else {
  9686. destination[prop] = cloneValue(sourceValue, destination);
  9687. }
  9688. }
  9689. else {
  9690. destination[prop] = sourceValue;
  9691. }
  9692. }
  9693. catch (e) {
  9694. // Just ignore error (it could be because of a read-only property)
  9695. }
  9696. }
  9697. };
  9698. /**
  9699. * Gets a boolean indicating if the given object has no own property
  9700. * @param obj defines the object to test
  9701. * @returns true if object has no own property
  9702. */
  9703. Tools.IsEmpty = function (obj) {
  9704. for (var i in obj) {
  9705. if (obj.hasOwnProperty(i)) {
  9706. return false;
  9707. }
  9708. }
  9709. return true;
  9710. };
  9711. /**
  9712. * Function used to register events at window level
  9713. * @param events defines the events to register
  9714. */
  9715. Tools.RegisterTopRootEvents = function (events) {
  9716. for (var index = 0; index < events.length; index++) {
  9717. var event = events[index];
  9718. window.addEventListener(event.name, event.handler, false);
  9719. try {
  9720. if (window.parent) {
  9721. window.parent.addEventListener(event.name, event.handler, false);
  9722. }
  9723. }
  9724. catch (e) {
  9725. // Silently fails...
  9726. }
  9727. }
  9728. };
  9729. /**
  9730. * Function used to unregister events from window level
  9731. * @param events defines the events to unregister
  9732. */
  9733. Tools.UnregisterTopRootEvents = function (events) {
  9734. for (var index = 0; index < events.length; index++) {
  9735. var event = events[index];
  9736. window.removeEventListener(event.name, event.handler);
  9737. try {
  9738. if (window.parent) {
  9739. window.parent.removeEventListener(event.name, event.handler);
  9740. }
  9741. }
  9742. catch (e) {
  9743. // Silently fails...
  9744. }
  9745. }
  9746. };
  9747. /**
  9748. * Dumps the current bound framebuffer
  9749. * @param width defines the rendering width
  9750. * @param height defines the rendering height
  9751. * @param engine defines the hosting engine
  9752. * @param successCallback defines the callback triggered once the data are available
  9753. * @param mimeType defines the mime type of the result
  9754. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  9755. */
  9756. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9757. if (mimeType === void 0) { mimeType = "image/png"; }
  9758. // Read the contents of the framebuffer
  9759. var numberOfChannelsByLine = width * 4;
  9760. var halfHeight = height / 2;
  9761. //Reading datas from WebGL
  9762. var data = engine.readPixels(0, 0, width, height);
  9763. //To flip image on Y axis.
  9764. for (var i = 0; i < halfHeight; i++) {
  9765. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9766. var currentCell = j + i * numberOfChannelsByLine;
  9767. var targetLine = height - i - 1;
  9768. var targetCell = j + targetLine * numberOfChannelsByLine;
  9769. var temp = data[currentCell];
  9770. data[currentCell] = data[targetCell];
  9771. data[targetCell] = temp;
  9772. }
  9773. }
  9774. // Create a 2D canvas to store the result
  9775. if (!screenshotCanvas) {
  9776. screenshotCanvas = document.createElement('canvas');
  9777. }
  9778. screenshotCanvas.width = width;
  9779. screenshotCanvas.height = height;
  9780. var context = screenshotCanvas.getContext('2d');
  9781. if (context) {
  9782. // Copy the pixels to a 2D canvas
  9783. var imageData = context.createImageData(width, height);
  9784. var castData = (imageData.data);
  9785. castData.set(data);
  9786. context.putImageData(imageData, 0, 0);
  9787. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9788. }
  9789. };
  9790. /**
  9791. * Converts the canvas data to blob.
  9792. * This acts as a polyfill for browsers not supporting the to blob function.
  9793. * @param canvas Defines the canvas to extract the data from
  9794. * @param successCallback Defines the callback triggered once the data are available
  9795. * @param mimeType Defines the mime type of the result
  9796. */
  9797. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9798. if (mimeType === void 0) { mimeType = "image/png"; }
  9799. // We need HTMLCanvasElement.toBlob for HD screenshots
  9800. if (!canvas.toBlob) {
  9801. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9802. canvas.toBlob = function (callback, type, quality) {
  9803. var _this = this;
  9804. setTimeout(function () {
  9805. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9806. for (var i = 0; i < len; i++) {
  9807. arr[i] = binStr.charCodeAt(i);
  9808. }
  9809. callback(new Blob([arr]));
  9810. });
  9811. };
  9812. }
  9813. canvas.toBlob(function (blob) {
  9814. successCallback(blob);
  9815. }, mimeType);
  9816. };
  9817. /**
  9818. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9819. * @param successCallback defines the callback triggered once the data are available
  9820. * @param mimeType defines the mime type of the result
  9821. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  9822. */
  9823. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9824. if (mimeType === void 0) { mimeType = "image/png"; }
  9825. if (successCallback) {
  9826. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9827. successCallback(base64Image);
  9828. }
  9829. else {
  9830. this.ToBlob(screenshotCanvas, function (blob) {
  9831. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9832. if (("download" in document.createElement("a"))) {
  9833. if (!fileName) {
  9834. var date = new Date();
  9835. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9836. fileName = "screenshot_" + stringDate + ".png";
  9837. }
  9838. Tools.Download(blob, fileName);
  9839. }
  9840. else {
  9841. var url = URL.createObjectURL(blob);
  9842. var newWindow = window.open("");
  9843. if (!newWindow)
  9844. return;
  9845. var img = newWindow.document.createElement("img");
  9846. img.onload = function () {
  9847. // no longer need to read the blob so it's revoked
  9848. URL.revokeObjectURL(url);
  9849. };
  9850. img.src = url;
  9851. newWindow.document.body.appendChild(img);
  9852. }
  9853. }, mimeType);
  9854. }
  9855. };
  9856. /**
  9857. * Downloads a blob in the browser
  9858. * @param blob defines the blob to download
  9859. * @param fileName defines the name of the downloaded file
  9860. */
  9861. Tools.Download = function (blob, fileName) {
  9862. if (navigator && navigator.msSaveBlob) {
  9863. navigator.msSaveBlob(blob, fileName);
  9864. return;
  9865. }
  9866. var url = window.URL.createObjectURL(blob);
  9867. var a = document.createElement("a");
  9868. document.body.appendChild(a);
  9869. a.style.display = "none";
  9870. a.href = url;
  9871. a.download = fileName;
  9872. a.addEventListener("click", function () {
  9873. if (a.parentElement) {
  9874. a.parentElement.removeChild(a);
  9875. }
  9876. });
  9877. a.click();
  9878. window.URL.revokeObjectURL(url);
  9879. };
  9880. /**
  9881. * Captures a screenshot of the current rendering
  9882. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  9883. * @param engine defines the rendering engine
  9884. * @param camera defines the source camera
  9885. * @param size This parameter can be set to a single number or to an object with the
  9886. * following (optional) properties: precision, width, height. If a single number is passed,
  9887. * it will be used for both width and height. If an object is passed, the screenshot size
  9888. * will be derived from the parameters. The precision property is a multiplier allowing
  9889. * rendering at a higher or lower resolution
  9890. * @param successCallback defines the callback receives a single parameter which contains the
  9891. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9892. * src parameter of an <img> to display it
  9893. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  9894. * Check your browser for supported MIME types
  9895. */
  9896. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9897. if (mimeType === void 0) { mimeType = "image/png"; }
  9898. var width;
  9899. var height;
  9900. // If a precision value is specified
  9901. if (size.precision) {
  9902. width = Math.round(engine.getRenderWidth() * size.precision);
  9903. height = Math.round(width / engine.getAspectRatio(camera));
  9904. }
  9905. else if (size.width && size.height) {
  9906. width = size.width;
  9907. height = size.height;
  9908. }
  9909. //If passing only width, computing height to keep display canvas ratio.
  9910. else if (size.width && !size.height) {
  9911. width = size.width;
  9912. height = Math.round(width / engine.getAspectRatio(camera));
  9913. }
  9914. //If passing only height, computing width to keep display canvas ratio.
  9915. else if (size.height && !size.width) {
  9916. height = size.height;
  9917. width = Math.round(height * engine.getAspectRatio(camera));
  9918. }
  9919. //Assuming here that "size" parameter is a number
  9920. else if (!isNaN(size)) {
  9921. height = size;
  9922. width = size;
  9923. }
  9924. else {
  9925. Tools.Error("Invalid 'size' parameter !");
  9926. return;
  9927. }
  9928. if (!screenshotCanvas) {
  9929. screenshotCanvas = document.createElement('canvas');
  9930. }
  9931. screenshotCanvas.width = width;
  9932. screenshotCanvas.height = height;
  9933. var renderContext = screenshotCanvas.getContext("2d");
  9934. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9935. var newWidth = width;
  9936. var newHeight = newWidth / ratio;
  9937. if (newHeight > height) {
  9938. newHeight = height;
  9939. newWidth = newHeight * ratio;
  9940. }
  9941. var offsetX = Math.max(0, width - newWidth) / 2;
  9942. var offsetY = Math.max(0, height - newHeight) / 2;
  9943. var renderingCanvas = engine.getRenderingCanvas();
  9944. if (renderContext && renderingCanvas) {
  9945. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9946. }
  9947. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9948. };
  9949. /**
  9950. * Generates an image screenshot from the specified camera.
  9951. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  9952. * @param engine The engine to use for rendering
  9953. * @param camera The camera to use for rendering
  9954. * @param size This parameter can be set to a single number or to an object with the
  9955. * following (optional) properties: precision, width, height. If a single number is passed,
  9956. * it will be used for both width and height. If an object is passed, the screenshot size
  9957. * will be derived from the parameters. The precision property is a multiplier allowing
  9958. * rendering at a higher or lower resolution
  9959. * @param successCallback The callback receives a single parameter which contains the
  9960. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9961. * src parameter of an <img> to display it
  9962. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9963. * Check your browser for supported MIME types
  9964. * @param samples Texture samples (default: 1)
  9965. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9966. * @param fileName A name for for the downloaded file.
  9967. */
  9968. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9969. if (mimeType === void 0) { mimeType = "image/png"; }
  9970. if (samples === void 0) { samples = 1; }
  9971. if (antialiasing === void 0) { antialiasing = false; }
  9972. var width;
  9973. var height;
  9974. //If a precision value is specified
  9975. if (size.precision) {
  9976. width = Math.round(engine.getRenderWidth() * size.precision);
  9977. height = Math.round(width / engine.getAspectRatio(camera));
  9978. size = { width: width, height: height };
  9979. }
  9980. else if (size.width && size.height) {
  9981. width = size.width;
  9982. height = size.height;
  9983. }
  9984. //If passing only width, computing height to keep display canvas ratio.
  9985. else if (size.width && !size.height) {
  9986. width = size.width;
  9987. height = Math.round(width / engine.getAspectRatio(camera));
  9988. size = { width: width, height: height };
  9989. }
  9990. //If passing only height, computing width to keep display canvas ratio.
  9991. else if (size.height && !size.width) {
  9992. height = size.height;
  9993. width = Math.round(height * engine.getAspectRatio(camera));
  9994. size = { width: width, height: height };
  9995. }
  9996. //Assuming here that "size" parameter is a number
  9997. else if (!isNaN(size)) {
  9998. height = size;
  9999. width = size;
  10000. }
  10001. else {
  10002. Tools.Error("Invalid 'size' parameter !");
  10003. return;
  10004. }
  10005. var scene = camera.getScene();
  10006. var previousCamera = null;
  10007. if (scene.activeCamera !== camera) {
  10008. previousCamera = scene.activeCamera;
  10009. scene.activeCamera = camera;
  10010. }
  10011. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10012. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10013. texture.renderList = null;
  10014. texture.samples = samples;
  10015. if (antialiasing) {
  10016. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10017. }
  10018. texture.onAfterRenderObservable.add(function () {
  10019. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10020. });
  10021. scene.incrementRenderId();
  10022. scene.resetCachedMaterial();
  10023. texture.render(true);
  10024. texture.dispose();
  10025. if (previousCamera) {
  10026. scene.activeCamera = previousCamera;
  10027. }
  10028. camera.getProjectionMatrix(true); // Force cache refresh;
  10029. };
  10030. /**
  10031. * Validates if xhr data is correct
  10032. * @param xhr defines the request to validate
  10033. * @param dataType defines the expected data type
  10034. * @returns true if data is correct
  10035. */
  10036. Tools.ValidateXHRData = function (xhr, dataType) {
  10037. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10038. if (dataType === void 0) { dataType = 7; }
  10039. try {
  10040. if (dataType & 1) {
  10041. if (xhr.responseText && xhr.responseText.length > 0) {
  10042. return true;
  10043. }
  10044. else if (dataType === 1) {
  10045. return false;
  10046. }
  10047. }
  10048. if (dataType & 2) {
  10049. // Check header width and height since there is no "TGA" magic number
  10050. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10051. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10052. return true;
  10053. }
  10054. else if (dataType === 2) {
  10055. return false;
  10056. }
  10057. }
  10058. if (dataType & 4) {
  10059. // Check for the "DDS" magic number
  10060. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10061. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10062. return true;
  10063. }
  10064. else {
  10065. return false;
  10066. }
  10067. }
  10068. }
  10069. catch (e) {
  10070. // Global protection
  10071. }
  10072. return false;
  10073. };
  10074. /**
  10075. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10076. * Be aware Math.random() could cause collisions, but:
  10077. * "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"
  10078. * @returns a pseudo random id
  10079. */
  10080. Tools.RandomId = function () {
  10081. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10082. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10083. return v.toString(16);
  10084. });
  10085. };
  10086. /**
  10087. * Test if the given uri is a base64 string
  10088. * @param uri The uri to test
  10089. * @return True if the uri is a base64 string or false otherwise
  10090. */
  10091. Tools.IsBase64 = function (uri) {
  10092. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10093. };
  10094. /**
  10095. * Decode the given base64 uri.
  10096. * @param uri The uri to decode
  10097. * @return The decoded base64 data.
  10098. */
  10099. Tools.DecodeBase64 = function (uri) {
  10100. var decodedString = atob(uri.split(",")[1]);
  10101. var bufferLength = decodedString.length;
  10102. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10103. for (var i = 0; i < bufferLength; i++) {
  10104. bufferView[i] = decodedString.charCodeAt(i);
  10105. }
  10106. return bufferView.buffer;
  10107. };
  10108. Tools._AddLogEntry = function (entry) {
  10109. Tools._LogCache = entry + Tools._LogCache;
  10110. if (Tools.OnNewCacheEntry) {
  10111. Tools.OnNewCacheEntry(entry);
  10112. }
  10113. };
  10114. Tools._FormatMessage = function (message) {
  10115. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10116. var date = new Date();
  10117. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10118. };
  10119. Tools._LogDisabled = function (message) {
  10120. // nothing to do
  10121. };
  10122. Tools._LogEnabled = function (message) {
  10123. var formattedMessage = Tools._FormatMessage(message);
  10124. console.log("BJS - " + formattedMessage);
  10125. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10126. Tools._AddLogEntry(entry);
  10127. };
  10128. Tools._WarnDisabled = function (message) {
  10129. // nothing to do
  10130. };
  10131. Tools._WarnEnabled = function (message) {
  10132. var formattedMessage = Tools._FormatMessage(message);
  10133. console.warn("BJS - " + formattedMessage);
  10134. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10135. Tools._AddLogEntry(entry);
  10136. };
  10137. Tools._ErrorDisabled = function (message) {
  10138. // nothing to do
  10139. };
  10140. Tools._ErrorEnabled = function (message) {
  10141. Tools.errorsCount++;
  10142. var formattedMessage = Tools._FormatMessage(message);
  10143. console.error("BJS - " + formattedMessage);
  10144. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10145. Tools._AddLogEntry(entry);
  10146. };
  10147. Object.defineProperty(Tools, "LogCache", {
  10148. /**
  10149. * Gets current log cache (list of logs)
  10150. */
  10151. get: function () {
  10152. return Tools._LogCache;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. /**
  10158. * Clears the log cache
  10159. */
  10160. Tools.ClearLogCache = function () {
  10161. Tools._LogCache = "";
  10162. Tools.errorsCount = 0;
  10163. };
  10164. Object.defineProperty(Tools, "LogLevels", {
  10165. /**
  10166. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10167. */
  10168. set: function (level) {
  10169. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10170. Tools.Log = Tools._LogEnabled;
  10171. }
  10172. else {
  10173. Tools.Log = Tools._LogDisabled;
  10174. }
  10175. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10176. Tools.Warn = Tools._WarnEnabled;
  10177. }
  10178. else {
  10179. Tools.Warn = Tools._WarnDisabled;
  10180. }
  10181. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10182. Tools.Error = Tools._ErrorEnabled;
  10183. }
  10184. else {
  10185. Tools.Error = Tools._ErrorDisabled;
  10186. }
  10187. },
  10188. enumerable: true,
  10189. configurable: true
  10190. });
  10191. /**
  10192. * Checks if the loaded document was accessed via `file:`-Protocol.
  10193. * @returns boolean
  10194. */
  10195. Tools.IsFileURL = function () {
  10196. return location.protocol === "file:";
  10197. };
  10198. /**
  10199. * Checks if the window object exists
  10200. * @returns true if the window object exists
  10201. */
  10202. Tools.IsWindowObjectExist = function () {
  10203. return (typeof window) !== "undefined";
  10204. };
  10205. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10206. /**
  10207. * Sets the current performance log level
  10208. */
  10209. set: function (level) {
  10210. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10211. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10212. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10213. return;
  10214. }
  10215. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10216. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10217. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10218. return;
  10219. }
  10220. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10221. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10222. },
  10223. enumerable: true,
  10224. configurable: true
  10225. });
  10226. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10227. };
  10228. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10229. };
  10230. Tools._StartUserMark = function (counterName, condition) {
  10231. if (condition === void 0) { condition = true; }
  10232. if (!Tools._performance) {
  10233. if (!Tools.IsWindowObjectExist()) {
  10234. return;
  10235. }
  10236. Tools._performance = window.performance;
  10237. }
  10238. if (!condition || !Tools._performance.mark) {
  10239. return;
  10240. }
  10241. Tools._performance.mark(counterName + "-Begin");
  10242. };
  10243. Tools._EndUserMark = function (counterName, condition) {
  10244. if (condition === void 0) { condition = true; }
  10245. if (!condition || !Tools._performance.mark) {
  10246. return;
  10247. }
  10248. Tools._performance.mark(counterName + "-End");
  10249. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10250. };
  10251. Tools._StartPerformanceConsole = function (counterName, condition) {
  10252. if (condition === void 0) { condition = true; }
  10253. if (!condition) {
  10254. return;
  10255. }
  10256. Tools._StartUserMark(counterName, condition);
  10257. if (console.time) {
  10258. console.time(counterName);
  10259. }
  10260. };
  10261. Tools._EndPerformanceConsole = function (counterName, condition) {
  10262. if (condition === void 0) { condition = true; }
  10263. if (!condition) {
  10264. return;
  10265. }
  10266. Tools._EndUserMark(counterName, condition);
  10267. if (console.time) {
  10268. console.timeEnd(counterName);
  10269. }
  10270. };
  10271. Object.defineProperty(Tools, "Now", {
  10272. /**
  10273. * Gets either window.performance.now() if supported or Date.now() else
  10274. */
  10275. get: function () {
  10276. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10277. return window.performance.now();
  10278. }
  10279. return Date.now();
  10280. },
  10281. enumerable: true,
  10282. configurable: true
  10283. });
  10284. /**
  10285. * This method will return the name of the class used to create the instance of the given object.
  10286. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10287. * @param object the object to get the class name from
  10288. * @param isType defines if the object is actually a type
  10289. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10290. */
  10291. Tools.GetClassName = function (object, isType) {
  10292. if (isType === void 0) { isType = false; }
  10293. var name = null;
  10294. if (!isType && object.getClassName) {
  10295. name = object.getClassName();
  10296. }
  10297. else {
  10298. if (object instanceof Object) {
  10299. var classObj = isType ? object : Object.getPrototypeOf(object);
  10300. name = classObj.constructor["__bjsclassName__"];
  10301. }
  10302. if (!name) {
  10303. name = typeof object;
  10304. }
  10305. }
  10306. return name;
  10307. };
  10308. /**
  10309. * Gets the first element of an array satisfying a given predicate
  10310. * @param array defines the array to browse
  10311. * @param predicate defines the predicate to use
  10312. * @returns null if not found or the element
  10313. */
  10314. Tools.First = function (array, predicate) {
  10315. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10316. var el = array_1[_i];
  10317. if (predicate(el)) {
  10318. return el;
  10319. }
  10320. }
  10321. return null;
  10322. };
  10323. /**
  10324. * This method will return the name of the full name of the class, including its owning module (if any).
  10325. * 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).
  10326. * @param object the object to get the class name from
  10327. * @param isType defines if the object is actually a type
  10328. * @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.
  10329. * @ignorenaming
  10330. */
  10331. Tools.getFullClassName = function (object, isType) {
  10332. if (isType === void 0) { isType = false; }
  10333. var className = null;
  10334. var moduleName = null;
  10335. if (!isType && object.getClassName) {
  10336. className = object.getClassName();
  10337. }
  10338. else {
  10339. if (object instanceof Object) {
  10340. var classObj = isType ? object : Object.getPrototypeOf(object);
  10341. className = classObj.constructor["__bjsclassName__"];
  10342. moduleName = classObj.constructor["__bjsmoduleName__"];
  10343. }
  10344. if (!className) {
  10345. className = typeof object;
  10346. }
  10347. }
  10348. if (!className) {
  10349. return null;
  10350. }
  10351. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10352. };
  10353. /**
  10354. * Returns a promise that resolves after the given amount of time.
  10355. * @param delay Number of milliseconds to delay
  10356. * @returns Promise that resolves after the given amount of time
  10357. */
  10358. Tools.DelayAsync = function (delay) {
  10359. return new Promise(function (resolve) {
  10360. setTimeout(function () {
  10361. resolve();
  10362. }, delay);
  10363. });
  10364. };
  10365. /**
  10366. * Gets the current gradient from an array of IValueGradient
  10367. * @param ratio defines the current ratio to get
  10368. * @param gradients defines the array of IValueGradient
  10369. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10370. */
  10371. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10372. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10373. var currentGradient = gradients[gradientIndex];
  10374. var nextGradient = gradients[gradientIndex + 1];
  10375. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10376. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10377. updateFunc(currentGradient, nextGradient, scale);
  10378. return;
  10379. }
  10380. }
  10381. // Use last index if over
  10382. var lastIndex = gradients.length - 1;
  10383. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10384. };
  10385. /**
  10386. * Gets or sets the base URL to use to load assets
  10387. */
  10388. Tools.BaseUrl = "";
  10389. /**
  10390. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10391. */
  10392. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10393. /**
  10394. * Default behaviour for cors in the application.
  10395. * It can be a string if the expected behavior is identical in the entire app.
  10396. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10397. */
  10398. Tools.CorsBehavior = "anonymous";
  10399. /**
  10400. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10401. * @ignorenaming
  10402. */
  10403. Tools.UseFallbackTexture = true;
  10404. /**
  10405. * Use this object to register external classes like custom textures or material
  10406. * to allow the laoders to instantiate them
  10407. */
  10408. Tools.RegisteredExternalClasses = {};
  10409. /**
  10410. * Texture content used if a texture cannot loaded
  10411. * @ignorenaming
  10412. */
  10413. 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";
  10414. Tools._tmpFloatArray = new Float32Array(1);
  10415. /**
  10416. * Gets or sets a function used to pre-process url before using them to load assets
  10417. */
  10418. Tools.PreprocessUrl = function (url) {
  10419. return url;
  10420. };
  10421. // Logs
  10422. /**
  10423. * No log
  10424. */
  10425. Tools.NoneLogLevel = 0;
  10426. /**
  10427. * Only message logs
  10428. */
  10429. Tools.MessageLogLevel = 1;
  10430. /**
  10431. * Only warning logs
  10432. */
  10433. Tools.WarningLogLevel = 2;
  10434. /**
  10435. * Only error logs
  10436. */
  10437. Tools.ErrorLogLevel = 4;
  10438. /**
  10439. * All logs
  10440. */
  10441. Tools.AllLogLevel = 7;
  10442. Tools._LogCache = "";
  10443. /**
  10444. * Gets a value indicating the number of loading errors
  10445. * @ignorenaming
  10446. */
  10447. Tools.errorsCount = 0;
  10448. /**
  10449. * Log a message to the console
  10450. */
  10451. Tools.Log = Tools._LogEnabled;
  10452. /**
  10453. * Write a warning message to the console
  10454. */
  10455. Tools.Warn = Tools._WarnEnabled;
  10456. /**
  10457. * Write an error message to the console
  10458. */
  10459. Tools.Error = Tools._ErrorEnabled;
  10460. // Performances
  10461. /**
  10462. * No performance log
  10463. */
  10464. Tools.PerformanceNoneLogLevel = 0;
  10465. /**
  10466. * Use user marks to log performance
  10467. */
  10468. Tools.PerformanceUserMarkLogLevel = 1;
  10469. /**
  10470. * Log performance to the console
  10471. */
  10472. Tools.PerformanceConsoleLogLevel = 2;
  10473. /**
  10474. * Starts a performance counter
  10475. */
  10476. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10477. /**
  10478. * Ends a specific performance coutner
  10479. */
  10480. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10481. return Tools;
  10482. }());
  10483. BABYLON.Tools = Tools;
  10484. /**
  10485. * This class is used to track a performance counter which is number based.
  10486. * The user has access to many properties which give statistics of different nature.
  10487. *
  10488. * The implementer can track two kinds of Performance Counter: time and count.
  10489. * 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.
  10490. * 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.
  10491. */
  10492. var PerfCounter = /** @class */ (function () {
  10493. /**
  10494. * Creates a new counter
  10495. */
  10496. function PerfCounter() {
  10497. this._startMonitoringTime = 0;
  10498. this._min = 0;
  10499. this._max = 0;
  10500. this._average = 0;
  10501. this._lastSecAverage = 0;
  10502. this._current = 0;
  10503. this._totalValueCount = 0;
  10504. this._totalAccumulated = 0;
  10505. this._lastSecAccumulated = 0;
  10506. this._lastSecTime = 0;
  10507. this._lastSecValueCount = 0;
  10508. }
  10509. Object.defineProperty(PerfCounter.prototype, "min", {
  10510. /**
  10511. * Returns the smallest value ever
  10512. */
  10513. get: function () {
  10514. return this._min;
  10515. },
  10516. enumerable: true,
  10517. configurable: true
  10518. });
  10519. Object.defineProperty(PerfCounter.prototype, "max", {
  10520. /**
  10521. * Returns the biggest value ever
  10522. */
  10523. get: function () {
  10524. return this._max;
  10525. },
  10526. enumerable: true,
  10527. configurable: true
  10528. });
  10529. Object.defineProperty(PerfCounter.prototype, "average", {
  10530. /**
  10531. * Returns the average value since the performance counter is running
  10532. */
  10533. get: function () {
  10534. return this._average;
  10535. },
  10536. enumerable: true,
  10537. configurable: true
  10538. });
  10539. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10540. /**
  10541. * Returns the average value of the last second the counter was monitored
  10542. */
  10543. get: function () {
  10544. return this._lastSecAverage;
  10545. },
  10546. enumerable: true,
  10547. configurable: true
  10548. });
  10549. Object.defineProperty(PerfCounter.prototype, "current", {
  10550. /**
  10551. * Returns the current value
  10552. */
  10553. get: function () {
  10554. return this._current;
  10555. },
  10556. enumerable: true,
  10557. configurable: true
  10558. });
  10559. Object.defineProperty(PerfCounter.prototype, "total", {
  10560. /**
  10561. * Gets the accumulated total
  10562. */
  10563. get: function () {
  10564. return this._totalAccumulated;
  10565. },
  10566. enumerable: true,
  10567. configurable: true
  10568. });
  10569. Object.defineProperty(PerfCounter.prototype, "count", {
  10570. /**
  10571. * Gets the total value count
  10572. */
  10573. get: function () {
  10574. return this._totalValueCount;
  10575. },
  10576. enumerable: true,
  10577. configurable: true
  10578. });
  10579. /**
  10580. * Call this method to start monitoring a new frame.
  10581. * 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.
  10582. */
  10583. PerfCounter.prototype.fetchNewFrame = function () {
  10584. this._totalValueCount++;
  10585. this._current = 0;
  10586. this._lastSecValueCount++;
  10587. };
  10588. /**
  10589. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10590. * @param newCount the count value to add to the monitored count
  10591. * @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.
  10592. */
  10593. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10594. if (!PerfCounter.Enabled) {
  10595. return;
  10596. }
  10597. this._current += newCount;
  10598. if (fetchResult) {
  10599. this._fetchResult();
  10600. }
  10601. };
  10602. /**
  10603. * Start monitoring this performance counter
  10604. */
  10605. PerfCounter.prototype.beginMonitoring = function () {
  10606. if (!PerfCounter.Enabled) {
  10607. return;
  10608. }
  10609. this._startMonitoringTime = Tools.Now;
  10610. };
  10611. /**
  10612. * Compute the time lapsed since the previous beginMonitoring() call.
  10613. * @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
  10614. */
  10615. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10616. if (newFrame === void 0) { newFrame = true; }
  10617. if (!PerfCounter.Enabled) {
  10618. return;
  10619. }
  10620. if (newFrame) {
  10621. this.fetchNewFrame();
  10622. }
  10623. var currentTime = Tools.Now;
  10624. this._current = currentTime - this._startMonitoringTime;
  10625. if (newFrame) {
  10626. this._fetchResult();
  10627. }
  10628. };
  10629. PerfCounter.prototype._fetchResult = function () {
  10630. this._totalAccumulated += this._current;
  10631. this._lastSecAccumulated += this._current;
  10632. // Min/Max update
  10633. this._min = Math.min(this._min, this._current);
  10634. this._max = Math.max(this._max, this._current);
  10635. this._average = this._totalAccumulated / this._totalValueCount;
  10636. // Reset last sec?
  10637. var now = Tools.Now;
  10638. if ((now - this._lastSecTime) > 1000) {
  10639. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10640. this._lastSecTime = now;
  10641. this._lastSecAccumulated = 0;
  10642. this._lastSecValueCount = 0;
  10643. }
  10644. };
  10645. /**
  10646. * Gets or sets a global boolean to turn on and off all the counters
  10647. */
  10648. PerfCounter.Enabled = true;
  10649. return PerfCounter;
  10650. }());
  10651. BABYLON.PerfCounter = PerfCounter;
  10652. /**
  10653. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10654. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10655. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10656. * @param name The name of the class, case should be preserved
  10657. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10658. */
  10659. function className(name, module) {
  10660. return function (target) {
  10661. target["__bjsclassName__"] = name;
  10662. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10663. };
  10664. }
  10665. BABYLON.className = className;
  10666. /**
  10667. * An implementation of a loop for asynchronous functions.
  10668. */
  10669. var AsyncLoop = /** @class */ (function () {
  10670. /**
  10671. * Constructor.
  10672. * @param iterations the number of iterations.
  10673. * @param func the function to run each iteration
  10674. * @param successCallback the callback that will be called upon succesful execution
  10675. * @param offset starting offset.
  10676. */
  10677. function AsyncLoop(
  10678. /**
  10679. * Defines the number of iterations for the loop
  10680. */
  10681. iterations, func, successCallback, offset) {
  10682. if (offset === void 0) { offset = 0; }
  10683. this.iterations = iterations;
  10684. this.index = offset - 1;
  10685. this._done = false;
  10686. this._fn = func;
  10687. this._successCallback = successCallback;
  10688. }
  10689. /**
  10690. * Execute the next iteration. Must be called after the last iteration was finished.
  10691. */
  10692. AsyncLoop.prototype.executeNext = function () {
  10693. if (!this._done) {
  10694. if (this.index + 1 < this.iterations) {
  10695. ++this.index;
  10696. this._fn(this);
  10697. }
  10698. else {
  10699. this.breakLoop();
  10700. }
  10701. }
  10702. };
  10703. /**
  10704. * Break the loop and run the success callback.
  10705. */
  10706. AsyncLoop.prototype.breakLoop = function () {
  10707. this._done = true;
  10708. this._successCallback();
  10709. };
  10710. /**
  10711. * Create and run an async loop.
  10712. * @param iterations the number of iterations.
  10713. * @param fn the function to run each iteration
  10714. * @param successCallback the callback that will be called upon succesful execution
  10715. * @param offset starting offset.
  10716. * @returns the created async loop object
  10717. */
  10718. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  10719. if (offset === void 0) { offset = 0; }
  10720. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  10721. loop.executeNext();
  10722. return loop;
  10723. };
  10724. /**
  10725. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10726. * @param iterations total number of iterations
  10727. * @param syncedIterations number of synchronous iterations in each async iteration.
  10728. * @param fn the function to call each iteration.
  10729. * @param callback a success call back that will be called when iterating stops.
  10730. * @param breakFunction a break condition (optional)
  10731. * @param timeout timeout settings for the setTimeout function. default - 0.
  10732. * @returns the created async loop object
  10733. */
  10734. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10735. if (timeout === void 0) { timeout = 0; }
  10736. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10737. if (breakFunction && breakFunction())
  10738. loop.breakLoop();
  10739. else {
  10740. setTimeout(function () {
  10741. for (var i = 0; i < syncedIterations; ++i) {
  10742. var iteration = (loop.index * syncedIterations) + i;
  10743. if (iteration >= iterations)
  10744. break;
  10745. fn(iteration);
  10746. if (breakFunction && breakFunction()) {
  10747. loop.breakLoop();
  10748. break;
  10749. }
  10750. }
  10751. loop.executeNext();
  10752. }, timeout);
  10753. }
  10754. }, callback);
  10755. };
  10756. return AsyncLoop;
  10757. }());
  10758. BABYLON.AsyncLoop = AsyncLoop;
  10759. })(BABYLON || (BABYLON = {}));
  10760. //# sourceMappingURL=babylon.tools.js.map
  10761. var BABYLON;
  10762. (function (BABYLON) {
  10763. var PromiseStates;
  10764. (function (PromiseStates) {
  10765. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10766. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10767. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10768. })(PromiseStates || (PromiseStates = {}));
  10769. var FulFillmentAgregator = /** @class */ (function () {
  10770. function FulFillmentAgregator() {
  10771. this.count = 0;
  10772. this.target = 0;
  10773. this.results = [];
  10774. }
  10775. return FulFillmentAgregator;
  10776. }());
  10777. var InternalPromise = /** @class */ (function () {
  10778. function InternalPromise(resolver) {
  10779. var _this = this;
  10780. this._state = PromiseStates.Pending;
  10781. this._children = new Array();
  10782. this._rejectWasConsumed = false;
  10783. if (!resolver) {
  10784. return;
  10785. }
  10786. try {
  10787. resolver(function (value) {
  10788. _this._resolve(value);
  10789. }, function (reason) {
  10790. _this._reject(reason);
  10791. });
  10792. }
  10793. catch (e) {
  10794. this._reject(e);
  10795. }
  10796. }
  10797. Object.defineProperty(InternalPromise.prototype, "_result", {
  10798. get: function () {
  10799. return this._resultValue;
  10800. },
  10801. set: function (value) {
  10802. this._resultValue = value;
  10803. if (this._parent && this._parent._result === undefined) {
  10804. this._parent._result = value;
  10805. }
  10806. },
  10807. enumerable: true,
  10808. configurable: true
  10809. });
  10810. InternalPromise.prototype.catch = function (onRejected) {
  10811. return this.then(undefined, onRejected);
  10812. };
  10813. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10814. var _this = this;
  10815. var newPromise = new InternalPromise();
  10816. newPromise._onFulfilled = onFulfilled;
  10817. newPromise._onRejected = onRejected;
  10818. // Composition
  10819. this._children.push(newPromise);
  10820. newPromise._parent = this;
  10821. if (this._state !== PromiseStates.Pending) {
  10822. BABYLON.Tools.SetImmediate(function () {
  10823. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10824. var returnedValue = newPromise._resolve(_this._result);
  10825. if (returnedValue !== undefined && returnedValue !== null) {
  10826. if (returnedValue._state !== undefined) {
  10827. var returnedPromise = returnedValue;
  10828. newPromise._children.push(returnedPromise);
  10829. returnedPromise._parent = newPromise;
  10830. newPromise = returnedPromise;
  10831. }
  10832. else {
  10833. newPromise._result = returnedValue;
  10834. }
  10835. }
  10836. }
  10837. else {
  10838. newPromise._reject(_this._reason);
  10839. }
  10840. });
  10841. }
  10842. return newPromise;
  10843. };
  10844. InternalPromise.prototype._moveChildren = function (children) {
  10845. var _this = this;
  10846. var _a;
  10847. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10848. this._children.forEach(function (child) {
  10849. child._parent = _this;
  10850. });
  10851. if (this._state === PromiseStates.Fulfilled) {
  10852. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10853. var child = _b[_i];
  10854. child._resolve(this._result);
  10855. }
  10856. }
  10857. else if (this._state === PromiseStates.Rejected) {
  10858. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10859. var child = _d[_c];
  10860. child._reject(this._reason);
  10861. }
  10862. }
  10863. };
  10864. InternalPromise.prototype._resolve = function (value) {
  10865. try {
  10866. this._state = PromiseStates.Fulfilled;
  10867. var returnedValue = null;
  10868. if (this._onFulfilled) {
  10869. returnedValue = this._onFulfilled(value);
  10870. }
  10871. if (returnedValue !== undefined && returnedValue !== null) {
  10872. if (returnedValue._state !== undefined) {
  10873. // Transmit children
  10874. var returnedPromise = returnedValue;
  10875. returnedPromise._parent = this;
  10876. returnedPromise._moveChildren(this._children);
  10877. value = returnedPromise._result;
  10878. }
  10879. else {
  10880. value = returnedValue;
  10881. }
  10882. }
  10883. this._result = value;
  10884. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10885. var child = _a[_i];
  10886. child._resolve(value);
  10887. }
  10888. this._children.length = 0;
  10889. delete this._onFulfilled;
  10890. delete this._onRejected;
  10891. }
  10892. catch (e) {
  10893. this._reject(e, true);
  10894. }
  10895. };
  10896. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10897. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10898. this._state = PromiseStates.Rejected;
  10899. this._reason = reason;
  10900. if (this._onRejected && !onLocalThrow) {
  10901. try {
  10902. this._onRejected(reason);
  10903. this._rejectWasConsumed = true;
  10904. }
  10905. catch (e) {
  10906. reason = e;
  10907. }
  10908. }
  10909. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10910. var child = _a[_i];
  10911. if (this._rejectWasConsumed) {
  10912. child._resolve(null);
  10913. }
  10914. else {
  10915. child._reject(reason);
  10916. }
  10917. }
  10918. this._children.length = 0;
  10919. delete this._onFulfilled;
  10920. delete this._onRejected;
  10921. };
  10922. InternalPromise.resolve = function (value) {
  10923. var newPromise = new InternalPromise();
  10924. newPromise._resolve(value);
  10925. return newPromise;
  10926. };
  10927. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10928. promise.then(function (value) {
  10929. agregator.results[index] = value;
  10930. agregator.count++;
  10931. if (agregator.count === agregator.target) {
  10932. agregator.rootPromise._resolve(agregator.results);
  10933. }
  10934. return null;
  10935. }, function (reason) {
  10936. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10937. agregator.rootPromise._reject(reason);
  10938. }
  10939. });
  10940. };
  10941. InternalPromise.all = function (promises) {
  10942. var newPromise = new InternalPromise();
  10943. var agregator = new FulFillmentAgregator();
  10944. agregator.target = promises.length;
  10945. agregator.rootPromise = newPromise;
  10946. if (promises.length) {
  10947. for (var index = 0; index < promises.length; index++) {
  10948. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10949. }
  10950. }
  10951. else {
  10952. newPromise._resolve([]);
  10953. }
  10954. return newPromise;
  10955. };
  10956. InternalPromise.race = function (promises) {
  10957. var newPromise = new InternalPromise();
  10958. if (promises.length) {
  10959. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10960. var promise = promises_1[_i];
  10961. promise.then(function (value) {
  10962. if (newPromise) {
  10963. newPromise._resolve(value);
  10964. newPromise = null;
  10965. }
  10966. return null;
  10967. }, function (reason) {
  10968. if (newPromise) {
  10969. newPromise._reject(reason);
  10970. newPromise = null;
  10971. }
  10972. });
  10973. }
  10974. }
  10975. return newPromise;
  10976. };
  10977. return InternalPromise;
  10978. }());
  10979. /**
  10980. * Helper class that provides a small promise polyfill
  10981. */
  10982. var PromisePolyfill = /** @class */ (function () {
  10983. function PromisePolyfill() {
  10984. }
  10985. /**
  10986. * Static function used to check if the polyfill is required
  10987. * If this is the case then the function will inject the polyfill to window.Promise
  10988. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10989. */
  10990. PromisePolyfill.Apply = function (force) {
  10991. if (force === void 0) { force = false; }
  10992. if (force || typeof Promise === 'undefined') {
  10993. var root = window;
  10994. root.Promise = InternalPromise;
  10995. }
  10996. };
  10997. return PromisePolyfill;
  10998. }());
  10999. BABYLON.PromisePolyfill = PromisePolyfill;
  11000. })(BABYLON || (BABYLON = {}));
  11001. //# sourceMappingURL=babylon.promise.js.map
  11002. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11003. var BABYLON;
  11004. (function (BABYLON) {
  11005. /**
  11006. * Helper class to push actions to a pool of workers.
  11007. */
  11008. var WorkerPool = /** @class */ (function () {
  11009. /**
  11010. * Constructor
  11011. * @param workers Array of workers to use for actions
  11012. */
  11013. function WorkerPool(workers) {
  11014. this._pendingActions = new Array();
  11015. this._workerInfos = workers.map(function (worker) { return ({
  11016. worker: worker,
  11017. active: false
  11018. }); });
  11019. }
  11020. /**
  11021. * Terminates all workers and clears any pending actions.
  11022. */
  11023. WorkerPool.prototype.dispose = function () {
  11024. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11025. var workerInfo = _a[_i];
  11026. workerInfo.worker.terminate();
  11027. }
  11028. delete this._workerInfos;
  11029. delete this._pendingActions;
  11030. };
  11031. /**
  11032. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11033. * pended until a worker has completed its action.
  11034. * @param action The action to perform. Call onComplete when the action is complete.
  11035. */
  11036. WorkerPool.prototype.push = function (action) {
  11037. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11038. var workerInfo = _a[_i];
  11039. if (!workerInfo.active) {
  11040. this._execute(workerInfo, action);
  11041. return;
  11042. }
  11043. }
  11044. this._pendingActions.push(action);
  11045. };
  11046. WorkerPool.prototype._execute = function (workerInfo, action) {
  11047. var _this = this;
  11048. workerInfo.active = true;
  11049. action(workerInfo.worker, function () {
  11050. workerInfo.active = false;
  11051. var nextAction = _this._pendingActions.shift();
  11052. if (nextAction) {
  11053. _this._execute(workerInfo, nextAction);
  11054. }
  11055. });
  11056. };
  11057. return WorkerPool;
  11058. }());
  11059. BABYLON.WorkerPool = WorkerPool;
  11060. })(BABYLON || (BABYLON = {}));
  11061. //# sourceMappingURL=babylon.workerPool.js.map
  11062. var BABYLON;
  11063. (function (BABYLON) {
  11064. /**
  11065. * @hidden
  11066. **/
  11067. var _AlphaState = /** @class */ (function () {
  11068. /**
  11069. * Initializes the state.
  11070. */
  11071. function _AlphaState() {
  11072. this._isAlphaBlendDirty = false;
  11073. this._isBlendFunctionParametersDirty = false;
  11074. this._isBlendEquationParametersDirty = false;
  11075. this._isBlendConstantsDirty = false;
  11076. this._alphaBlend = false;
  11077. this._blendFunctionParameters = new Array(4);
  11078. this._blendEquationParameters = new Array(2);
  11079. this._blendConstants = new Array(4);
  11080. this.reset();
  11081. }
  11082. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11083. get: function () {
  11084. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11085. },
  11086. enumerable: true,
  11087. configurable: true
  11088. });
  11089. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11090. get: function () {
  11091. return this._alphaBlend;
  11092. },
  11093. set: function (value) {
  11094. if (this._alphaBlend === value) {
  11095. return;
  11096. }
  11097. this._alphaBlend = value;
  11098. this._isAlphaBlendDirty = true;
  11099. },
  11100. enumerable: true,
  11101. configurable: true
  11102. });
  11103. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11104. if (this._blendConstants[0] === r &&
  11105. this._blendConstants[1] === g &&
  11106. this._blendConstants[2] === b &&
  11107. this._blendConstants[3] === a) {
  11108. return;
  11109. }
  11110. this._blendConstants[0] = r;
  11111. this._blendConstants[1] = g;
  11112. this._blendConstants[2] = b;
  11113. this._blendConstants[3] = a;
  11114. this._isBlendConstantsDirty = true;
  11115. };
  11116. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11117. if (this._blendFunctionParameters[0] === value0 &&
  11118. this._blendFunctionParameters[1] === value1 &&
  11119. this._blendFunctionParameters[2] === value2 &&
  11120. this._blendFunctionParameters[3] === value3) {
  11121. return;
  11122. }
  11123. this._blendFunctionParameters[0] = value0;
  11124. this._blendFunctionParameters[1] = value1;
  11125. this._blendFunctionParameters[2] = value2;
  11126. this._blendFunctionParameters[3] = value3;
  11127. this._isBlendFunctionParametersDirty = true;
  11128. };
  11129. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11130. if (this._blendEquationParameters[0] === rgb &&
  11131. this._blendEquationParameters[1] === alpha) {
  11132. return;
  11133. }
  11134. this._blendEquationParameters[0] = rgb;
  11135. this._blendEquationParameters[1] = alpha;
  11136. this._isBlendEquationParametersDirty = true;
  11137. };
  11138. _AlphaState.prototype.reset = function () {
  11139. this._alphaBlend = false;
  11140. this._blendFunctionParameters[0] = null;
  11141. this._blendFunctionParameters[1] = null;
  11142. this._blendFunctionParameters[2] = null;
  11143. this._blendFunctionParameters[3] = null;
  11144. this._blendEquationParameters[0] = null;
  11145. this._blendEquationParameters[1] = null;
  11146. this._blendConstants[0] = null;
  11147. this._blendConstants[1] = null;
  11148. this._blendConstants[2] = null;
  11149. this._blendConstants[3] = null;
  11150. this._isAlphaBlendDirty = true;
  11151. this._isBlendFunctionParametersDirty = false;
  11152. this._isBlendEquationParametersDirty = false;
  11153. this._isBlendConstantsDirty = false;
  11154. };
  11155. _AlphaState.prototype.apply = function (gl) {
  11156. if (!this.isDirty) {
  11157. return;
  11158. }
  11159. // Alpha blend
  11160. if (this._isAlphaBlendDirty) {
  11161. if (this._alphaBlend) {
  11162. gl.enable(gl.BLEND);
  11163. }
  11164. else {
  11165. gl.disable(gl.BLEND);
  11166. }
  11167. this._isAlphaBlendDirty = false;
  11168. }
  11169. // Alpha function
  11170. if (this._isBlendFunctionParametersDirty) {
  11171. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11172. this._isBlendFunctionParametersDirty = false;
  11173. }
  11174. // Alpha equation
  11175. if (this._isBlendEquationParametersDirty) {
  11176. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11177. this._isBlendEquationParametersDirty = false;
  11178. }
  11179. // Constants
  11180. if (this._isBlendConstantsDirty) {
  11181. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11182. this._isBlendConstantsDirty = false;
  11183. }
  11184. };
  11185. return _AlphaState;
  11186. }());
  11187. BABYLON._AlphaState = _AlphaState;
  11188. })(BABYLON || (BABYLON = {}));
  11189. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11190. var BABYLON;
  11191. (function (BABYLON) {
  11192. /**
  11193. * @hidden
  11194. **/
  11195. var _DepthCullingState = /** @class */ (function () {
  11196. /**
  11197. * Initializes the state.
  11198. */
  11199. function _DepthCullingState() {
  11200. this._isDepthTestDirty = false;
  11201. this._isDepthMaskDirty = false;
  11202. this._isDepthFuncDirty = false;
  11203. this._isCullFaceDirty = false;
  11204. this._isCullDirty = false;
  11205. this._isZOffsetDirty = false;
  11206. this._isFrontFaceDirty = false;
  11207. this.reset();
  11208. }
  11209. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11210. get: function () {
  11211. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11217. get: function () {
  11218. return this._zOffset;
  11219. },
  11220. set: function (value) {
  11221. if (this._zOffset === value) {
  11222. return;
  11223. }
  11224. this._zOffset = value;
  11225. this._isZOffsetDirty = true;
  11226. },
  11227. enumerable: true,
  11228. configurable: true
  11229. });
  11230. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11231. get: function () {
  11232. return this._cullFace;
  11233. },
  11234. set: function (value) {
  11235. if (this._cullFace === value) {
  11236. return;
  11237. }
  11238. this._cullFace = value;
  11239. this._isCullFaceDirty = true;
  11240. },
  11241. enumerable: true,
  11242. configurable: true
  11243. });
  11244. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11245. get: function () {
  11246. return this._cull;
  11247. },
  11248. set: function (value) {
  11249. if (this._cull === value) {
  11250. return;
  11251. }
  11252. this._cull = value;
  11253. this._isCullDirty = true;
  11254. },
  11255. enumerable: true,
  11256. configurable: true
  11257. });
  11258. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11259. get: function () {
  11260. return this._depthFunc;
  11261. },
  11262. set: function (value) {
  11263. if (this._depthFunc === value) {
  11264. return;
  11265. }
  11266. this._depthFunc = value;
  11267. this._isDepthFuncDirty = true;
  11268. },
  11269. enumerable: true,
  11270. configurable: true
  11271. });
  11272. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11273. get: function () {
  11274. return this._depthMask;
  11275. },
  11276. set: function (value) {
  11277. if (this._depthMask === value) {
  11278. return;
  11279. }
  11280. this._depthMask = value;
  11281. this._isDepthMaskDirty = true;
  11282. },
  11283. enumerable: true,
  11284. configurable: true
  11285. });
  11286. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11287. get: function () {
  11288. return this._depthTest;
  11289. },
  11290. set: function (value) {
  11291. if (this._depthTest === value) {
  11292. return;
  11293. }
  11294. this._depthTest = value;
  11295. this._isDepthTestDirty = true;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11301. get: function () {
  11302. return this._frontFace;
  11303. },
  11304. set: function (value) {
  11305. if (this._frontFace === value) {
  11306. return;
  11307. }
  11308. this._frontFace = value;
  11309. this._isFrontFaceDirty = true;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. _DepthCullingState.prototype.reset = function () {
  11315. this._depthMask = true;
  11316. this._depthTest = true;
  11317. this._depthFunc = null;
  11318. this._cullFace = null;
  11319. this._cull = null;
  11320. this._zOffset = 0;
  11321. this._frontFace = null;
  11322. this._isDepthTestDirty = true;
  11323. this._isDepthMaskDirty = true;
  11324. this._isDepthFuncDirty = false;
  11325. this._isCullFaceDirty = false;
  11326. this._isCullDirty = false;
  11327. this._isZOffsetDirty = false;
  11328. this._isFrontFaceDirty = false;
  11329. };
  11330. _DepthCullingState.prototype.apply = function (gl) {
  11331. if (!this.isDirty) {
  11332. return;
  11333. }
  11334. // Cull
  11335. if (this._isCullDirty) {
  11336. if (this.cull) {
  11337. gl.enable(gl.CULL_FACE);
  11338. }
  11339. else {
  11340. gl.disable(gl.CULL_FACE);
  11341. }
  11342. this._isCullDirty = false;
  11343. }
  11344. // Cull face
  11345. if (this._isCullFaceDirty) {
  11346. gl.cullFace(this.cullFace);
  11347. this._isCullFaceDirty = false;
  11348. }
  11349. // Depth mask
  11350. if (this._isDepthMaskDirty) {
  11351. gl.depthMask(this.depthMask);
  11352. this._isDepthMaskDirty = false;
  11353. }
  11354. // Depth test
  11355. if (this._isDepthTestDirty) {
  11356. if (this.depthTest) {
  11357. gl.enable(gl.DEPTH_TEST);
  11358. }
  11359. else {
  11360. gl.disable(gl.DEPTH_TEST);
  11361. }
  11362. this._isDepthTestDirty = false;
  11363. }
  11364. // Depth func
  11365. if (this._isDepthFuncDirty) {
  11366. gl.depthFunc(this.depthFunc);
  11367. this._isDepthFuncDirty = false;
  11368. }
  11369. // zOffset
  11370. if (this._isZOffsetDirty) {
  11371. if (this.zOffset) {
  11372. gl.enable(gl.POLYGON_OFFSET_FILL);
  11373. gl.polygonOffset(this.zOffset, 0);
  11374. }
  11375. else {
  11376. gl.disable(gl.POLYGON_OFFSET_FILL);
  11377. }
  11378. this._isZOffsetDirty = false;
  11379. }
  11380. // Front face
  11381. if (this._isFrontFaceDirty) {
  11382. gl.frontFace(this.frontFace);
  11383. this._isFrontFaceDirty = false;
  11384. }
  11385. };
  11386. return _DepthCullingState;
  11387. }());
  11388. BABYLON._DepthCullingState = _DepthCullingState;
  11389. })(BABYLON || (BABYLON = {}));
  11390. //# sourceMappingURL=babylon.depthCullingState.js.map
  11391. var BABYLON;
  11392. (function (BABYLON) {
  11393. /**
  11394. * @hidden
  11395. **/
  11396. var _StencilState = /** @class */ (function () {
  11397. function _StencilState() {
  11398. this._isStencilTestDirty = false;
  11399. this._isStencilMaskDirty = false;
  11400. this._isStencilFuncDirty = false;
  11401. this._isStencilOpDirty = false;
  11402. this.reset();
  11403. }
  11404. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11405. get: function () {
  11406. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11407. },
  11408. enumerable: true,
  11409. configurable: true
  11410. });
  11411. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11412. get: function () {
  11413. return this._stencilFunc;
  11414. },
  11415. set: function (value) {
  11416. if (this._stencilFunc === value) {
  11417. return;
  11418. }
  11419. this._stencilFunc = value;
  11420. this._isStencilFuncDirty = true;
  11421. },
  11422. enumerable: true,
  11423. configurable: true
  11424. });
  11425. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11426. get: function () {
  11427. return this._stencilFuncRef;
  11428. },
  11429. set: function (value) {
  11430. if (this._stencilFuncRef === value) {
  11431. return;
  11432. }
  11433. this._stencilFuncRef = value;
  11434. this._isStencilFuncDirty = true;
  11435. },
  11436. enumerable: true,
  11437. configurable: true
  11438. });
  11439. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11440. get: function () {
  11441. return this._stencilFuncMask;
  11442. },
  11443. set: function (value) {
  11444. if (this._stencilFuncMask === value) {
  11445. return;
  11446. }
  11447. this._stencilFuncMask = value;
  11448. this._isStencilFuncDirty = true;
  11449. },
  11450. enumerable: true,
  11451. configurable: true
  11452. });
  11453. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11454. get: function () {
  11455. return this._stencilOpStencilFail;
  11456. },
  11457. set: function (value) {
  11458. if (this._stencilOpStencilFail === value) {
  11459. return;
  11460. }
  11461. this._stencilOpStencilFail = value;
  11462. this._isStencilOpDirty = true;
  11463. },
  11464. enumerable: true,
  11465. configurable: true
  11466. });
  11467. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11468. get: function () {
  11469. return this._stencilOpDepthFail;
  11470. },
  11471. set: function (value) {
  11472. if (this._stencilOpDepthFail === value) {
  11473. return;
  11474. }
  11475. this._stencilOpDepthFail = value;
  11476. this._isStencilOpDirty = true;
  11477. },
  11478. enumerable: true,
  11479. configurable: true
  11480. });
  11481. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11482. get: function () {
  11483. return this._stencilOpStencilDepthPass;
  11484. },
  11485. set: function (value) {
  11486. if (this._stencilOpStencilDepthPass === value) {
  11487. return;
  11488. }
  11489. this._stencilOpStencilDepthPass = value;
  11490. this._isStencilOpDirty = true;
  11491. },
  11492. enumerable: true,
  11493. configurable: true
  11494. });
  11495. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11496. get: function () {
  11497. return this._stencilMask;
  11498. },
  11499. set: function (value) {
  11500. if (this._stencilMask === value) {
  11501. return;
  11502. }
  11503. this._stencilMask = value;
  11504. this._isStencilMaskDirty = true;
  11505. },
  11506. enumerable: true,
  11507. configurable: true
  11508. });
  11509. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11510. get: function () {
  11511. return this._stencilTest;
  11512. },
  11513. set: function (value) {
  11514. if (this._stencilTest === value) {
  11515. return;
  11516. }
  11517. this._stencilTest = value;
  11518. this._isStencilTestDirty = true;
  11519. },
  11520. enumerable: true,
  11521. configurable: true
  11522. });
  11523. _StencilState.prototype.reset = function () {
  11524. this._stencilTest = false;
  11525. this._stencilMask = 0xFF;
  11526. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11527. this._stencilFuncRef = 1;
  11528. this._stencilFuncMask = 0xFF;
  11529. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11530. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11531. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11532. this._isStencilTestDirty = true;
  11533. this._isStencilMaskDirty = true;
  11534. this._isStencilFuncDirty = true;
  11535. this._isStencilOpDirty = true;
  11536. };
  11537. _StencilState.prototype.apply = function (gl) {
  11538. if (!this.isDirty) {
  11539. return;
  11540. }
  11541. // Stencil test
  11542. if (this._isStencilTestDirty) {
  11543. if (this.stencilTest) {
  11544. gl.enable(gl.STENCIL_TEST);
  11545. }
  11546. else {
  11547. gl.disable(gl.STENCIL_TEST);
  11548. }
  11549. this._isStencilTestDirty = false;
  11550. }
  11551. // Stencil mask
  11552. if (this._isStencilMaskDirty) {
  11553. gl.stencilMask(this.stencilMask);
  11554. this._isStencilMaskDirty = false;
  11555. }
  11556. // Stencil func
  11557. if (this._isStencilFuncDirty) {
  11558. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11559. this._isStencilFuncDirty = false;
  11560. }
  11561. // Stencil op
  11562. if (this._isStencilOpDirty) {
  11563. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11564. this._isStencilOpDirty = false;
  11565. }
  11566. };
  11567. return _StencilState;
  11568. }());
  11569. BABYLON._StencilState = _StencilState;
  11570. })(BABYLON || (BABYLON = {}));
  11571. //# sourceMappingURL=babylon.stencilState.js.map
  11572. var __assign = (this && this.__assign) || function () {
  11573. __assign = Object.assign || function(t) {
  11574. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11575. s = arguments[i];
  11576. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11577. t[p] = s[p];
  11578. }
  11579. return t;
  11580. };
  11581. return __assign.apply(this, arguments);
  11582. };
  11583. var BABYLON;
  11584. (function (BABYLON) {
  11585. /**
  11586. * Keeps track of all the buffer info used in engine.
  11587. */
  11588. var BufferPointer = /** @class */ (function () {
  11589. function BufferPointer() {
  11590. }
  11591. return BufferPointer;
  11592. }());
  11593. /**
  11594. * Interface for attribute information associated with buffer instanciation
  11595. */
  11596. var InstancingAttributeInfo = /** @class */ (function () {
  11597. function InstancingAttributeInfo() {
  11598. }
  11599. return InstancingAttributeInfo;
  11600. }());
  11601. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11602. /**
  11603. * Define options used to create a render target texture
  11604. */
  11605. var RenderTargetCreationOptions = /** @class */ (function () {
  11606. function RenderTargetCreationOptions() {
  11607. }
  11608. return RenderTargetCreationOptions;
  11609. }());
  11610. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11611. /**
  11612. * Define options used to create a depth texture
  11613. */
  11614. var DepthTextureCreationOptions = /** @class */ (function () {
  11615. function DepthTextureCreationOptions() {
  11616. }
  11617. return DepthTextureCreationOptions;
  11618. }());
  11619. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11620. /**
  11621. * Class used to describe the capabilities of the engine relatively to the current browser
  11622. */
  11623. var EngineCapabilities = /** @class */ (function () {
  11624. function EngineCapabilities() {
  11625. }
  11626. return EngineCapabilities;
  11627. }());
  11628. BABYLON.EngineCapabilities = EngineCapabilities;
  11629. /**
  11630. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11631. */
  11632. var Engine = /** @class */ (function () {
  11633. /**
  11634. * Creates a new engine
  11635. * @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
  11636. * @param antialias defines enable antialiasing (default: false)
  11637. * @param options defines further options to be sent to the getContext() function
  11638. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11639. */
  11640. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11641. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11642. var _this = this;
  11643. // Public members
  11644. /**
  11645. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11646. */
  11647. this.forcePOTTextures = false;
  11648. /**
  11649. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11650. */
  11651. this.isFullscreen = false;
  11652. /**
  11653. * Gets a boolean indicating if the pointer is currently locked
  11654. */
  11655. this.isPointerLock = false;
  11656. /**
  11657. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11658. */
  11659. this.cullBackFaces = true;
  11660. /**
  11661. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11662. */
  11663. this.renderEvenInBackground = true;
  11664. /**
  11665. * Gets or sets a boolean indicating that cache can be kept between frames
  11666. */
  11667. this.preventCacheWipeBetweenFrames = false;
  11668. /**
  11669. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11670. **/
  11671. this.enableOfflineSupport = false;
  11672. /**
  11673. * 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)
  11674. **/
  11675. this.disableManifestCheck = false;
  11676. /**
  11677. * Gets the list of created scenes
  11678. */
  11679. this.scenes = new Array();
  11680. /**
  11681. * Gets the list of created postprocesses
  11682. */
  11683. this.postProcesses = new Array();
  11684. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11685. this.validateShaderPrograms = false;
  11686. // Observables
  11687. /**
  11688. * Observable event triggered each time the rendering canvas is resized
  11689. */
  11690. this.onResizeObservable = new BABYLON.Observable();
  11691. /**
  11692. * Observable event triggered each time the canvas loses focus
  11693. */
  11694. this.onCanvasBlurObservable = new BABYLON.Observable();
  11695. /**
  11696. * Observable event triggered each time the canvas gains focus
  11697. */
  11698. this.onCanvasFocusObservable = new BABYLON.Observable();
  11699. /**
  11700. * Observable event triggered each time the canvas receives pointerout event
  11701. */
  11702. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11703. /**
  11704. * Observable event triggered before each texture is initialized
  11705. */
  11706. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11707. //WebVR
  11708. this._vrDisplay = undefined;
  11709. this._vrSupported = false;
  11710. this._vrExclusivePointerMode = false;
  11711. // Uniform buffers list
  11712. /**
  11713. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11714. */
  11715. this.disableUniformBuffers = false;
  11716. /** @hidden */
  11717. this._uniformBuffers = new Array();
  11718. // Observables
  11719. /**
  11720. * Observable raised when the engine begins a new frame
  11721. */
  11722. this.onBeginFrameObservable = new BABYLON.Observable();
  11723. /**
  11724. * Observable raised when the engine ends the current frame
  11725. */
  11726. this.onEndFrameObservable = new BABYLON.Observable();
  11727. /**
  11728. * Observable raised when the engine is about to compile a shader
  11729. */
  11730. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11731. /**
  11732. * Observable raised when the engine has jsut compiled a shader
  11733. */
  11734. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11735. this._windowIsBackground = false;
  11736. this._webGLVersion = 1.0;
  11737. /** @hidden */
  11738. this._badOS = false;
  11739. /** @hidden */
  11740. this._badDesktopOS = false;
  11741. /**
  11742. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11743. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11744. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11745. */
  11746. this.disableTextureBindingOptimization = false;
  11747. /**
  11748. * Observable signaled when VR display mode changes
  11749. */
  11750. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11751. /**
  11752. * Observable signaled when VR request present is complete
  11753. */
  11754. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11755. /**
  11756. * Observable signaled when VR request present starts
  11757. */
  11758. this.onVRRequestPresentStart = new BABYLON.Observable();
  11759. this._colorWrite = true;
  11760. /** @hidden */
  11761. this._drawCalls = new BABYLON.PerfCounter();
  11762. /** @hidden */
  11763. this._textureCollisions = new BABYLON.PerfCounter();
  11764. this._renderingQueueLaunched = false;
  11765. this._activeRenderLoops = new Array();
  11766. // Deterministic lockstepMaxSteps
  11767. this._deterministicLockstep = false;
  11768. this._lockstepMaxSteps = 4;
  11769. // Lost context
  11770. /**
  11771. * Observable signaled when a context lost event is raised
  11772. */
  11773. this.onContextLostObservable = new BABYLON.Observable();
  11774. /**
  11775. * Observable signaled when a context restored event is raised
  11776. */
  11777. this.onContextRestoredObservable = new BABYLON.Observable();
  11778. this._contextWasLost = false;
  11779. this._doNotHandleContextLost = false;
  11780. // FPS
  11781. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11782. this._fps = 60;
  11783. this._deltaTime = 0;
  11784. /**
  11785. * Turn this value on if you want to pause FPS computation when in background
  11786. */
  11787. this.disablePerformanceMonitorInBackground = false;
  11788. // States
  11789. /** @hidden */
  11790. this._depthCullingState = new BABYLON._DepthCullingState();
  11791. /** @hidden */
  11792. this._stencilState = new BABYLON._StencilState();
  11793. /** @hidden */
  11794. this._alphaState = new BABYLON._AlphaState();
  11795. /** @hidden */
  11796. this._alphaMode = Engine.ALPHA_DISABLE;
  11797. // Cache
  11798. this._internalTexturesCache = new Array();
  11799. /** @hidden */
  11800. this._activeChannel = 0;
  11801. this._currentTextureChannel = -1;
  11802. /** @hidden */
  11803. this._boundTexturesCache = {};
  11804. this._compiledEffects = {};
  11805. this._vertexAttribArraysEnabled = [];
  11806. this._uintIndicesCurrentlySet = false;
  11807. this._currentBoundBuffer = new Array();
  11808. /** @hidden */
  11809. this._currentFramebuffer = null;
  11810. this._currentBufferPointers = new Array();
  11811. this._currentInstanceLocations = new Array();
  11812. this._currentInstanceBuffers = new Array();
  11813. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11814. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11815. this._vaoRecordInProgress = false;
  11816. this._mustWipeVertexAttributes = false;
  11817. this._nextFreeTextureSlots = new Array();
  11818. this._maxSimultaneousTextures = 0;
  11819. this._activeRequests = new Array();
  11820. // Hardware supported Compressed Textures
  11821. this._texturesSupported = new Array();
  11822. /**
  11823. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11824. */
  11825. this.premultipliedAlpha = true;
  11826. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11827. this._onVRFullScreenTriggered = function () {
  11828. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11829. //get the old size before we change
  11830. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11831. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11832. //get the width and height, change the render size
  11833. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11834. _this.setHardwareScalingLevel(1);
  11835. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11836. }
  11837. else {
  11838. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11839. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11840. }
  11841. };
  11842. this._unpackFlipYCached = null;
  11843. /**
  11844. * In case you are sharing the context with other applications, it might
  11845. * be interested to not cache the unpack flip y state to ensure a consistent
  11846. * value would be set.
  11847. */
  11848. this.enableUnpackFlipYCached = true;
  11849. this._boundUniforms = {};
  11850. // Register promises
  11851. BABYLON.PromisePolyfill.Apply();
  11852. var canvas = null;
  11853. Engine.Instances.push(this);
  11854. if (!canvasOrContext) {
  11855. return;
  11856. }
  11857. options = options || {};
  11858. if (canvasOrContext.getContext) {
  11859. canvas = canvasOrContext;
  11860. this._renderingCanvas = canvas;
  11861. if (antialias != null) {
  11862. options.antialias = antialias;
  11863. }
  11864. if (options.deterministicLockstep === undefined) {
  11865. options.deterministicLockstep = false;
  11866. }
  11867. if (options.lockstepMaxSteps === undefined) {
  11868. options.lockstepMaxSteps = 4;
  11869. }
  11870. if (options.preserveDrawingBuffer === undefined) {
  11871. options.preserveDrawingBuffer = false;
  11872. }
  11873. if (options.audioEngine === undefined) {
  11874. options.audioEngine = true;
  11875. }
  11876. if (options.stencil === undefined) {
  11877. options.stencil = true;
  11878. }
  11879. if (options.premultipliedAlpha === false) {
  11880. this.premultipliedAlpha = false;
  11881. }
  11882. this._deterministicLockstep = options.deterministicLockstep;
  11883. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11884. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11885. // Exceptions
  11886. if (navigator && navigator.userAgent) {
  11887. var ua = navigator.userAgent;
  11888. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11889. var exception = _a[_i];
  11890. var key = exception.key;
  11891. var targets = exception.targets;
  11892. if (ua.indexOf(key) > -1) {
  11893. if (exception.capture && exception.captureConstraint) {
  11894. var capture = exception.capture;
  11895. var constraint = exception.captureConstraint;
  11896. var regex = new RegExp(capture);
  11897. var matches = regex.exec(ua);
  11898. if (matches && matches.length > 0) {
  11899. var capturedValue = parseInt(matches[matches.length - 1]);
  11900. if (capturedValue >= constraint) {
  11901. continue;
  11902. }
  11903. }
  11904. }
  11905. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11906. var target = targets_1[_b];
  11907. switch (target) {
  11908. case "uniformBuffer":
  11909. this.disableUniformBuffers = true;
  11910. break;
  11911. case "textureBindingOptimization":
  11912. this.disableTextureBindingOptimization = true;
  11913. break;
  11914. }
  11915. }
  11916. }
  11917. }
  11918. }
  11919. // GL
  11920. if (!options.disableWebGL2Support) {
  11921. try {
  11922. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11923. if (this._gl) {
  11924. this._webGLVersion = 2.0;
  11925. }
  11926. }
  11927. catch (e) {
  11928. // Do nothing
  11929. }
  11930. }
  11931. if (!this._gl) {
  11932. if (!canvas) {
  11933. throw new Error("The provided canvas is null or undefined.");
  11934. }
  11935. try {
  11936. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11937. }
  11938. catch (e) {
  11939. throw new Error("WebGL not supported");
  11940. }
  11941. }
  11942. if (!this._gl) {
  11943. throw new Error("WebGL not supported");
  11944. }
  11945. this._onCanvasFocus = function () {
  11946. _this.onCanvasFocusObservable.notifyObservers(_this);
  11947. };
  11948. this._onCanvasBlur = function () {
  11949. _this.onCanvasBlurObservable.notifyObservers(_this);
  11950. };
  11951. canvas.addEventListener("focus", this._onCanvasFocus);
  11952. canvas.addEventListener("blur", this._onCanvasBlur);
  11953. this._onBlur = function () {
  11954. if (_this.disablePerformanceMonitorInBackground) {
  11955. _this._performanceMonitor.disable();
  11956. }
  11957. _this._windowIsBackground = true;
  11958. };
  11959. this._onFocus = function () {
  11960. if (_this.disablePerformanceMonitorInBackground) {
  11961. _this._performanceMonitor.enable();
  11962. }
  11963. _this._windowIsBackground = false;
  11964. };
  11965. this._onCanvasPointerOut = function (ev) {
  11966. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11967. };
  11968. window.addEventListener("blur", this._onBlur);
  11969. window.addEventListener("focus", this._onFocus);
  11970. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11971. // Context lost
  11972. if (!this._doNotHandleContextLost) {
  11973. this._onContextLost = function (evt) {
  11974. evt.preventDefault();
  11975. _this._contextWasLost = true;
  11976. BABYLON.Tools.Warn("WebGL context lost.");
  11977. _this.onContextLostObservable.notifyObservers(_this);
  11978. };
  11979. this._onContextRestored = function (evt) {
  11980. // Adding a timeout to avoid race condition at browser level
  11981. setTimeout(function () {
  11982. // Rebuild gl context
  11983. _this._initGLContext();
  11984. // Rebuild effects
  11985. _this._rebuildEffects();
  11986. // Rebuild textures
  11987. _this._rebuildInternalTextures();
  11988. // Rebuild buffers
  11989. _this._rebuildBuffers();
  11990. // Cache
  11991. _this.wipeCaches(true);
  11992. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11993. _this.onContextRestoredObservable.notifyObservers(_this);
  11994. _this._contextWasLost = false;
  11995. }, 0);
  11996. };
  11997. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11998. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11999. }
  12000. }
  12001. else {
  12002. this._gl = canvasOrContext;
  12003. this._renderingCanvas = this._gl.canvas;
  12004. if (this._gl.renderbufferStorageMultisample) {
  12005. this._webGLVersion = 2.0;
  12006. }
  12007. options.stencil = this._gl.getContextAttributes().stencil;
  12008. }
  12009. // Viewport
  12010. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12011. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12012. this.resize();
  12013. this._isStencilEnable = options.stencil ? true : false;
  12014. this._initGLContext();
  12015. if (canvas) {
  12016. // Fullscreen
  12017. this._onFullscreenChange = function () {
  12018. if (document.fullscreen !== undefined) {
  12019. _this.isFullscreen = document.fullscreen;
  12020. }
  12021. else if (document.mozFullScreen !== undefined) {
  12022. _this.isFullscreen = document.mozFullScreen;
  12023. }
  12024. else if (document.webkitIsFullScreen !== undefined) {
  12025. _this.isFullscreen = document.webkitIsFullScreen;
  12026. }
  12027. else if (document.msIsFullScreen !== undefined) {
  12028. _this.isFullscreen = document.msIsFullScreen;
  12029. }
  12030. // Pointer lock
  12031. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12032. canvas.requestPointerLock = canvas.requestPointerLock ||
  12033. canvas.msRequestPointerLock ||
  12034. canvas.mozRequestPointerLock ||
  12035. canvas.webkitRequestPointerLock;
  12036. if (canvas.requestPointerLock) {
  12037. canvas.requestPointerLock();
  12038. }
  12039. }
  12040. };
  12041. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12042. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12043. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12044. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12045. // Pointer lock
  12046. this._onPointerLockChange = function () {
  12047. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12048. document.webkitPointerLockElement === canvas ||
  12049. document.msPointerLockElement === canvas ||
  12050. document.pointerLockElement === canvas);
  12051. };
  12052. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12053. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12054. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12055. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12056. this._onVRDisplayPointerRestricted = function () {
  12057. if (canvas) {
  12058. canvas.requestPointerLock();
  12059. }
  12060. };
  12061. this._onVRDisplayPointerUnrestricted = function () {
  12062. document.exitPointerLock();
  12063. };
  12064. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12065. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12066. }
  12067. // Create Audio Engine if needed.
  12068. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12069. Engine.audioEngine = Engine.AudioEngineFactory(this);
  12070. }
  12071. // Prepare buffer pointers
  12072. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12073. this._currentBufferPointers[i] = new BufferPointer();
  12074. }
  12075. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12076. // Load WebVR Devices
  12077. if (options.autoEnableWebVR) {
  12078. this.initWebVR();
  12079. }
  12080. // Detect if we are running on a faulty buggy OS.
  12081. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12082. // Detect if we are running on a faulty buggy desktop OS.
  12083. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12084. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12085. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12086. }
  12087. Object.defineProperty(Engine, "LastCreatedEngine", {
  12088. /**
  12089. * Gets the latest created engine
  12090. */
  12091. get: function () {
  12092. if (Engine.Instances.length === 0) {
  12093. return null;
  12094. }
  12095. return Engine.Instances[Engine.Instances.length - 1];
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. Object.defineProperty(Engine, "LastCreatedScene", {
  12101. /**
  12102. * Gets the latest created scene
  12103. */
  12104. get: function () {
  12105. var lastCreatedEngine = Engine.LastCreatedEngine;
  12106. if (!lastCreatedEngine) {
  12107. return null;
  12108. }
  12109. if (lastCreatedEngine.scenes.length === 0) {
  12110. return null;
  12111. }
  12112. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. /**
  12118. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12119. * @param flag defines which part of the materials must be marked as dirty
  12120. * @param predicate defines a predicate used to filter which materials should be affected
  12121. */
  12122. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12123. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12124. var engine = Engine.Instances[engineIndex];
  12125. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12126. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12127. }
  12128. }
  12129. };
  12130. Object.defineProperty(Engine, "Version", {
  12131. /**
  12132. * Returns the current version of the framework
  12133. */
  12134. get: function () {
  12135. return "3.3.0-rc.1";
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12141. /**
  12142. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12143. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12144. */
  12145. get: function () {
  12146. return this._vrExclusivePointerMode;
  12147. },
  12148. enumerable: true,
  12149. configurable: true
  12150. });
  12151. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12152. /**
  12153. * Gets a boolean indicating that the engine supports uniform buffers
  12154. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12155. */
  12156. get: function () {
  12157. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12158. },
  12159. enumerable: true,
  12160. configurable: true
  12161. });
  12162. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12163. /**
  12164. * Gets a boolean indicating that only power of 2 textures are supported
  12165. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12166. */
  12167. get: function () {
  12168. return this._webGLVersion < 2 || this.forcePOTTextures;
  12169. },
  12170. enumerable: true,
  12171. configurable: true
  12172. });
  12173. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12174. /**
  12175. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12176. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12177. */
  12178. get: function () {
  12179. return this._doNotHandleContextLost;
  12180. },
  12181. set: function (value) {
  12182. this._doNotHandleContextLost = value;
  12183. },
  12184. enumerable: true,
  12185. configurable: true
  12186. });
  12187. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12188. /**
  12189. * Gets the performance monitor attached to this engine
  12190. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12191. */
  12192. get: function () {
  12193. return this._performanceMonitor;
  12194. },
  12195. enumerable: true,
  12196. configurable: true
  12197. });
  12198. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12199. /**
  12200. * Gets the list of texture formats supported
  12201. */
  12202. get: function () {
  12203. return this._texturesSupported;
  12204. },
  12205. enumerable: true,
  12206. configurable: true
  12207. });
  12208. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12209. /**
  12210. * Gets the list of texture formats in use
  12211. */
  12212. get: function () {
  12213. return this._textureFormatInUse;
  12214. },
  12215. enumerable: true,
  12216. configurable: true
  12217. });
  12218. Object.defineProperty(Engine.prototype, "currentViewport", {
  12219. /**
  12220. * Gets the current viewport
  12221. */
  12222. get: function () {
  12223. return this._cachedViewport;
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12229. /**
  12230. * Gets the default empty texture
  12231. */
  12232. get: function () {
  12233. if (!this._emptyTexture) {
  12234. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12235. }
  12236. return this._emptyTexture;
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12242. /**
  12243. * Gets the default empty 3D texture
  12244. */
  12245. get: function () {
  12246. if (!this._emptyTexture3D) {
  12247. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12248. }
  12249. return this._emptyTexture3D;
  12250. },
  12251. enumerable: true,
  12252. configurable: true
  12253. });
  12254. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12255. /**
  12256. * Gets the default empty cube texture
  12257. */
  12258. get: function () {
  12259. if (!this._emptyCubeTexture) {
  12260. var faceData = new Uint8Array(4);
  12261. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12262. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12263. }
  12264. return this._emptyCubeTexture;
  12265. },
  12266. enumerable: true,
  12267. configurable: true
  12268. });
  12269. Engine.prototype._rebuildInternalTextures = function () {
  12270. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12271. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12272. var internalTexture = currentState_1[_i];
  12273. internalTexture._rebuild();
  12274. }
  12275. };
  12276. Engine.prototype._rebuildEffects = function () {
  12277. for (var key in this._compiledEffects) {
  12278. var effect = this._compiledEffects[key];
  12279. effect._prepareEffect();
  12280. }
  12281. BABYLON.Effect.ResetCache();
  12282. };
  12283. Engine.prototype._rebuildBuffers = function () {
  12284. // Index / Vertex
  12285. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12286. var scene = _a[_i];
  12287. scene.resetCachedMaterial();
  12288. scene._rebuildGeometries();
  12289. scene._rebuildTextures();
  12290. }
  12291. // Uniforms
  12292. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12293. var uniformBuffer = _c[_b];
  12294. uniformBuffer._rebuild();
  12295. }
  12296. };
  12297. Engine.prototype._initGLContext = function () {
  12298. // Caps
  12299. this._caps = new EngineCapabilities();
  12300. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12301. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12302. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12303. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12304. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12305. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12306. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12307. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12308. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12309. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12310. // Infos
  12311. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12312. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12313. if (rendererInfo != null) {
  12314. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12315. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12316. }
  12317. if (!this._glVendor) {
  12318. this._glVendor = "Unknown vendor";
  12319. }
  12320. if (!this._glRenderer) {
  12321. this._glRenderer = "Unknown renderer";
  12322. }
  12323. // Constants
  12324. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12325. if (this._gl.RGBA16F !== 0x881A) {
  12326. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12327. }
  12328. if (this._gl.RGBA32F !== 0x8814) {
  12329. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12330. }
  12331. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12332. this._gl.DEPTH24_STENCIL8 = 35056;
  12333. }
  12334. // Extensions
  12335. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12336. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12337. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12338. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12339. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12340. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12341. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12342. 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');
  12343. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12344. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12345. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12346. this._caps.highPrecisionShaderSupported = true;
  12347. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12348. if (this._caps.timerQuery) {
  12349. if (this._webGLVersion === 1) {
  12350. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12351. }
  12352. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12353. }
  12354. // Checks if some of the format renders first to allow the use of webgl inspector.
  12355. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12356. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12357. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12358. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12359. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12360. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12361. if (this._webGLVersion > 1) {
  12362. this._gl.HALF_FLOAT_OES = 0x140B;
  12363. }
  12364. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12365. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12366. // Draw buffers
  12367. if (this._webGLVersion > 1) {
  12368. this._caps.drawBuffersExtension = true;
  12369. }
  12370. else {
  12371. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12372. if (drawBuffersExtension !== null) {
  12373. this._caps.drawBuffersExtension = true;
  12374. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12375. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12376. for (var i = 0; i < 16; i++) {
  12377. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12378. }
  12379. }
  12380. else {
  12381. this._caps.drawBuffersExtension = false;
  12382. }
  12383. }
  12384. // Depth Texture
  12385. if (this._webGLVersion > 1) {
  12386. this._caps.depthTextureExtension = true;
  12387. }
  12388. else {
  12389. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12390. if (depthTextureExtension != null) {
  12391. this._caps.depthTextureExtension = true;
  12392. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12393. }
  12394. }
  12395. // Vertex array object
  12396. if (this._webGLVersion > 1) {
  12397. this._caps.vertexArrayObject = true;
  12398. }
  12399. else {
  12400. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12401. if (vertexArrayObjectExtension != null) {
  12402. this._caps.vertexArrayObject = true;
  12403. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12404. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12405. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12406. }
  12407. else {
  12408. this._caps.vertexArrayObject = false;
  12409. }
  12410. }
  12411. // Instances count
  12412. if (this._webGLVersion > 1) {
  12413. this._caps.instancedArrays = true;
  12414. }
  12415. else {
  12416. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12417. if (instanceExtension != null) {
  12418. this._caps.instancedArrays = true;
  12419. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12420. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12421. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12422. }
  12423. else {
  12424. this._caps.instancedArrays = false;
  12425. }
  12426. }
  12427. // Intelligently add supported compressed formats in order to check for.
  12428. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12429. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12430. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12431. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12432. if (this._caps.astc)
  12433. this.texturesSupported.push('-astc.ktx');
  12434. if (this._caps.s3tc)
  12435. this.texturesSupported.push('-dxt.ktx');
  12436. if (this._caps.pvrtc)
  12437. this.texturesSupported.push('-pvrtc.ktx');
  12438. if (this._caps.etc2)
  12439. this.texturesSupported.push('-etc2.ktx');
  12440. if (this._caps.etc1)
  12441. this.texturesSupported.push('-etc1.ktx');
  12442. if (this._gl.getShaderPrecisionFormat) {
  12443. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12444. if (highp) {
  12445. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12446. }
  12447. }
  12448. // Depth buffer
  12449. this.setDepthBuffer(true);
  12450. this.setDepthFunctionToLessOrEqual();
  12451. this.setDepthWrite(true);
  12452. // Texture maps
  12453. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12454. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12455. this._nextFreeTextureSlots.push(slot);
  12456. }
  12457. };
  12458. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12459. /**
  12460. * Gets version of the current webGL context
  12461. */
  12462. get: function () {
  12463. return this._webGLVersion;
  12464. },
  12465. enumerable: true,
  12466. configurable: true
  12467. });
  12468. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12469. /**
  12470. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12471. */
  12472. get: function () {
  12473. return this._isStencilEnable;
  12474. },
  12475. enumerable: true,
  12476. configurable: true
  12477. });
  12478. Engine.prototype._prepareWorkingCanvas = function () {
  12479. if (this._workingCanvas) {
  12480. return;
  12481. }
  12482. this._workingCanvas = document.createElement("canvas");
  12483. var context = this._workingCanvas.getContext("2d");
  12484. if (context) {
  12485. this._workingContext = context;
  12486. }
  12487. };
  12488. /**
  12489. * Reset the texture cache to empty state
  12490. */
  12491. Engine.prototype.resetTextureCache = function () {
  12492. for (var key in this._boundTexturesCache) {
  12493. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12494. continue;
  12495. }
  12496. var boundTexture = this._boundTexturesCache[key];
  12497. if (boundTexture) {
  12498. this._removeDesignatedSlot(boundTexture);
  12499. }
  12500. this._boundTexturesCache[key] = null;
  12501. }
  12502. if (!this.disableTextureBindingOptimization) {
  12503. this._nextFreeTextureSlots = [];
  12504. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12505. this._nextFreeTextureSlots.push(slot);
  12506. }
  12507. }
  12508. this._currentTextureChannel = -1;
  12509. };
  12510. /**
  12511. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12512. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12513. * @returns true if engine is in deterministic lock step mode
  12514. */
  12515. Engine.prototype.isDeterministicLockStep = function () {
  12516. return this._deterministicLockstep;
  12517. };
  12518. /**
  12519. * Gets the max steps when engine is running in deterministic lock step
  12520. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12521. * @returns the max steps
  12522. */
  12523. Engine.prototype.getLockstepMaxSteps = function () {
  12524. return this._lockstepMaxSteps;
  12525. };
  12526. /**
  12527. * Gets an object containing information about the current webGL context
  12528. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12529. */
  12530. Engine.prototype.getGlInfo = function () {
  12531. return {
  12532. vendor: this._glVendor,
  12533. renderer: this._glRenderer,
  12534. version: this._glVersion
  12535. };
  12536. };
  12537. /**
  12538. * Gets current aspect ratio
  12539. * @param camera defines the camera to use to get the aspect ratio
  12540. * @param useScreen defines if screen size must be used (or the current render target if any)
  12541. * @returns a number defining the aspect ratio
  12542. */
  12543. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12544. if (useScreen === void 0) { useScreen = false; }
  12545. var viewport = camera.viewport;
  12546. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12547. };
  12548. /**
  12549. * Gets current screen aspect ratio
  12550. * @returns a number defining the aspect ratio
  12551. */
  12552. Engine.prototype.getScreenAspectRatio = function () {
  12553. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12554. };
  12555. /**
  12556. * Gets the current render width
  12557. * @param useScreen defines if screen size must be used (or the current render target if any)
  12558. * @returns a number defining the current render width
  12559. */
  12560. Engine.prototype.getRenderWidth = function (useScreen) {
  12561. if (useScreen === void 0) { useScreen = false; }
  12562. if (!useScreen && this._currentRenderTarget) {
  12563. return this._currentRenderTarget.width;
  12564. }
  12565. return this._gl.drawingBufferWidth;
  12566. };
  12567. /**
  12568. * Gets the current render height
  12569. * @param useScreen defines if screen size must be used (or the current render target if any)
  12570. * @returns a number defining the current render height
  12571. */
  12572. Engine.prototype.getRenderHeight = function (useScreen) {
  12573. if (useScreen === void 0) { useScreen = false; }
  12574. if (!useScreen && this._currentRenderTarget) {
  12575. return this._currentRenderTarget.height;
  12576. }
  12577. return this._gl.drawingBufferHeight;
  12578. };
  12579. /**
  12580. * Gets the HTML canvas attached with the current webGL context
  12581. * @returns a HTML canvas
  12582. */
  12583. Engine.prototype.getRenderingCanvas = function () {
  12584. return this._renderingCanvas;
  12585. };
  12586. /**
  12587. * Gets the client rect of the HTML canvas attached with the current webGL context
  12588. * @returns a client rectanglee
  12589. */
  12590. Engine.prototype.getRenderingCanvasClientRect = function () {
  12591. if (!this._renderingCanvas) {
  12592. return null;
  12593. }
  12594. return this._renderingCanvas.getBoundingClientRect();
  12595. };
  12596. /**
  12597. * Defines the hardware scaling level.
  12598. * By default the hardware scaling level is computed from the window device ratio.
  12599. * 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.
  12600. * @param level defines the level to use
  12601. */
  12602. Engine.prototype.setHardwareScalingLevel = function (level) {
  12603. this._hardwareScalingLevel = level;
  12604. this.resize();
  12605. };
  12606. /**
  12607. * Gets the current hardware scaling level.
  12608. * By default the hardware scaling level is computed from the window device ratio.
  12609. * 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.
  12610. * @returns a number indicating the current hardware scaling level
  12611. */
  12612. Engine.prototype.getHardwareScalingLevel = function () {
  12613. return this._hardwareScalingLevel;
  12614. };
  12615. /**
  12616. * Gets the list of loaded textures
  12617. * @returns an array containing all loaded textures
  12618. */
  12619. Engine.prototype.getLoadedTexturesCache = function () {
  12620. return this._internalTexturesCache;
  12621. };
  12622. /**
  12623. * Gets the object containing all engine capabilities
  12624. * @returns the EngineCapabilities object
  12625. */
  12626. Engine.prototype.getCaps = function () {
  12627. return this._caps;
  12628. };
  12629. Object.defineProperty(Engine.prototype, "drawCalls", {
  12630. /** @hidden */
  12631. get: function () {
  12632. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12633. return 0;
  12634. },
  12635. enumerable: true,
  12636. configurable: true
  12637. });
  12638. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12639. /** @hidden */
  12640. get: function () {
  12641. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12642. return null;
  12643. },
  12644. enumerable: true,
  12645. configurable: true
  12646. });
  12647. /**
  12648. * Gets the current depth function
  12649. * @returns a number defining the depth function
  12650. */
  12651. Engine.prototype.getDepthFunction = function () {
  12652. return this._depthCullingState.depthFunc;
  12653. };
  12654. /**
  12655. * Sets the current depth function
  12656. * @param depthFunc defines the function to use
  12657. */
  12658. Engine.prototype.setDepthFunction = function (depthFunc) {
  12659. this._depthCullingState.depthFunc = depthFunc;
  12660. };
  12661. /**
  12662. * Sets the current depth function to GREATER
  12663. */
  12664. Engine.prototype.setDepthFunctionToGreater = function () {
  12665. this._depthCullingState.depthFunc = this._gl.GREATER;
  12666. };
  12667. /**
  12668. * Sets the current depth function to GEQUAL
  12669. */
  12670. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12671. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12672. };
  12673. /**
  12674. * Sets the current depth function to LESS
  12675. */
  12676. Engine.prototype.setDepthFunctionToLess = function () {
  12677. this._depthCullingState.depthFunc = this._gl.LESS;
  12678. };
  12679. /**
  12680. * Sets the current depth function to LEQUAL
  12681. */
  12682. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12683. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12684. };
  12685. /**
  12686. * Gets a boolean indicating if stencil buffer is enabled
  12687. * @returns the current stencil buffer state
  12688. */
  12689. Engine.prototype.getStencilBuffer = function () {
  12690. return this._stencilState.stencilTest;
  12691. };
  12692. /**
  12693. * Enable or disable the stencil buffer
  12694. * @param enable defines if the stencil buffer must be enabled or disabled
  12695. */
  12696. Engine.prototype.setStencilBuffer = function (enable) {
  12697. this._stencilState.stencilTest = enable;
  12698. };
  12699. /**
  12700. * Gets the current stencil mask
  12701. * @returns a number defining the new stencil mask to use
  12702. */
  12703. Engine.prototype.getStencilMask = function () {
  12704. return this._stencilState.stencilMask;
  12705. };
  12706. /**
  12707. * Sets the current stencil mask
  12708. * @param mask defines the new stencil mask to use
  12709. */
  12710. Engine.prototype.setStencilMask = function (mask) {
  12711. this._stencilState.stencilMask = mask;
  12712. };
  12713. /**
  12714. * Gets the current stencil function
  12715. * @returns a number defining the stencil function to use
  12716. */
  12717. Engine.prototype.getStencilFunction = function () {
  12718. return this._stencilState.stencilFunc;
  12719. };
  12720. /**
  12721. * Gets the current stencil reference value
  12722. * @returns a number defining the stencil reference value to use
  12723. */
  12724. Engine.prototype.getStencilFunctionReference = function () {
  12725. return this._stencilState.stencilFuncRef;
  12726. };
  12727. /**
  12728. * Gets the current stencil mask
  12729. * @returns a number defining the stencil mask to use
  12730. */
  12731. Engine.prototype.getStencilFunctionMask = function () {
  12732. return this._stencilState.stencilFuncMask;
  12733. };
  12734. /**
  12735. * Sets the current stencil function
  12736. * @param stencilFunc defines the new stencil function to use
  12737. */
  12738. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12739. this._stencilState.stencilFunc = stencilFunc;
  12740. };
  12741. /**
  12742. * Sets the current stencil reference
  12743. * @param reference defines the new stencil reference to use
  12744. */
  12745. Engine.prototype.setStencilFunctionReference = function (reference) {
  12746. this._stencilState.stencilFuncRef = reference;
  12747. };
  12748. /**
  12749. * Sets the current stencil mask
  12750. * @param mask defines the new stencil mask to use
  12751. */
  12752. Engine.prototype.setStencilFunctionMask = function (mask) {
  12753. this._stencilState.stencilFuncMask = mask;
  12754. };
  12755. /**
  12756. * Gets the current stencil operation when stencil fails
  12757. * @returns a number defining stencil operation to use when stencil fails
  12758. */
  12759. Engine.prototype.getStencilOperationFail = function () {
  12760. return this._stencilState.stencilOpStencilFail;
  12761. };
  12762. /**
  12763. * Gets the current stencil operation when depth fails
  12764. * @returns a number defining stencil operation to use when depth fails
  12765. */
  12766. Engine.prototype.getStencilOperationDepthFail = function () {
  12767. return this._stencilState.stencilOpDepthFail;
  12768. };
  12769. /**
  12770. * Gets the current stencil operation when stencil passes
  12771. * @returns a number defining stencil operation to use when stencil passes
  12772. */
  12773. Engine.prototype.getStencilOperationPass = function () {
  12774. return this._stencilState.stencilOpStencilDepthPass;
  12775. };
  12776. /**
  12777. * Sets the stencil operation to use when stencil fails
  12778. * @param operation defines the stencil operation to use when stencil fails
  12779. */
  12780. Engine.prototype.setStencilOperationFail = function (operation) {
  12781. this._stencilState.stencilOpStencilFail = operation;
  12782. };
  12783. /**
  12784. * Sets the stencil operation to use when depth fails
  12785. * @param operation defines the stencil operation to use when depth fails
  12786. */
  12787. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12788. this._stencilState.stencilOpDepthFail = operation;
  12789. };
  12790. /**
  12791. * Sets the stencil operation to use when stencil passes
  12792. * @param operation defines the stencil operation to use when stencil passes
  12793. */
  12794. Engine.prototype.setStencilOperationPass = function (operation) {
  12795. this._stencilState.stencilOpStencilDepthPass = operation;
  12796. };
  12797. /**
  12798. * Sets a boolean indicating if the dithering state is enabled or disabled
  12799. * @param value defines the dithering state
  12800. */
  12801. Engine.prototype.setDitheringState = function (value) {
  12802. if (value) {
  12803. this._gl.enable(this._gl.DITHER);
  12804. }
  12805. else {
  12806. this._gl.disable(this._gl.DITHER);
  12807. }
  12808. };
  12809. /**
  12810. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12811. * @param value defines the rasterizer state
  12812. */
  12813. Engine.prototype.setRasterizerState = function (value) {
  12814. if (value) {
  12815. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12816. }
  12817. else {
  12818. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12819. }
  12820. };
  12821. /**
  12822. * stop executing a render loop function and remove it from the execution array
  12823. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12824. */
  12825. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12826. if (!renderFunction) {
  12827. this._activeRenderLoops = [];
  12828. return;
  12829. }
  12830. var index = this._activeRenderLoops.indexOf(renderFunction);
  12831. if (index >= 0) {
  12832. this._activeRenderLoops.splice(index, 1);
  12833. }
  12834. };
  12835. /** @hidden */
  12836. Engine.prototype._renderLoop = function () {
  12837. if (!this._contextWasLost) {
  12838. var shouldRender = true;
  12839. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12840. shouldRender = false;
  12841. }
  12842. if (shouldRender) {
  12843. // Start new frame
  12844. this.beginFrame();
  12845. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12846. var renderFunction = this._activeRenderLoops[index];
  12847. renderFunction();
  12848. }
  12849. // Present
  12850. this.endFrame();
  12851. }
  12852. }
  12853. if (this._activeRenderLoops.length > 0) {
  12854. // Register new frame
  12855. var requester = null;
  12856. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12857. requester = this._vrDisplay;
  12858. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12859. }
  12860. else {
  12861. this._renderingQueueLaunched = false;
  12862. }
  12863. };
  12864. /**
  12865. * Register and execute a render loop. The engine can have more than one render function
  12866. * @param renderFunction defines the function to continuously execute
  12867. */
  12868. Engine.prototype.runRenderLoop = function (renderFunction) {
  12869. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12870. return;
  12871. }
  12872. this._activeRenderLoops.push(renderFunction);
  12873. if (!this._renderingQueueLaunched) {
  12874. this._renderingQueueLaunched = true;
  12875. this._bindedRenderFunction = this._renderLoop.bind(this);
  12876. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12877. }
  12878. };
  12879. /**
  12880. * Toggle full screen mode
  12881. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12882. */
  12883. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12884. if (this.isFullscreen) {
  12885. BABYLON.Tools.ExitFullscreen();
  12886. }
  12887. else {
  12888. this._pointerLockRequested = requestPointerLock;
  12889. if (this._renderingCanvas) {
  12890. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12891. }
  12892. }
  12893. };
  12894. /**
  12895. * Clear the current render buffer or the current render target (if any is set up)
  12896. * @param color defines the color to use
  12897. * @param backBuffer defines if the back buffer must be cleared
  12898. * @param depth defines if the depth buffer must be cleared
  12899. * @param stencil defines if the stencil buffer must be cleared
  12900. */
  12901. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12902. if (stencil === void 0) { stencil = false; }
  12903. this.applyStates();
  12904. var mode = 0;
  12905. if (backBuffer && color) {
  12906. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12907. mode |= this._gl.COLOR_BUFFER_BIT;
  12908. }
  12909. if (depth) {
  12910. this._gl.clearDepth(1.0);
  12911. mode |= this._gl.DEPTH_BUFFER_BIT;
  12912. }
  12913. if (stencil) {
  12914. this._gl.clearStencil(0);
  12915. mode |= this._gl.STENCIL_BUFFER_BIT;
  12916. }
  12917. this._gl.clear(mode);
  12918. };
  12919. /**
  12920. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12921. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12922. * @param y defines the y-coordinate of the corner of the clear rectangle
  12923. * @param width defines the width of the clear rectangle
  12924. * @param height defines the height of the clear rectangle
  12925. * @param clearColor defines the clear color
  12926. */
  12927. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12928. var gl = this._gl;
  12929. // Save state
  12930. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12931. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12932. // Change state
  12933. gl.enable(gl.SCISSOR_TEST);
  12934. gl.scissor(x, y, width, height);
  12935. // Clear
  12936. this.clear(clearColor, true, true, true);
  12937. // Restore state
  12938. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12939. if (curScissor === true) {
  12940. gl.enable(gl.SCISSOR_TEST);
  12941. }
  12942. else {
  12943. gl.disable(gl.SCISSOR_TEST);
  12944. }
  12945. };
  12946. /** @hidden */
  12947. Engine.prototype._viewport = function (x, y, width, height) {
  12948. if (x !== this._viewportCached.x ||
  12949. y !== this._viewportCached.y ||
  12950. width !== this._viewportCached.z ||
  12951. height !== this._viewportCached.w) {
  12952. this._viewportCached.x = x;
  12953. this._viewportCached.y = y;
  12954. this._viewportCached.z = width;
  12955. this._viewportCached.w = height;
  12956. this._gl.viewport(x, y, width, height);
  12957. }
  12958. };
  12959. /**
  12960. * Set the WebGL's viewport
  12961. * @param viewport defines the viewport element to be used
  12962. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12963. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12964. */
  12965. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12966. var width = requiredWidth || this.getRenderWidth();
  12967. var height = requiredHeight || this.getRenderHeight();
  12968. var x = viewport.x || 0;
  12969. var y = viewport.y || 0;
  12970. this._cachedViewport = viewport;
  12971. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12972. };
  12973. /**
  12974. * Directly set the WebGL Viewport
  12975. * @param x defines the x coordinate of the viewport (in screen space)
  12976. * @param y defines the y coordinate of the viewport (in screen space)
  12977. * @param width defines the width of the viewport (in screen space)
  12978. * @param height defines the height of the viewport (in screen space)
  12979. * @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
  12980. */
  12981. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12982. var currentViewport = this._cachedViewport;
  12983. this._cachedViewport = null;
  12984. this._viewport(x, y, width, height);
  12985. return currentViewport;
  12986. };
  12987. /**
  12988. * Begin a new frame
  12989. */
  12990. Engine.prototype.beginFrame = function () {
  12991. this.onBeginFrameObservable.notifyObservers(this);
  12992. this._measureFps();
  12993. };
  12994. /**
  12995. * Enf the current frame
  12996. */
  12997. Engine.prototype.endFrame = function () {
  12998. // Force a flush in case we are using a bad OS.
  12999. if (this._badOS) {
  13000. this.flushFramebuffer();
  13001. }
  13002. // Submit frame to the vr device, if enabled
  13003. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13004. // TODO: We should only submit the frame if we read frameData successfully.
  13005. this._vrDisplay.submitFrame();
  13006. }
  13007. this.onEndFrameObservable.notifyObservers(this);
  13008. };
  13009. /**
  13010. * Resize the view according to the canvas' size
  13011. */
  13012. Engine.prototype.resize = function () {
  13013. // We're not resizing the size of the canvas while in VR mode & presenting
  13014. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13015. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13016. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13017. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13018. }
  13019. };
  13020. /**
  13021. * Force a specific size of the canvas
  13022. * @param width defines the new canvas' width
  13023. * @param height defines the new canvas' height
  13024. */
  13025. Engine.prototype.setSize = function (width, height) {
  13026. if (!this._renderingCanvas) {
  13027. return;
  13028. }
  13029. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13030. return;
  13031. }
  13032. this._renderingCanvas.width = width;
  13033. this._renderingCanvas.height = height;
  13034. for (var index = 0; index < this.scenes.length; index++) {
  13035. var scene = this.scenes[index];
  13036. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13037. var cam = scene.cameras[camIndex];
  13038. cam._currentRenderId = 0;
  13039. }
  13040. }
  13041. if (this.onResizeObservable.hasObservers) {
  13042. this.onResizeObservable.notifyObservers(this);
  13043. }
  13044. };
  13045. // WebVR functions
  13046. /**
  13047. * Gets a boolean indicating if a webVR device was detected
  13048. * @returns true if a webVR device was detected
  13049. */
  13050. Engine.prototype.isVRDevicePresent = function () {
  13051. return !!this._vrDisplay;
  13052. };
  13053. /**
  13054. * Gets the current webVR device
  13055. * @returns the current webVR device (or null)
  13056. */
  13057. Engine.prototype.getVRDevice = function () {
  13058. return this._vrDisplay;
  13059. };
  13060. /**
  13061. * Initializes a webVR display and starts listening to display change events
  13062. * The onVRDisplayChangedObservable will be notified upon these changes
  13063. * @returns The onVRDisplayChangedObservable
  13064. */
  13065. Engine.prototype.initWebVR = function () {
  13066. this.initWebVRAsync();
  13067. return this.onVRDisplayChangedObservable;
  13068. };
  13069. /**
  13070. * Initializes a webVR display and starts listening to display change events
  13071. * The onVRDisplayChangedObservable will be notified upon these changes
  13072. * @returns A promise containing a VRDisplay and if vr is supported
  13073. */
  13074. Engine.prototype.initWebVRAsync = function () {
  13075. var _this = this;
  13076. var notifyObservers = function () {
  13077. var eventArgs = {
  13078. vrDisplay: _this._vrDisplay,
  13079. vrSupported: _this._vrSupported
  13080. };
  13081. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13082. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13083. };
  13084. if (!this._onVrDisplayConnect) {
  13085. this._onVrDisplayConnect = function (event) {
  13086. _this._vrDisplay = event.display;
  13087. notifyObservers();
  13088. };
  13089. this._onVrDisplayDisconnect = function () {
  13090. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13091. _this._vrDisplay = undefined;
  13092. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13093. notifyObservers();
  13094. };
  13095. this._onVrDisplayPresentChange = function () {
  13096. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13097. };
  13098. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13099. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13100. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13101. }
  13102. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13103. this._webVRInitPromise.then(notifyObservers);
  13104. return this._webVRInitPromise;
  13105. };
  13106. /**
  13107. * Call this function to switch to webVR mode
  13108. * Will do nothing if webVR is not supported or if there is no webVR device
  13109. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13110. */
  13111. Engine.prototype.enableVR = function () {
  13112. var _this = this;
  13113. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13114. var onResolved = function () {
  13115. _this.onVRRequestPresentComplete.notifyObservers(true);
  13116. _this._onVRFullScreenTriggered();
  13117. };
  13118. var onRejected = function () {
  13119. _this.onVRRequestPresentComplete.notifyObservers(false);
  13120. };
  13121. this.onVRRequestPresentStart.notifyObservers(this);
  13122. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13123. }
  13124. };
  13125. /**
  13126. * Call this function to leave webVR mode
  13127. * Will do nothing if webVR is not supported or if there is no webVR device
  13128. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13129. */
  13130. Engine.prototype.disableVR = function () {
  13131. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13132. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13133. }
  13134. };
  13135. Engine.prototype._getVRDisplaysAsync = function () {
  13136. var _this = this;
  13137. return new Promise(function (res, rej) {
  13138. if (navigator.getVRDisplays) {
  13139. navigator.getVRDisplays().then(function (devices) {
  13140. _this._vrSupported = true;
  13141. // note that devices may actually be an empty array. This is fine;
  13142. // we expect this._vrDisplay to be undefined in this case.
  13143. _this._vrDisplay = devices[0];
  13144. res({
  13145. vrDisplay: _this._vrDisplay,
  13146. vrSupported: _this._vrSupported
  13147. });
  13148. });
  13149. }
  13150. else {
  13151. _this._vrDisplay = undefined;
  13152. _this._vrSupported = false;
  13153. res({
  13154. vrDisplay: _this._vrDisplay,
  13155. vrSupported: _this._vrSupported
  13156. });
  13157. }
  13158. });
  13159. };
  13160. /**
  13161. * Binds the frame buffer to the specified texture.
  13162. * @param texture The texture to render to or null for the default canvas
  13163. * @param faceIndex The face of the texture to render to in case of cube texture
  13164. * @param requiredWidth The width of the target to render to
  13165. * @param requiredHeight The height of the target to render to
  13166. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13167. * @param depthStencilTexture The depth stencil texture to use to render
  13168. * @param lodLevel defines le lod level to bind to the frame buffer
  13169. */
  13170. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13171. if (lodLevel === void 0) { lodLevel = 0; }
  13172. if (this._currentRenderTarget) {
  13173. this.unBindFramebuffer(this._currentRenderTarget);
  13174. }
  13175. this._currentRenderTarget = texture;
  13176. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13177. var gl = this._gl;
  13178. if (texture.isCube) {
  13179. if (faceIndex === undefined) {
  13180. faceIndex = 0;
  13181. }
  13182. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13183. if (depthStencilTexture) {
  13184. if (depthStencilTexture._generateStencilBuffer) {
  13185. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13186. }
  13187. else {
  13188. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13189. }
  13190. }
  13191. }
  13192. if (this._cachedViewport && !forceFullscreenViewport) {
  13193. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13194. }
  13195. else {
  13196. if (!requiredWidth) {
  13197. requiredWidth = texture.width;
  13198. if (lodLevel) {
  13199. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13200. }
  13201. }
  13202. if (!requiredHeight) {
  13203. requiredHeight = texture.height;
  13204. if (lodLevel) {
  13205. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13206. }
  13207. }
  13208. this._viewport(0, 0, requiredWidth, requiredHeight);
  13209. }
  13210. this.wipeCaches();
  13211. };
  13212. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13213. if (this._currentFramebuffer !== framebuffer) {
  13214. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13215. this._currentFramebuffer = framebuffer;
  13216. }
  13217. };
  13218. /**
  13219. * Unbind the current render target texture from the webGL context
  13220. * @param texture defines the render target texture to unbind
  13221. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13222. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13223. */
  13224. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13225. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13226. this._currentRenderTarget = null;
  13227. // If MSAA, we need to bitblt back to main texture
  13228. var gl = this._gl;
  13229. if (texture._MSAAFramebuffer) {
  13230. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13231. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13232. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13233. }
  13234. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13235. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13236. gl.generateMipmap(gl.TEXTURE_2D);
  13237. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13238. }
  13239. if (onBeforeUnbind) {
  13240. if (texture._MSAAFramebuffer) {
  13241. // Bind the correct framebuffer
  13242. this.bindUnboundFramebuffer(texture._framebuffer);
  13243. }
  13244. onBeforeUnbind();
  13245. }
  13246. this.bindUnboundFramebuffer(null);
  13247. };
  13248. /**
  13249. * Unbind a list of render target textures from the webGL context
  13250. * This is used only when drawBuffer extension or webGL2 are active
  13251. * @param textures defines the render target textures to unbind
  13252. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13253. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13254. */
  13255. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13256. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13257. this._currentRenderTarget = null;
  13258. // If MSAA, we need to bitblt back to main texture
  13259. var gl = this._gl;
  13260. if (textures[0]._MSAAFramebuffer) {
  13261. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13262. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13263. var attachments = textures[0]._attachments;
  13264. if (!attachments) {
  13265. attachments = new Array(textures.length);
  13266. textures[0]._attachments = attachments;
  13267. }
  13268. for (var i = 0; i < textures.length; i++) {
  13269. var texture = textures[i];
  13270. for (var j = 0; j < attachments.length; j++) {
  13271. attachments[j] = gl.NONE;
  13272. }
  13273. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13274. gl.readBuffer(attachments[i]);
  13275. gl.drawBuffers(attachments);
  13276. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13277. }
  13278. for (var i = 0; i < attachments.length; i++) {
  13279. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13280. }
  13281. gl.drawBuffers(attachments);
  13282. }
  13283. for (var i = 0; i < textures.length; i++) {
  13284. var texture = textures[i];
  13285. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13286. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13287. gl.generateMipmap(gl.TEXTURE_2D);
  13288. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13289. }
  13290. }
  13291. if (onBeforeUnbind) {
  13292. if (textures[0]._MSAAFramebuffer) {
  13293. // Bind the correct framebuffer
  13294. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13295. }
  13296. onBeforeUnbind();
  13297. }
  13298. this.bindUnboundFramebuffer(null);
  13299. };
  13300. /**
  13301. * Force the mipmap generation for the given render target texture
  13302. * @param texture defines the render target texture to use
  13303. */
  13304. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13305. if (texture.generateMipMaps) {
  13306. var gl = this._gl;
  13307. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13308. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13309. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13310. }
  13311. };
  13312. /**
  13313. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13314. */
  13315. Engine.prototype.flushFramebuffer = function () {
  13316. this._gl.flush();
  13317. };
  13318. /**
  13319. * Unbind the current render target and bind the default framebuffer
  13320. */
  13321. Engine.prototype.restoreDefaultFramebuffer = function () {
  13322. if (this._currentRenderTarget) {
  13323. this.unBindFramebuffer(this._currentRenderTarget);
  13324. }
  13325. else {
  13326. this.bindUnboundFramebuffer(null);
  13327. }
  13328. if (this._cachedViewport) {
  13329. this.setViewport(this._cachedViewport);
  13330. }
  13331. this.wipeCaches();
  13332. };
  13333. // UBOs
  13334. /**
  13335. * Create an uniform buffer
  13336. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13337. * @param elements defines the content of the uniform buffer
  13338. * @returns the webGL uniform buffer
  13339. */
  13340. Engine.prototype.createUniformBuffer = function (elements) {
  13341. var ubo = this._gl.createBuffer();
  13342. if (!ubo) {
  13343. throw new Error("Unable to create uniform buffer");
  13344. }
  13345. this.bindUniformBuffer(ubo);
  13346. if (elements instanceof Float32Array) {
  13347. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13348. }
  13349. else {
  13350. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13351. }
  13352. this.bindUniformBuffer(null);
  13353. ubo.references = 1;
  13354. return ubo;
  13355. };
  13356. /**
  13357. * Create a dynamic uniform buffer
  13358. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13359. * @param elements defines the content of the uniform buffer
  13360. * @returns the webGL uniform buffer
  13361. */
  13362. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13363. var ubo = this._gl.createBuffer();
  13364. if (!ubo) {
  13365. throw new Error("Unable to create dynamic uniform buffer");
  13366. }
  13367. this.bindUniformBuffer(ubo);
  13368. if (elements instanceof Float32Array) {
  13369. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13370. }
  13371. else {
  13372. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13373. }
  13374. this.bindUniformBuffer(null);
  13375. ubo.references = 1;
  13376. return ubo;
  13377. };
  13378. /**
  13379. * Update an existing uniform buffer
  13380. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13381. * @param uniformBuffer defines the target uniform buffer
  13382. * @param elements defines the content to update
  13383. * @param offset defines the offset in the uniform buffer where update should start
  13384. * @param count defines the size of the data to update
  13385. */
  13386. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13387. this.bindUniformBuffer(uniformBuffer);
  13388. if (offset === undefined) {
  13389. offset = 0;
  13390. }
  13391. if (count === undefined) {
  13392. if (elements instanceof Float32Array) {
  13393. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13394. }
  13395. else {
  13396. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13397. }
  13398. }
  13399. else {
  13400. if (elements instanceof Float32Array) {
  13401. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13402. }
  13403. else {
  13404. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13405. }
  13406. }
  13407. this.bindUniformBuffer(null);
  13408. };
  13409. // VBOs
  13410. Engine.prototype._resetVertexBufferBinding = function () {
  13411. this.bindArrayBuffer(null);
  13412. this._cachedVertexBuffers = null;
  13413. };
  13414. /**
  13415. * Creates a vertex buffer
  13416. * @param data the data for the vertex buffer
  13417. * @returns the new WebGL static buffer
  13418. */
  13419. Engine.prototype.createVertexBuffer = function (data) {
  13420. var vbo = this._gl.createBuffer();
  13421. if (!vbo) {
  13422. throw new Error("Unable to create vertex buffer");
  13423. }
  13424. this.bindArrayBuffer(vbo);
  13425. if (data instanceof Array) {
  13426. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13427. }
  13428. else {
  13429. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13430. }
  13431. this._resetVertexBufferBinding();
  13432. vbo.references = 1;
  13433. return vbo;
  13434. };
  13435. /**
  13436. * Creates a dynamic vertex buffer
  13437. * @param data the data for the dynamic vertex buffer
  13438. * @returns the new WebGL dynamic buffer
  13439. */
  13440. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13441. var vbo = this._gl.createBuffer();
  13442. if (!vbo) {
  13443. throw new Error("Unable to create dynamic vertex buffer");
  13444. }
  13445. this.bindArrayBuffer(vbo);
  13446. if (data instanceof Array) {
  13447. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13448. }
  13449. else {
  13450. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13451. }
  13452. this._resetVertexBufferBinding();
  13453. vbo.references = 1;
  13454. return vbo;
  13455. };
  13456. /**
  13457. * Update a dynamic index buffer
  13458. * @param indexBuffer defines the target index buffer
  13459. * @param indices defines the data to update
  13460. * @param offset defines the offset in the target index buffer where update should start
  13461. */
  13462. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13463. if (offset === void 0) { offset = 0; }
  13464. // Force cache update
  13465. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13466. this.bindIndexBuffer(indexBuffer);
  13467. var arrayBuffer;
  13468. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13469. arrayBuffer = indices;
  13470. }
  13471. else {
  13472. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13473. }
  13474. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13475. this._resetIndexBufferBinding();
  13476. };
  13477. /**
  13478. * Updates a dynamic vertex buffer.
  13479. * @param vertexBuffer the vertex buffer to update
  13480. * @param data the data used to update the vertex buffer
  13481. * @param byteOffset the byte offset of the data
  13482. * @param byteLength the byte length of the data
  13483. */
  13484. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13485. this.bindArrayBuffer(vertexBuffer);
  13486. if (byteOffset === undefined) {
  13487. byteOffset = 0;
  13488. }
  13489. if (byteLength === undefined) {
  13490. if (data instanceof Array) {
  13491. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13492. }
  13493. else {
  13494. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13495. }
  13496. }
  13497. else {
  13498. if (data instanceof Array) {
  13499. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13500. }
  13501. else {
  13502. if (data instanceof ArrayBuffer) {
  13503. data = new Uint8Array(data, byteOffset, byteLength);
  13504. }
  13505. else {
  13506. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13507. }
  13508. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13509. }
  13510. }
  13511. this._resetVertexBufferBinding();
  13512. };
  13513. Engine.prototype._resetIndexBufferBinding = function () {
  13514. this.bindIndexBuffer(null);
  13515. this._cachedIndexBuffer = null;
  13516. };
  13517. /**
  13518. * Creates a new index buffer
  13519. * @param indices defines the content of the index buffer
  13520. * @param updatable defines if the index buffer must be updatable
  13521. * @returns a new webGL buffer
  13522. */
  13523. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13524. var vbo = this._gl.createBuffer();
  13525. if (!vbo) {
  13526. throw new Error("Unable to create index buffer");
  13527. }
  13528. this.bindIndexBuffer(vbo);
  13529. // Check for 32 bits indices
  13530. var arrayBuffer;
  13531. var need32Bits = false;
  13532. if (indices instanceof Uint16Array) {
  13533. arrayBuffer = indices;
  13534. }
  13535. else {
  13536. //check 32 bit support
  13537. if (this._caps.uintIndices) {
  13538. if (indices instanceof Uint32Array) {
  13539. arrayBuffer = indices;
  13540. need32Bits = true;
  13541. }
  13542. else {
  13543. //number[] or Int32Array, check if 32 bit is necessary
  13544. for (var index = 0; index < indices.length; index++) {
  13545. if (indices[index] > 65535) {
  13546. need32Bits = true;
  13547. break;
  13548. }
  13549. }
  13550. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13551. }
  13552. }
  13553. else {
  13554. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13555. arrayBuffer = new Uint16Array(indices);
  13556. }
  13557. }
  13558. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13559. this._resetIndexBufferBinding();
  13560. vbo.references = 1;
  13561. vbo.is32Bits = need32Bits;
  13562. return vbo;
  13563. };
  13564. /**
  13565. * Bind a webGL buffer to the webGL context
  13566. * @param buffer defines the buffer to bind
  13567. */
  13568. Engine.prototype.bindArrayBuffer = function (buffer) {
  13569. if (!this._vaoRecordInProgress) {
  13570. this._unbindVertexArrayObject();
  13571. }
  13572. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13573. };
  13574. /**
  13575. * Bind an uniform buffer to the current webGL context
  13576. * @param buffer defines the buffer to bind
  13577. */
  13578. Engine.prototype.bindUniformBuffer = function (buffer) {
  13579. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13580. };
  13581. /**
  13582. * Bind a buffer to the current webGL context at a given location
  13583. * @param buffer defines the buffer to bind
  13584. * @param location defines the index where to bind the buffer
  13585. */
  13586. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13587. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13588. };
  13589. /**
  13590. * Bind a specific block at a given index in a specific shader program
  13591. * @param shaderProgram defines the shader program
  13592. * @param blockName defines the block name
  13593. * @param index defines the index where to bind the block
  13594. */
  13595. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13596. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13597. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13598. };
  13599. ;
  13600. Engine.prototype.bindIndexBuffer = function (buffer) {
  13601. if (!this._vaoRecordInProgress) {
  13602. this._unbindVertexArrayObject();
  13603. }
  13604. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13605. };
  13606. Engine.prototype.bindBuffer = function (buffer, target) {
  13607. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13608. this._gl.bindBuffer(target, buffer);
  13609. this._currentBoundBuffer[target] = buffer;
  13610. }
  13611. };
  13612. /**
  13613. * update the bound buffer with the given data
  13614. * @param data defines the data to update
  13615. */
  13616. Engine.prototype.updateArrayBuffer = function (data) {
  13617. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13618. };
  13619. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13620. var pointer = this._currentBufferPointers[indx];
  13621. var changed = false;
  13622. if (!pointer.active) {
  13623. changed = true;
  13624. pointer.active = true;
  13625. pointer.index = indx;
  13626. pointer.size = size;
  13627. pointer.type = type;
  13628. pointer.normalized = normalized;
  13629. pointer.stride = stride;
  13630. pointer.offset = offset;
  13631. pointer.buffer = buffer;
  13632. }
  13633. else {
  13634. if (pointer.buffer !== buffer) {
  13635. pointer.buffer = buffer;
  13636. changed = true;
  13637. }
  13638. if (pointer.size !== size) {
  13639. pointer.size = size;
  13640. changed = true;
  13641. }
  13642. if (pointer.type !== type) {
  13643. pointer.type = type;
  13644. changed = true;
  13645. }
  13646. if (pointer.normalized !== normalized) {
  13647. pointer.normalized = normalized;
  13648. changed = true;
  13649. }
  13650. if (pointer.stride !== stride) {
  13651. pointer.stride = stride;
  13652. changed = true;
  13653. }
  13654. if (pointer.offset !== offset) {
  13655. pointer.offset = offset;
  13656. changed = true;
  13657. }
  13658. }
  13659. if (changed || this._vaoRecordInProgress) {
  13660. this.bindArrayBuffer(buffer);
  13661. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13662. }
  13663. };
  13664. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13665. if (indexBuffer == null) {
  13666. return;
  13667. }
  13668. if (this._cachedIndexBuffer !== indexBuffer) {
  13669. this._cachedIndexBuffer = indexBuffer;
  13670. this.bindIndexBuffer(indexBuffer);
  13671. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13672. }
  13673. };
  13674. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13675. var attributes = effect.getAttributesNames();
  13676. if (!this._vaoRecordInProgress) {
  13677. this._unbindVertexArrayObject();
  13678. }
  13679. this.unbindAllAttributes();
  13680. for (var index = 0; index < attributes.length; index++) {
  13681. var order = effect.getAttributeLocation(index);
  13682. if (order >= 0) {
  13683. var vertexBuffer = vertexBuffers[attributes[index]];
  13684. if (!vertexBuffer) {
  13685. continue;
  13686. }
  13687. this._gl.enableVertexAttribArray(order);
  13688. if (!this._vaoRecordInProgress) {
  13689. this._vertexAttribArraysEnabled[order] = true;
  13690. }
  13691. var buffer = vertexBuffer.getBuffer();
  13692. if (buffer) {
  13693. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13694. if (vertexBuffer.getIsInstanced()) {
  13695. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13696. if (!this._vaoRecordInProgress) {
  13697. this._currentInstanceLocations.push(order);
  13698. this._currentInstanceBuffers.push(buffer);
  13699. }
  13700. }
  13701. }
  13702. }
  13703. }
  13704. };
  13705. /**
  13706. * Records a vertex array object
  13707. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13708. * @param vertexBuffers defines the list of vertex buffers to store
  13709. * @param indexBuffer defines the index buffer to store
  13710. * @param effect defines the effect to store
  13711. * @returns the new vertex array object
  13712. */
  13713. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13714. var vao = this._gl.createVertexArray();
  13715. this._vaoRecordInProgress = true;
  13716. this._gl.bindVertexArray(vao);
  13717. this._mustWipeVertexAttributes = true;
  13718. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13719. this.bindIndexBuffer(indexBuffer);
  13720. this._vaoRecordInProgress = false;
  13721. this._gl.bindVertexArray(null);
  13722. return vao;
  13723. };
  13724. /**
  13725. * Bind a specific vertex array object
  13726. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13727. * @param vertexArrayObject defines the vertex array object to bind
  13728. * @param indexBuffer defines the index buffer to bind
  13729. */
  13730. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13731. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13732. this._cachedVertexArrayObject = vertexArrayObject;
  13733. this._gl.bindVertexArray(vertexArrayObject);
  13734. this._cachedVertexBuffers = null;
  13735. this._cachedIndexBuffer = null;
  13736. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13737. this._mustWipeVertexAttributes = true;
  13738. }
  13739. };
  13740. /**
  13741. * Bind webGl buffers directly to the webGL context
  13742. * @param vertexBuffer defines the vertex buffer to bind
  13743. * @param indexBuffer defines the index buffer to bind
  13744. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13745. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13746. * @param effect defines the effect associated with the vertex buffer
  13747. */
  13748. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13749. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13750. this._cachedVertexBuffers = vertexBuffer;
  13751. this._cachedEffectForVertexBuffers = effect;
  13752. var attributesCount = effect.getAttributesCount();
  13753. this._unbindVertexArrayObject();
  13754. this.unbindAllAttributes();
  13755. var offset = 0;
  13756. for (var index = 0; index < attributesCount; index++) {
  13757. if (index < vertexDeclaration.length) {
  13758. var order = effect.getAttributeLocation(index);
  13759. if (order >= 0) {
  13760. this._gl.enableVertexAttribArray(order);
  13761. this._vertexAttribArraysEnabled[order] = true;
  13762. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13763. }
  13764. offset += vertexDeclaration[index] * 4;
  13765. }
  13766. }
  13767. }
  13768. this._bindIndexBufferWithCache(indexBuffer);
  13769. };
  13770. Engine.prototype._unbindVertexArrayObject = function () {
  13771. if (!this._cachedVertexArrayObject) {
  13772. return;
  13773. }
  13774. this._cachedVertexArrayObject = null;
  13775. this._gl.bindVertexArray(null);
  13776. };
  13777. /**
  13778. * Bind a list of vertex buffers to the webGL context
  13779. * @param vertexBuffers defines the list of vertex buffers to bind
  13780. * @param indexBuffer defines the index buffer to bind
  13781. * @param effect defines the effect associated with the vertex buffers
  13782. */
  13783. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13784. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13785. this._cachedVertexBuffers = vertexBuffers;
  13786. this._cachedEffectForVertexBuffers = effect;
  13787. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13788. }
  13789. this._bindIndexBufferWithCache(indexBuffer);
  13790. };
  13791. /**
  13792. * Unbind all instance attributes
  13793. */
  13794. Engine.prototype.unbindInstanceAttributes = function () {
  13795. var boundBuffer;
  13796. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13797. var instancesBuffer = this._currentInstanceBuffers[i];
  13798. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13799. boundBuffer = instancesBuffer;
  13800. this.bindArrayBuffer(instancesBuffer);
  13801. }
  13802. var offsetLocation = this._currentInstanceLocations[i];
  13803. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13804. }
  13805. this._currentInstanceBuffers.length = 0;
  13806. this._currentInstanceLocations.length = 0;
  13807. };
  13808. /**
  13809. * Release and free the memory of a vertex array object
  13810. * @param vao defines the vertex array object to delete
  13811. */
  13812. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13813. this._gl.deleteVertexArray(vao);
  13814. };
  13815. /** @hidden */
  13816. Engine.prototype._releaseBuffer = function (buffer) {
  13817. buffer.references--;
  13818. if (buffer.references === 0) {
  13819. this._gl.deleteBuffer(buffer);
  13820. return true;
  13821. }
  13822. return false;
  13823. };
  13824. /**
  13825. * Creates a webGL buffer to use with instanciation
  13826. * @param capacity defines the size of the buffer
  13827. * @returns the webGL buffer
  13828. */
  13829. Engine.prototype.createInstancesBuffer = function (capacity) {
  13830. var buffer = this._gl.createBuffer();
  13831. if (!buffer) {
  13832. throw new Error("Unable to create instance buffer");
  13833. }
  13834. buffer.capacity = capacity;
  13835. this.bindArrayBuffer(buffer);
  13836. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13837. return buffer;
  13838. };
  13839. /**
  13840. * Delete a webGL buffer used with instanciation
  13841. * @param buffer defines the webGL buffer to delete
  13842. */
  13843. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13844. this._gl.deleteBuffer(buffer);
  13845. };
  13846. /**
  13847. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13848. * @param instancesBuffer defines the webGL buffer to update and bind
  13849. * @param data defines the data to store in the buffer
  13850. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13851. */
  13852. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13853. this.bindArrayBuffer(instancesBuffer);
  13854. if (data) {
  13855. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13856. }
  13857. if (offsetLocations[0].index !== undefined) {
  13858. var stride = 0;
  13859. for (var i = 0; i < offsetLocations.length; i++) {
  13860. var ai = offsetLocations[i];
  13861. stride += ai.attributeSize * 4;
  13862. }
  13863. for (var i = 0; i < offsetLocations.length; i++) {
  13864. var ai = offsetLocations[i];
  13865. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13866. this._gl.enableVertexAttribArray(ai.index);
  13867. this._vertexAttribArraysEnabled[ai.index] = true;
  13868. }
  13869. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13870. this._gl.vertexAttribDivisor(ai.index, 1);
  13871. this._currentInstanceLocations.push(ai.index);
  13872. this._currentInstanceBuffers.push(instancesBuffer);
  13873. }
  13874. }
  13875. else {
  13876. for (var index = 0; index < 4; index++) {
  13877. var offsetLocation = offsetLocations[index];
  13878. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13879. this._gl.enableVertexAttribArray(offsetLocation);
  13880. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13881. }
  13882. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13883. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13884. this._currentInstanceLocations.push(offsetLocation);
  13885. this._currentInstanceBuffers.push(instancesBuffer);
  13886. }
  13887. }
  13888. };
  13889. /**
  13890. * Apply all cached states (depth, culling, stencil and alpha)
  13891. */
  13892. Engine.prototype.applyStates = function () {
  13893. this._depthCullingState.apply(this._gl);
  13894. this._stencilState.apply(this._gl);
  13895. this._alphaState.apply(this._gl);
  13896. };
  13897. /**
  13898. * Send a draw order
  13899. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13900. * @param indexStart defines the starting index
  13901. * @param indexCount defines the number of index to draw
  13902. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13903. */
  13904. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13905. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13906. };
  13907. /**
  13908. * Draw a list of points
  13909. * @param verticesStart defines the index of first vertex to draw
  13910. * @param verticesCount defines the count of vertices to draw
  13911. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13912. */
  13913. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13914. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13915. };
  13916. /**
  13917. * Draw a list of unindexed primitives
  13918. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13919. * @param verticesStart defines the index of first vertex to draw
  13920. * @param verticesCount defines the count of vertices to draw
  13921. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13922. */
  13923. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13924. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13925. };
  13926. /**
  13927. * Draw a list of indexed primitives
  13928. * @param fillMode defines the primitive to use
  13929. * @param indexStart defines the starting index
  13930. * @param indexCount defines the number of index to draw
  13931. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13932. */
  13933. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13934. // Apply states
  13935. this.applyStates();
  13936. this._drawCalls.addCount(1, false);
  13937. // Render
  13938. var drawMode = this._drawMode(fillMode);
  13939. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13940. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13941. if (instancesCount) {
  13942. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13943. }
  13944. else {
  13945. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13946. }
  13947. };
  13948. /**
  13949. * Draw a list of unindexed primitives
  13950. * @param fillMode defines the primitive to use
  13951. * @param verticesStart defines the index of first vertex to draw
  13952. * @param verticesCount defines the count of vertices to draw
  13953. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13954. */
  13955. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13956. // Apply states
  13957. this.applyStates();
  13958. this._drawCalls.addCount(1, false);
  13959. var drawMode = this._drawMode(fillMode);
  13960. if (instancesCount) {
  13961. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13962. }
  13963. else {
  13964. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13965. }
  13966. };
  13967. Engine.prototype._drawMode = function (fillMode) {
  13968. switch (fillMode) {
  13969. // Triangle views
  13970. case BABYLON.Material.TriangleFillMode:
  13971. return this._gl.TRIANGLES;
  13972. case BABYLON.Material.PointFillMode:
  13973. return this._gl.POINTS;
  13974. case BABYLON.Material.WireFrameFillMode:
  13975. return this._gl.LINES;
  13976. // Draw modes
  13977. case BABYLON.Material.PointListDrawMode:
  13978. return this._gl.POINTS;
  13979. case BABYLON.Material.LineListDrawMode:
  13980. return this._gl.LINES;
  13981. case BABYLON.Material.LineLoopDrawMode:
  13982. return this._gl.LINE_LOOP;
  13983. case BABYLON.Material.LineStripDrawMode:
  13984. return this._gl.LINE_STRIP;
  13985. case BABYLON.Material.TriangleStripDrawMode:
  13986. return this._gl.TRIANGLE_STRIP;
  13987. case BABYLON.Material.TriangleFanDrawMode:
  13988. return this._gl.TRIANGLE_FAN;
  13989. default:
  13990. return this._gl.TRIANGLES;
  13991. }
  13992. };
  13993. // Shaders
  13994. /** @hidden */
  13995. Engine.prototype._releaseEffect = function (effect) {
  13996. if (this._compiledEffects[effect._key]) {
  13997. delete this._compiledEffects[effect._key];
  13998. this._deleteProgram(effect.getProgram());
  13999. }
  14000. };
  14001. /** @hidden */
  14002. Engine.prototype._deleteProgram = function (program) {
  14003. if (program) {
  14004. program.__SPECTOR_rebuildProgram = null;
  14005. if (program.transformFeedback) {
  14006. this.deleteTransformFeedback(program.transformFeedback);
  14007. program.transformFeedback = null;
  14008. }
  14009. this._gl.deleteProgram(program);
  14010. }
  14011. };
  14012. /**
  14013. * Create a new effect (used to store vertex/fragment shaders)
  14014. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14015. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14016. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14017. * @param samplers defines an array of string used to represent textures
  14018. * @param defines defines the string containing the defines to use to compile the shaders
  14019. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14020. * @param onCompiled defines a function to call when the effect creation is successful
  14021. * @param onError defines a function to call when the effect creation has failed
  14022. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14023. * @returns the new Effect
  14024. */
  14025. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14026. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14027. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14028. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14029. if (this._compiledEffects[name]) {
  14030. var compiledEffect = this._compiledEffects[name];
  14031. if (onCompiled && compiledEffect.isReady()) {
  14032. onCompiled(compiledEffect);
  14033. }
  14034. return compiledEffect;
  14035. }
  14036. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14037. effect._key = name;
  14038. this._compiledEffects[name] = effect;
  14039. return effect;
  14040. };
  14041. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14042. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14043. };
  14044. ;
  14045. Engine.prototype._compileRawShader = function (source, type) {
  14046. var gl = this._gl;
  14047. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14048. gl.shaderSource(shader, source);
  14049. gl.compileShader(shader);
  14050. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14051. var log = gl.getShaderInfoLog(shader);
  14052. if (log) {
  14053. throw new Error(log);
  14054. }
  14055. }
  14056. if (!shader) {
  14057. throw new Error("Something went wrong while compile the shader.");
  14058. }
  14059. return shader;
  14060. };
  14061. ;
  14062. /**
  14063. * Directly creates a webGL program
  14064. * @param vertexCode defines the vertex shader code to use
  14065. * @param fragmentCode defines the fragment shader code to use
  14066. * @param context defines the webGL context to use (if not set, the current one will be used)
  14067. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14068. * @returns the new webGL program
  14069. */
  14070. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14071. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14072. context = context || this._gl;
  14073. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14074. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14075. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14076. };
  14077. /**
  14078. * Creates a webGL program
  14079. * @param vertexCode defines the vertex shader code to use
  14080. * @param fragmentCode defines the fragment shader code to use
  14081. * @param defines defines the string containing the defines to use to compile the shaders
  14082. * @param context defines the webGL context to use (if not set, the current one will be used)
  14083. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14084. * @returns the new webGL program
  14085. */
  14086. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14087. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14088. context = context || this._gl;
  14089. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14090. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14091. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14092. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14093. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14094. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14095. return program;
  14096. };
  14097. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14098. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14099. var shaderProgram = context.createProgram();
  14100. if (!shaderProgram) {
  14101. throw new Error("Unable to create program");
  14102. }
  14103. context.attachShader(shaderProgram, vertexShader);
  14104. context.attachShader(shaderProgram, fragmentShader);
  14105. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14106. var transformFeedback = this.createTransformFeedback();
  14107. this.bindTransformFeedback(transformFeedback);
  14108. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14109. shaderProgram.transformFeedback = transformFeedback;
  14110. }
  14111. context.linkProgram(shaderProgram);
  14112. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14113. this.bindTransformFeedback(null);
  14114. }
  14115. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14116. if (!linked) {
  14117. var error = context.getProgramInfoLog(shaderProgram);
  14118. if (error) {
  14119. throw new Error(error);
  14120. }
  14121. }
  14122. if (this.validateShaderPrograms) {
  14123. context.validateProgram(shaderProgram);
  14124. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14125. if (!validated) {
  14126. var error = context.getProgramInfoLog(shaderProgram);
  14127. if (error) {
  14128. throw new Error(error);
  14129. }
  14130. }
  14131. }
  14132. context.deleteShader(vertexShader);
  14133. context.deleteShader(fragmentShader);
  14134. return shaderProgram;
  14135. };
  14136. /**
  14137. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14138. * @param shaderProgram defines the webGL program to use
  14139. * @param uniformsNames defines the list of uniform names
  14140. * @returns an array of webGL uniform locations
  14141. */
  14142. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14143. var results = new Array();
  14144. for (var index = 0; index < uniformsNames.length; index++) {
  14145. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14146. }
  14147. return results;
  14148. };
  14149. /**
  14150. * Gets the lsit of active attributes for a given webGL program
  14151. * @param shaderProgram defines the webGL program to use
  14152. * @param attributesNames defines the list of attribute names to get
  14153. * @returns an array of indices indicating the offset of each attribute
  14154. */
  14155. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14156. var results = [];
  14157. for (var index = 0; index < attributesNames.length; index++) {
  14158. try {
  14159. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14160. }
  14161. catch (e) {
  14162. results.push(-1);
  14163. }
  14164. }
  14165. return results;
  14166. };
  14167. /**
  14168. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14169. * @param effect defines the effect to activate
  14170. */
  14171. Engine.prototype.enableEffect = function (effect) {
  14172. if (!effect || effect === this._currentEffect) {
  14173. return;
  14174. }
  14175. // Use program
  14176. this.bindSamplers(effect);
  14177. this._currentEffect = effect;
  14178. if (effect.onBind) {
  14179. effect.onBind(effect);
  14180. }
  14181. if (effect._onBindObservable) {
  14182. effect._onBindObservable.notifyObservers(effect);
  14183. }
  14184. };
  14185. /**
  14186. * Set the value of an uniform to an array of int32
  14187. * @param uniform defines the webGL uniform location where to store the value
  14188. * @param array defines the array of int32 to store
  14189. */
  14190. Engine.prototype.setIntArray = function (uniform, array) {
  14191. if (!uniform)
  14192. return;
  14193. this._gl.uniform1iv(uniform, array);
  14194. };
  14195. /**
  14196. * Set the value of an uniform to an array of int32 (stored as vec2)
  14197. * @param uniform defines the webGL uniform location where to store the value
  14198. * @param array defines the array of int32 to store
  14199. */
  14200. Engine.prototype.setIntArray2 = function (uniform, array) {
  14201. if (!uniform || array.length % 2 !== 0)
  14202. return;
  14203. this._gl.uniform2iv(uniform, array);
  14204. };
  14205. /**
  14206. * Set the value of an uniform to an array of int32 (stored as vec3)
  14207. * @param uniform defines the webGL uniform location where to store the value
  14208. * @param array defines the array of int32 to store
  14209. */
  14210. Engine.prototype.setIntArray3 = function (uniform, array) {
  14211. if (!uniform || array.length % 3 !== 0)
  14212. return;
  14213. this._gl.uniform3iv(uniform, array);
  14214. };
  14215. /**
  14216. * Set the value of an uniform to an array of int32 (stored as vec4)
  14217. * @param uniform defines the webGL uniform location where to store the value
  14218. * @param array defines the array of int32 to store
  14219. */
  14220. Engine.prototype.setIntArray4 = function (uniform, array) {
  14221. if (!uniform || array.length % 4 !== 0)
  14222. return;
  14223. this._gl.uniform4iv(uniform, array);
  14224. };
  14225. /**
  14226. * Set the value of an uniform to an array of float32
  14227. * @param uniform defines the webGL uniform location where to store the value
  14228. * @param array defines the array of float32 to store
  14229. */
  14230. Engine.prototype.setFloatArray = function (uniform, array) {
  14231. if (!uniform)
  14232. return;
  14233. this._gl.uniform1fv(uniform, array);
  14234. };
  14235. /**
  14236. * Set the value of an uniform to an array of float32 (stored as vec2)
  14237. * @param uniform defines the webGL uniform location where to store the value
  14238. * @param array defines the array of float32 to store
  14239. */
  14240. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14241. if (!uniform || array.length % 2 !== 0)
  14242. return;
  14243. this._gl.uniform2fv(uniform, array);
  14244. };
  14245. /**
  14246. * Set the value of an uniform to an array of float32 (stored as vec3)
  14247. * @param uniform defines the webGL uniform location where to store the value
  14248. * @param array defines the array of float32 to store
  14249. */
  14250. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14251. if (!uniform || array.length % 3 !== 0)
  14252. return;
  14253. this._gl.uniform3fv(uniform, array);
  14254. };
  14255. /**
  14256. * Set the value of an uniform to an array of float32 (stored as vec4)
  14257. * @param uniform defines the webGL uniform location where to store the value
  14258. * @param array defines the array of float32 to store
  14259. */
  14260. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14261. if (!uniform || array.length % 4 !== 0)
  14262. return;
  14263. this._gl.uniform4fv(uniform, array);
  14264. };
  14265. /**
  14266. * Set the value of an uniform to an array of number
  14267. * @param uniform defines the webGL uniform location where to store the value
  14268. * @param array defines the array of number to store
  14269. */
  14270. Engine.prototype.setArray = function (uniform, array) {
  14271. if (!uniform)
  14272. return;
  14273. this._gl.uniform1fv(uniform, array);
  14274. };
  14275. /**
  14276. * Set the value of an uniform to an array of number (stored as vec2)
  14277. * @param uniform defines the webGL uniform location where to store the value
  14278. * @param array defines the array of number to store
  14279. */
  14280. Engine.prototype.setArray2 = function (uniform, array) {
  14281. if (!uniform || array.length % 2 !== 0)
  14282. return;
  14283. this._gl.uniform2fv(uniform, array);
  14284. };
  14285. /**
  14286. * Set the value of an uniform to an array of number (stored as vec3)
  14287. * @param uniform defines the webGL uniform location where to store the value
  14288. * @param array defines the array of number to store
  14289. */
  14290. Engine.prototype.setArray3 = function (uniform, array) {
  14291. if (!uniform || array.length % 3 !== 0)
  14292. return;
  14293. this._gl.uniform3fv(uniform, array);
  14294. };
  14295. /**
  14296. * Set the value of an uniform to an array of number (stored as vec4)
  14297. * @param uniform defines the webGL uniform location where to store the value
  14298. * @param array defines the array of number to store
  14299. */
  14300. Engine.prototype.setArray4 = function (uniform, array) {
  14301. if (!uniform || array.length % 4 !== 0)
  14302. return;
  14303. this._gl.uniform4fv(uniform, array);
  14304. };
  14305. /**
  14306. * Set the value of an uniform to an array of float32 (stored as matrices)
  14307. * @param uniform defines the webGL uniform location where to store the value
  14308. * @param matrices defines the array of float32 to store
  14309. */
  14310. Engine.prototype.setMatrices = function (uniform, matrices) {
  14311. if (!uniform)
  14312. return;
  14313. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14314. };
  14315. /**
  14316. * Set the value of an uniform to a matrix
  14317. * @param uniform defines the webGL uniform location where to store the value
  14318. * @param matrix defines the matrix to store
  14319. */
  14320. Engine.prototype.setMatrix = function (uniform, matrix) {
  14321. if (!uniform)
  14322. return;
  14323. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14324. };
  14325. /**
  14326. * Set the value of an uniform to a matrix (3x3)
  14327. * @param uniform defines the webGL uniform location where to store the value
  14328. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14329. */
  14330. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14331. if (!uniform)
  14332. return;
  14333. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14334. };
  14335. /**
  14336. * Set the value of an uniform to a matrix (2x2)
  14337. * @param uniform defines the webGL uniform location where to store the value
  14338. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14339. */
  14340. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14341. if (!uniform)
  14342. return;
  14343. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14344. };
  14345. /**
  14346. * Set the value of an uniform to a number (int)
  14347. * @param uniform defines the webGL uniform location where to store the value
  14348. * @param value defines the int number to store
  14349. */
  14350. Engine.prototype.setInt = function (uniform, value) {
  14351. if (!uniform)
  14352. return;
  14353. this._gl.uniform1i(uniform, value);
  14354. };
  14355. /**
  14356. * Set the value of an uniform to a number (float)
  14357. * @param uniform defines the webGL uniform location where to store the value
  14358. * @param value defines the float number to store
  14359. */
  14360. Engine.prototype.setFloat = function (uniform, value) {
  14361. if (!uniform)
  14362. return;
  14363. this._gl.uniform1f(uniform, value);
  14364. };
  14365. /**
  14366. * Set the value of an uniform to a vec2
  14367. * @param uniform defines the webGL uniform location where to store the value
  14368. * @param x defines the 1st component of the value
  14369. * @param y defines the 2nd component of the value
  14370. */
  14371. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14372. if (!uniform)
  14373. return;
  14374. this._gl.uniform2f(uniform, x, y);
  14375. };
  14376. /**
  14377. * Set the value of an uniform to a vec3
  14378. * @param uniform defines the webGL uniform location where to store the value
  14379. * @param x defines the 1st component of the value
  14380. * @param y defines the 2nd component of the value
  14381. * @param z defines the 3rd component of the value
  14382. */
  14383. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14384. if (!uniform)
  14385. return;
  14386. this._gl.uniform3f(uniform, x, y, z);
  14387. };
  14388. /**
  14389. * Set the value of an uniform to a boolean
  14390. * @param uniform defines the webGL uniform location where to store the value
  14391. * @param bool defines the boolean to store
  14392. */
  14393. Engine.prototype.setBool = function (uniform, bool) {
  14394. if (!uniform)
  14395. return;
  14396. this._gl.uniform1i(uniform, bool);
  14397. };
  14398. /**
  14399. * Set the value of an uniform to a vec4
  14400. * @param uniform defines the webGL uniform location where to store the value
  14401. * @param x defines the 1st component of the value
  14402. * @param y defines the 2nd component of the value
  14403. * @param z defines the 3rd component of the value
  14404. * @param w defines the 4th component of the value
  14405. */
  14406. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14407. if (!uniform)
  14408. return;
  14409. this._gl.uniform4f(uniform, x, y, z, w);
  14410. };
  14411. /**
  14412. * Set the value of an uniform to a Color3
  14413. * @param uniform defines the webGL uniform location where to store the value
  14414. * @param color3 defines the color to store
  14415. */
  14416. Engine.prototype.setColor3 = function (uniform, color3) {
  14417. if (!uniform)
  14418. return;
  14419. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14420. };
  14421. /**
  14422. * Set the value of an uniform to a Color3 and an alpha value
  14423. * @param uniform defines the webGL uniform location where to store the value
  14424. * @param color3 defines the color to store
  14425. * @param alpha defines the alpha component to store
  14426. */
  14427. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14428. if (!uniform)
  14429. return;
  14430. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14431. };
  14432. /**
  14433. * Sets a Color4 on a uniform variable
  14434. * @param uniform defines the uniform location
  14435. * @param color4 defines the value to be set
  14436. */
  14437. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14438. if (!uniform)
  14439. return;
  14440. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14441. };
  14442. // States
  14443. /**
  14444. * Set various states to the webGL context
  14445. * @param culling defines backface culling state
  14446. * @param zOffset defines the value to apply to zOffset (0 by default)
  14447. * @param force defines if states must be applied even if cache is up to date
  14448. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14449. */
  14450. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14451. if (zOffset === void 0) { zOffset = 0; }
  14452. if (reverseSide === void 0) { reverseSide = false; }
  14453. // Culling
  14454. if (this._depthCullingState.cull !== culling || force) {
  14455. this._depthCullingState.cull = culling;
  14456. }
  14457. // Cull face
  14458. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14459. if (this._depthCullingState.cullFace !== cullFace || force) {
  14460. this._depthCullingState.cullFace = cullFace;
  14461. }
  14462. // Z offset
  14463. this.setZOffset(zOffset);
  14464. // Front face
  14465. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14466. if (this._depthCullingState.frontFace !== frontFace || force) {
  14467. this._depthCullingState.frontFace = frontFace;
  14468. }
  14469. };
  14470. /**
  14471. * Set the z offset to apply to current rendering
  14472. * @param value defines the offset to apply
  14473. */
  14474. Engine.prototype.setZOffset = function (value) {
  14475. this._depthCullingState.zOffset = value;
  14476. };
  14477. /**
  14478. * Gets the current value of the zOffset
  14479. * @returns the current zOffset state
  14480. */
  14481. Engine.prototype.getZOffset = function () {
  14482. return this._depthCullingState.zOffset;
  14483. };
  14484. /**
  14485. * Enable or disable depth buffering
  14486. * @param enable defines the state to set
  14487. */
  14488. Engine.prototype.setDepthBuffer = function (enable) {
  14489. this._depthCullingState.depthTest = enable;
  14490. };
  14491. /**
  14492. * Gets a boolean indicating if depth writing is enabled
  14493. * @returns the current depth writing state
  14494. */
  14495. Engine.prototype.getDepthWrite = function () {
  14496. return this._depthCullingState.depthMask;
  14497. };
  14498. /**
  14499. * Enable or disable depth writing
  14500. * @param enable defines the state to set
  14501. */
  14502. Engine.prototype.setDepthWrite = function (enable) {
  14503. this._depthCullingState.depthMask = enable;
  14504. };
  14505. /**
  14506. * Enable or disable color writing
  14507. * @param enable defines the state to set
  14508. */
  14509. Engine.prototype.setColorWrite = function (enable) {
  14510. this._gl.colorMask(enable, enable, enable, enable);
  14511. this._colorWrite = enable;
  14512. };
  14513. /**
  14514. * Gets a boolean indicating if color writing is enabled
  14515. * @returns the current color writing state
  14516. */
  14517. Engine.prototype.getColorWrite = function () {
  14518. return this._colorWrite;
  14519. };
  14520. /**
  14521. * Sets alpha constants used by some alpha blending modes
  14522. * @param r defines the red component
  14523. * @param g defines the green component
  14524. * @param b defines the blue component
  14525. * @param a defines the alpha component
  14526. */
  14527. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14528. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14529. };
  14530. /**
  14531. * Sets the current alpha mode
  14532. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14533. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14534. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14535. */
  14536. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14537. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14538. if (this._alphaMode === mode) {
  14539. return;
  14540. }
  14541. switch (mode) {
  14542. case Engine.ALPHA_DISABLE:
  14543. this._alphaState.alphaBlend = false;
  14544. break;
  14545. case Engine.ALPHA_PREMULTIPLIED:
  14546. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14547. this._alphaState.alphaBlend = true;
  14548. break;
  14549. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14550. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14551. this._alphaState.alphaBlend = true;
  14552. break;
  14553. case Engine.ALPHA_COMBINE:
  14554. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14555. this._alphaState.alphaBlend = true;
  14556. break;
  14557. case Engine.ALPHA_ONEONE:
  14558. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14559. this._alphaState.alphaBlend = true;
  14560. break;
  14561. case Engine.ALPHA_ADD:
  14562. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14563. this._alphaState.alphaBlend = true;
  14564. break;
  14565. case Engine.ALPHA_SUBTRACT:
  14566. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14567. this._alphaState.alphaBlend = true;
  14568. break;
  14569. case Engine.ALPHA_MULTIPLY:
  14570. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14571. this._alphaState.alphaBlend = true;
  14572. break;
  14573. case Engine.ALPHA_MAXIMIZED:
  14574. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14575. this._alphaState.alphaBlend = true;
  14576. break;
  14577. case Engine.ALPHA_INTERPOLATE:
  14578. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14579. this._alphaState.alphaBlend = true;
  14580. break;
  14581. case Engine.ALPHA_SCREENMODE:
  14582. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14583. this._alphaState.alphaBlend = true;
  14584. break;
  14585. }
  14586. if (!noDepthWriteChange) {
  14587. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14588. }
  14589. this._alphaMode = mode;
  14590. };
  14591. /**
  14592. * Gets the current alpha mode
  14593. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14594. * @returns the current alpha mode
  14595. */
  14596. Engine.prototype.getAlphaMode = function () {
  14597. return this._alphaMode;
  14598. };
  14599. // Textures
  14600. /**
  14601. * Clears the list of texture accessible through engine.
  14602. * This can help preventing texture load conflict due to name collision.
  14603. */
  14604. Engine.prototype.clearInternalTexturesCache = function () {
  14605. this._internalTexturesCache = [];
  14606. };
  14607. /**
  14608. * Force the entire cache to be cleared
  14609. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14610. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14611. */
  14612. Engine.prototype.wipeCaches = function (bruteForce) {
  14613. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14614. return;
  14615. }
  14616. this._currentEffect = null;
  14617. this._viewportCached.x = 0;
  14618. this._viewportCached.y = 0;
  14619. this._viewportCached.z = 0;
  14620. this._viewportCached.w = 0;
  14621. if (bruteForce) {
  14622. this.resetTextureCache();
  14623. this._currentProgram = null;
  14624. this._stencilState.reset();
  14625. this._depthCullingState.reset();
  14626. this.setDepthFunctionToLessOrEqual();
  14627. this._alphaState.reset();
  14628. this._unpackFlipYCached = null;
  14629. }
  14630. this._resetVertexBufferBinding();
  14631. this._cachedIndexBuffer = null;
  14632. this._cachedEffectForVertexBuffers = null;
  14633. this._unbindVertexArrayObject();
  14634. this.bindIndexBuffer(null);
  14635. };
  14636. /**
  14637. * Set the compressed texture format to use, based on the formats you have, and the formats
  14638. * supported by the hardware / browser.
  14639. *
  14640. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14641. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14642. * to API arguments needed to compressed textures. This puts the burden on the container
  14643. * generator to house the arcane code for determining these for current & future formats.
  14644. *
  14645. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14646. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14647. *
  14648. * Note: The result of this call is not taken into account when a texture is base64.
  14649. *
  14650. * @param formatsAvailable defines the list of those format families you have created
  14651. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14652. *
  14653. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14654. * @returns The extension selected.
  14655. */
  14656. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14657. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14658. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14659. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14660. return this._textureFormatInUse = this._texturesSupported[i];
  14661. }
  14662. }
  14663. }
  14664. // actively set format to nothing, to allow this to be called more than once
  14665. // and possibly fail the 2nd time
  14666. this._textureFormatInUse = null;
  14667. return null;
  14668. };
  14669. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14670. var gl = this._gl;
  14671. var magFilter = gl.NEAREST;
  14672. var minFilter = gl.NEAREST;
  14673. switch (samplingMode) {
  14674. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14675. magFilter = gl.LINEAR;
  14676. if (generateMipMaps) {
  14677. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14678. }
  14679. else {
  14680. minFilter = gl.LINEAR;
  14681. }
  14682. break;
  14683. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14684. magFilter = gl.LINEAR;
  14685. if (generateMipMaps) {
  14686. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14687. }
  14688. else {
  14689. minFilter = gl.LINEAR;
  14690. }
  14691. break;
  14692. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14693. magFilter = gl.NEAREST;
  14694. if (generateMipMaps) {
  14695. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14696. }
  14697. else {
  14698. minFilter = gl.NEAREST;
  14699. }
  14700. break;
  14701. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14702. magFilter = gl.NEAREST;
  14703. if (generateMipMaps) {
  14704. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14705. }
  14706. else {
  14707. minFilter = gl.NEAREST;
  14708. }
  14709. break;
  14710. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14711. magFilter = gl.NEAREST;
  14712. if (generateMipMaps) {
  14713. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14714. }
  14715. else {
  14716. minFilter = gl.LINEAR;
  14717. }
  14718. break;
  14719. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14720. magFilter = gl.NEAREST;
  14721. if (generateMipMaps) {
  14722. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14723. }
  14724. else {
  14725. minFilter = gl.LINEAR;
  14726. }
  14727. break;
  14728. case Engine.TEXTURE_NEAREST_LINEAR:
  14729. magFilter = gl.NEAREST;
  14730. minFilter = gl.LINEAR;
  14731. break;
  14732. case Engine.TEXTURE_NEAREST_NEAREST:
  14733. magFilter = gl.NEAREST;
  14734. minFilter = gl.NEAREST;
  14735. break;
  14736. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14737. magFilter = gl.LINEAR;
  14738. if (generateMipMaps) {
  14739. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14740. }
  14741. else {
  14742. minFilter = gl.NEAREST;
  14743. }
  14744. break;
  14745. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14746. magFilter = gl.LINEAR;
  14747. if (generateMipMaps) {
  14748. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14749. }
  14750. else {
  14751. minFilter = gl.NEAREST;
  14752. }
  14753. break;
  14754. case Engine.TEXTURE_LINEAR_LINEAR:
  14755. magFilter = gl.LINEAR;
  14756. minFilter = gl.LINEAR;
  14757. break;
  14758. case Engine.TEXTURE_LINEAR_NEAREST:
  14759. magFilter = gl.LINEAR;
  14760. minFilter = gl.NEAREST;
  14761. break;
  14762. }
  14763. return {
  14764. min: minFilter,
  14765. mag: magFilter
  14766. };
  14767. };
  14768. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14769. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14770. var img;
  14771. var onload = function () {
  14772. loadedImages[index] = img;
  14773. loadedImages._internalCount++;
  14774. if (scene) {
  14775. scene._removePendingData(img);
  14776. }
  14777. if (loadedImages._internalCount === 6) {
  14778. onfinish(loadedImages);
  14779. }
  14780. };
  14781. var onerror = function (message, exception) {
  14782. if (scene) {
  14783. scene._removePendingData(img);
  14784. }
  14785. if (onErrorCallBack) {
  14786. onErrorCallBack(message, exception);
  14787. }
  14788. };
  14789. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14790. if (scene) {
  14791. scene._addPendingData(img);
  14792. }
  14793. };
  14794. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14795. if (onError === void 0) { onError = null; }
  14796. var loadedImages = [];
  14797. loadedImages._internalCount = 0;
  14798. for (var index = 0; index < 6; index++) {
  14799. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14800. }
  14801. };
  14802. ;
  14803. /** @hidden */
  14804. Engine.prototype._createTexture = function () {
  14805. var texture = this._gl.createTexture();
  14806. if (!texture) {
  14807. throw new Error("Unable to create texture");
  14808. }
  14809. return texture;
  14810. };
  14811. /**
  14812. * Usually called from BABYLON.Texture.ts.
  14813. * Passed information to create a WebGLTexture
  14814. * @param urlArg defines a value which contains one of the following:
  14815. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14816. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14817. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14818. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14819. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14820. * @param scene needed for loading to the correct scene
  14821. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14822. * @param onLoad optional callback to be called upon successful completion
  14823. * @param onError optional callback to be called upon failure
  14824. * @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
  14825. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14826. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14827. * @param forcedExtension defines the extension to use to pick the right loader
  14828. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14829. */
  14830. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14831. var _this = this;
  14832. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14833. if (onLoad === void 0) { onLoad = null; }
  14834. if (onError === void 0) { onError = null; }
  14835. if (buffer === void 0) { buffer = null; }
  14836. if (fallback === void 0) { fallback = null; }
  14837. if (format === void 0) { format = null; }
  14838. if (forcedExtension === void 0) { forcedExtension = null; }
  14839. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14840. var fromData = url.substr(0, 5) === "data:";
  14841. var fromBlob = url.substr(0, 5) === "blob:";
  14842. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  14843. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14844. // establish the file extension, if possible
  14845. var lastDot = url.lastIndexOf('.');
  14846. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14847. var loader = null;
  14848. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14849. var availableLoader = _a[_i];
  14850. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14851. loader = availableLoader;
  14852. break;
  14853. }
  14854. }
  14855. if (loader) {
  14856. url = loader.transformUrl(url, this._textureFormatInUse);
  14857. }
  14858. if (scene) {
  14859. scene._addPendingData(texture);
  14860. }
  14861. texture.url = url;
  14862. texture.generateMipMaps = !noMipmap;
  14863. texture.samplingMode = samplingMode;
  14864. texture.invertY = invertY;
  14865. if (!this._doNotHandleContextLost) {
  14866. // Keep a link to the buffer only if we plan to handle context lost
  14867. texture._buffer = buffer;
  14868. }
  14869. var onLoadObserver = null;
  14870. if (onLoad && !fallback) {
  14871. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14872. }
  14873. if (!fallback)
  14874. this._internalTexturesCache.push(texture);
  14875. var onInternalError = function (message, exception) {
  14876. if (scene) {
  14877. scene._removePendingData(texture);
  14878. }
  14879. var customFallback = false;
  14880. if (loader) {
  14881. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14882. if (fallbackUrl) {
  14883. // Add Back
  14884. customFallback = true;
  14885. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14886. }
  14887. }
  14888. if (!customFallback) {
  14889. if (onLoadObserver) {
  14890. texture.onLoadedObservable.remove(onLoadObserver);
  14891. }
  14892. if (BABYLON.Tools.UseFallbackTexture) {
  14893. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14894. }
  14895. }
  14896. if (onError) {
  14897. onError(message || "Unknown error", exception);
  14898. }
  14899. };
  14900. // processing for non-image formats
  14901. if (loader) {
  14902. var callback = function (data) {
  14903. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14904. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14905. done();
  14906. return false;
  14907. }, samplingMode);
  14908. });
  14909. };
  14910. if (!buffer) {
  14911. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14912. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14913. });
  14914. }
  14915. else {
  14916. callback(buffer);
  14917. }
  14918. }
  14919. else {
  14920. var onload = function (img) {
  14921. if (fromBlob && !_this._doNotHandleContextLost) {
  14922. // We need to store the image if we need to rebuild the texture
  14923. // in case of a webgl context lost
  14924. texture._buffer = img;
  14925. }
  14926. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14927. var gl = _this._gl;
  14928. var isPot = (img.width === potWidth && img.height === potHeight);
  14929. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14930. if (isPot) {
  14931. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14932. return false;
  14933. }
  14934. var maxTextureSize = _this._caps.maxTextureSize;
  14935. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14936. _this._prepareWorkingCanvas();
  14937. if (!_this._workingCanvas || !_this._workingContext) {
  14938. return false;
  14939. }
  14940. _this._workingCanvas.width = potWidth;
  14941. _this._workingCanvas.height = potHeight;
  14942. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14943. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14944. texture.width = potWidth;
  14945. texture.height = potHeight;
  14946. return false;
  14947. }
  14948. else {
  14949. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14950. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14951. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14952. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14953. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14954. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14955. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14956. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14957. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14958. _this._releaseTexture(source_1);
  14959. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14960. continuationCallback();
  14961. });
  14962. }
  14963. return true;
  14964. }, samplingMode);
  14965. };
  14966. if (!fromData || isBase64) {
  14967. if (buffer instanceof HTMLImageElement) {
  14968. onload(buffer);
  14969. }
  14970. else {
  14971. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14972. }
  14973. }
  14974. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14975. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14976. }
  14977. else {
  14978. onload(buffer);
  14979. }
  14980. }
  14981. return texture;
  14982. };
  14983. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14984. var _this = this;
  14985. var rtt = this.createRenderTargetTexture({
  14986. width: destination.width,
  14987. height: destination.height,
  14988. }, {
  14989. generateMipMaps: false,
  14990. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14991. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14992. generateDepthBuffer: false,
  14993. generateStencilBuffer: false
  14994. });
  14995. if (!this._rescalePostProcess) {
  14996. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14997. }
  14998. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14999. _this._rescalePostProcess.onApply = function (effect) {
  15000. effect._bindTexture("textureSampler", source);
  15001. };
  15002. var hostingScene = scene;
  15003. if (!hostingScene) {
  15004. hostingScene = _this.scenes[_this.scenes.length - 1];
  15005. }
  15006. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15007. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15008. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15009. _this.unBindFramebuffer(rtt);
  15010. _this._releaseTexture(rtt);
  15011. if (onComplete) {
  15012. onComplete();
  15013. }
  15014. });
  15015. };
  15016. /**
  15017. * Update a raw texture
  15018. * @param texture defines the texture to update
  15019. * @param data defines the data to store in the texture
  15020. * @param format defines the format of the data
  15021. * @param invertY defines if data must be stored with Y axis inverted
  15022. * @param compression defines the compression used (null by default)
  15023. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15024. */
  15025. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15026. if (compression === void 0) { compression = null; }
  15027. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15028. if (!texture) {
  15029. return;
  15030. }
  15031. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15032. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15033. // babylon's internalFormat but gl's texImage2D format
  15034. var internalFormat = this._getInternalFormat(format);
  15035. var textureType = this._getWebGLTextureType(type);
  15036. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15037. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15038. if (!this._doNotHandleContextLost) {
  15039. texture._bufferView = data;
  15040. texture.format = format;
  15041. texture.type = type;
  15042. texture.invertY = invertY;
  15043. texture._compression = compression;
  15044. }
  15045. if (texture.width % 4 !== 0) {
  15046. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15047. }
  15048. if (compression && data) {
  15049. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15050. }
  15051. else {
  15052. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15053. }
  15054. if (texture.generateMipMaps) {
  15055. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15056. }
  15057. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15058. // this.resetTextureCache();
  15059. texture.isReady = true;
  15060. };
  15061. /**
  15062. * Creates a raw texture
  15063. * @param data defines the data to store in the texture
  15064. * @param width defines the width of the texture
  15065. * @param height defines the height of the texture
  15066. * @param format defines the format of the data
  15067. * @param generateMipMaps defines if the engine should generate the mip levels
  15068. * @param invertY defines if data must be stored with Y axis inverted
  15069. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15070. * @param compression defines the compression used (null by default)
  15071. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15072. * @returns the raw texture inside an InternalTexture
  15073. */
  15074. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15075. if (compression === void 0) { compression = null; }
  15076. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15077. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15078. texture.baseWidth = width;
  15079. texture.baseHeight = height;
  15080. texture.width = width;
  15081. texture.height = height;
  15082. texture.format = format;
  15083. texture.generateMipMaps = generateMipMaps;
  15084. texture.samplingMode = samplingMode;
  15085. texture.invertY = invertY;
  15086. texture._compression = compression;
  15087. texture.type = type;
  15088. if (!this._doNotHandleContextLost) {
  15089. texture._bufferView = data;
  15090. }
  15091. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15092. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15093. // Filters
  15094. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15095. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15096. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15097. if (generateMipMaps) {
  15098. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15099. }
  15100. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15101. this._internalTexturesCache.push(texture);
  15102. return texture;
  15103. };
  15104. /** @hidden */
  15105. Engine.prototype._unpackFlipY = function (value) {
  15106. if (this._unpackFlipYCached !== value) {
  15107. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15108. if (this.enableUnpackFlipYCached) {
  15109. this._unpackFlipYCached = value;
  15110. }
  15111. }
  15112. };
  15113. /** @hidden */
  15114. Engine.prototype._getUnpackAlignement = function () {
  15115. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15116. };
  15117. /**
  15118. * Creates a dynamic texture
  15119. * @param width defines the width of the texture
  15120. * @param height defines the height of the texture
  15121. * @param generateMipMaps defines if the engine should generate the mip levels
  15122. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15123. * @returns the dynamic texture inside an InternalTexture
  15124. */
  15125. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15126. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15127. texture.baseWidth = width;
  15128. texture.baseHeight = height;
  15129. if (generateMipMaps) {
  15130. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15131. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15132. }
  15133. // this.resetTextureCache();
  15134. texture.width = width;
  15135. texture.height = height;
  15136. texture.isReady = false;
  15137. texture.generateMipMaps = generateMipMaps;
  15138. texture.samplingMode = samplingMode;
  15139. this.updateTextureSamplingMode(samplingMode, texture);
  15140. this._internalTexturesCache.push(texture);
  15141. return texture;
  15142. };
  15143. /**
  15144. * Update the sampling mode of a given texture
  15145. * @param samplingMode defines the required sampling mode
  15146. * @param texture defines the texture to update
  15147. */
  15148. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15149. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15150. if (texture.isCube) {
  15151. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15152. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15153. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15154. }
  15155. else if (texture.is3D) {
  15156. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15157. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15158. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15159. }
  15160. else {
  15161. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15162. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15163. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15164. }
  15165. texture.samplingMode = samplingMode;
  15166. };
  15167. /**
  15168. * Update the content of a dynamic texture
  15169. * @param texture defines the texture to update
  15170. * @param canvas defines the canvas containing the source
  15171. * @param invertY defines if data must be stored with Y axis inverted
  15172. * @param premulAlpha defines if alpha is stored as premultiplied
  15173. * @param format defines the format of the data
  15174. */
  15175. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15176. if (premulAlpha === void 0) { premulAlpha = false; }
  15177. if (!texture) {
  15178. return;
  15179. }
  15180. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15181. this._unpackFlipY(invertY);
  15182. if (premulAlpha) {
  15183. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15184. }
  15185. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15186. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15187. if (texture.generateMipMaps) {
  15188. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15189. }
  15190. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15191. if (premulAlpha) {
  15192. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15193. }
  15194. texture.isReady = true;
  15195. };
  15196. /**
  15197. * Update a video texture
  15198. * @param texture defines the texture to update
  15199. * @param video defines the video element to use
  15200. * @param invertY defines if data must be stored with Y axis inverted
  15201. */
  15202. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15203. if (!texture || texture._isDisabled) {
  15204. return;
  15205. }
  15206. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15207. this._unpackFlipY(!invertY); // Video are upside down by default
  15208. try {
  15209. // Testing video texture support
  15210. if (this._videoTextureSupported === undefined) {
  15211. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15212. if (this._gl.getError() !== 0) {
  15213. this._videoTextureSupported = false;
  15214. }
  15215. else {
  15216. this._videoTextureSupported = true;
  15217. }
  15218. }
  15219. // Copy video through the current working canvas if video texture is not supported
  15220. if (!this._videoTextureSupported) {
  15221. if (!texture._workingCanvas) {
  15222. texture._workingCanvas = document.createElement("canvas");
  15223. var context = texture._workingCanvas.getContext("2d");
  15224. if (!context) {
  15225. throw new Error("Unable to get 2d context");
  15226. }
  15227. texture._workingContext = context;
  15228. texture._workingCanvas.width = texture.width;
  15229. texture._workingCanvas.height = texture.height;
  15230. }
  15231. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15232. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15233. }
  15234. else {
  15235. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15236. }
  15237. if (texture.generateMipMaps) {
  15238. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15239. }
  15240. if (!wasPreviouslyBound) {
  15241. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15242. }
  15243. // this.resetTextureCache();
  15244. texture.isReady = true;
  15245. }
  15246. catch (ex) {
  15247. // Something unexpected
  15248. // Let's disable the texture
  15249. texture._isDisabled = true;
  15250. }
  15251. };
  15252. /**
  15253. * Updates a depth texture Comparison Mode and Function.
  15254. * If the comparison Function is equal to 0, the mode will be set to none.
  15255. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15256. * @param texture The texture to set the comparison function for
  15257. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15258. */
  15259. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15260. if (this.webGLVersion === 1) {
  15261. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15262. return;
  15263. }
  15264. var gl = this._gl;
  15265. if (texture.isCube) {
  15266. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15267. if (comparisonFunction === 0) {
  15268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15269. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15270. }
  15271. else {
  15272. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15273. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15274. }
  15275. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15276. }
  15277. else {
  15278. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15279. if (comparisonFunction === 0) {
  15280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15282. }
  15283. else {
  15284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15286. }
  15287. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15288. }
  15289. texture._comparisonFunction = comparisonFunction;
  15290. };
  15291. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15292. var width = size.width || size;
  15293. var height = size.height || size;
  15294. internalTexture.baseWidth = width;
  15295. internalTexture.baseHeight = height;
  15296. internalTexture.width = width;
  15297. internalTexture.height = height;
  15298. internalTexture.isReady = true;
  15299. internalTexture.samples = 1;
  15300. internalTexture.generateMipMaps = false;
  15301. internalTexture._generateDepthBuffer = true;
  15302. internalTexture._generateStencilBuffer = generateStencil;
  15303. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15304. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15305. internalTexture._comparisonFunction = comparisonFunction;
  15306. var gl = this._gl;
  15307. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15308. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15309. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15310. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15311. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15312. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15313. if (comparisonFunction === 0) {
  15314. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15315. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15316. }
  15317. else {
  15318. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15319. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15320. }
  15321. };
  15322. /**
  15323. * Creates a depth stencil texture.
  15324. * This is only available in WebGL 2 or with the depth texture extension available.
  15325. * @param size The size of face edge in the texture.
  15326. * @param options The options defining the texture.
  15327. * @returns The texture
  15328. */
  15329. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15330. if (options.isCube) {
  15331. var width = size.width || size;
  15332. return this._createDepthStencilCubeTexture(width, options);
  15333. }
  15334. else {
  15335. return this._createDepthStencilTexture(size, options);
  15336. }
  15337. };
  15338. /**
  15339. * Creates a depth stencil texture.
  15340. * This is only available in WebGL 2 or with the depth texture extension available.
  15341. * @param size The size of face edge in the texture.
  15342. * @param options The options defining the texture.
  15343. * @returns The texture
  15344. */
  15345. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15346. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15347. if (!this._caps.depthTextureExtension) {
  15348. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15349. return internalTexture;
  15350. }
  15351. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15352. var gl = this._gl;
  15353. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15354. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15355. if (this.webGLVersion > 1) {
  15356. if (internalOptions.generateStencil) {
  15357. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15358. }
  15359. else {
  15360. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15361. }
  15362. }
  15363. else {
  15364. if (internalOptions.generateStencil) {
  15365. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15366. }
  15367. else {
  15368. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15369. }
  15370. }
  15371. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15372. return internalTexture;
  15373. };
  15374. /**
  15375. * Creates a depth stencil cube texture.
  15376. * This is only available in WebGL 2.
  15377. * @param size The size of face edge in the cube texture.
  15378. * @param options The options defining the cube texture.
  15379. * @returns The cube texture
  15380. */
  15381. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15382. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15383. internalTexture.isCube = true;
  15384. if (this.webGLVersion === 1) {
  15385. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15386. return internalTexture;
  15387. }
  15388. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15389. var gl = this._gl;
  15390. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15391. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15392. // Create the depth/stencil buffer
  15393. for (var face = 0; face < 6; face++) {
  15394. if (internalOptions.generateStencil) {
  15395. 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);
  15396. }
  15397. else {
  15398. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15399. }
  15400. }
  15401. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15402. return internalTexture;
  15403. };
  15404. /**
  15405. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15406. * @param renderTarget The render target to set the frame buffer for
  15407. */
  15408. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15409. // Create the framebuffer
  15410. var internalTexture = renderTarget.getInternalTexture();
  15411. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15412. return;
  15413. }
  15414. var gl = this._gl;
  15415. var depthStencilTexture = renderTarget.depthStencilTexture;
  15416. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15417. if (depthStencilTexture.isCube) {
  15418. if (depthStencilTexture._generateStencilBuffer) {
  15419. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15420. }
  15421. else {
  15422. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15423. }
  15424. }
  15425. else {
  15426. if (depthStencilTexture._generateStencilBuffer) {
  15427. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15428. }
  15429. else {
  15430. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15431. }
  15432. }
  15433. this.bindUnboundFramebuffer(null);
  15434. };
  15435. /**
  15436. * Creates a new render target texture
  15437. * @param size defines the size of the texture
  15438. * @param options defines the options used to create the texture
  15439. * @returns a new render target texture stored in an InternalTexture
  15440. */
  15441. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15442. var fullOptions = new RenderTargetCreationOptions();
  15443. if (options !== undefined && typeof options === "object") {
  15444. fullOptions.generateMipMaps = options.generateMipMaps;
  15445. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15446. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15447. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15448. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15449. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15450. }
  15451. else {
  15452. fullOptions.generateMipMaps = options;
  15453. fullOptions.generateDepthBuffer = true;
  15454. fullOptions.generateStencilBuffer = false;
  15455. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15456. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15457. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15458. }
  15459. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15460. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15461. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15462. }
  15463. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15464. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15465. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15466. }
  15467. var gl = this._gl;
  15468. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15469. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15470. var width = size.width || size;
  15471. var height = size.height || size;
  15472. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15473. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15474. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15475. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15476. }
  15477. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15478. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15479. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15480. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15481. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15482. // Create the framebuffer
  15483. var currentFrameBuffer = this._currentFramebuffer;
  15484. var framebuffer = gl.createFramebuffer();
  15485. this.bindUnboundFramebuffer(framebuffer);
  15486. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15487. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15488. if (fullOptions.generateMipMaps) {
  15489. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15490. }
  15491. // Unbind
  15492. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15493. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15494. this.bindUnboundFramebuffer(currentFrameBuffer);
  15495. texture._framebuffer = framebuffer;
  15496. texture.baseWidth = width;
  15497. texture.baseHeight = height;
  15498. texture.width = width;
  15499. texture.height = height;
  15500. texture.isReady = true;
  15501. texture.samples = 1;
  15502. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15503. texture.samplingMode = fullOptions.samplingMode;
  15504. texture.type = fullOptions.type;
  15505. texture.format = fullOptions.format;
  15506. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15507. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15508. // this.resetTextureCache();
  15509. this._internalTexturesCache.push(texture);
  15510. return texture;
  15511. };
  15512. /**
  15513. * Create a multi render target texture
  15514. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15515. * @param size defines the size of the texture
  15516. * @param options defines the creation options
  15517. * @returns the cube texture as an InternalTexture
  15518. */
  15519. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15520. var generateMipMaps = false;
  15521. var generateDepthBuffer = true;
  15522. var generateStencilBuffer = false;
  15523. var generateDepthTexture = false;
  15524. var textureCount = 1;
  15525. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15526. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15527. var types = new Array();
  15528. var samplingModes = new Array();
  15529. if (options !== undefined) {
  15530. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15531. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15532. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15533. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15534. textureCount = options.textureCount || 1;
  15535. if (options.types) {
  15536. types = options.types;
  15537. }
  15538. if (options.samplingModes) {
  15539. samplingModes = options.samplingModes;
  15540. }
  15541. }
  15542. var gl = this._gl;
  15543. // Create the framebuffer
  15544. var framebuffer = gl.createFramebuffer();
  15545. this.bindUnboundFramebuffer(framebuffer);
  15546. var width = size.width || size;
  15547. var height = size.height || size;
  15548. var textures = [];
  15549. var attachments = [];
  15550. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15551. for (var i = 0; i < textureCount; i++) {
  15552. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15553. var type = types[i] || defaultType;
  15554. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15555. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15556. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15557. }
  15558. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15559. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15560. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15561. }
  15562. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15563. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15564. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15565. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15566. }
  15567. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15568. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15569. textures.push(texture);
  15570. attachments.push(attachment);
  15571. gl.activeTexture(gl["TEXTURE" + i]);
  15572. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15573. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15576. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15577. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15578. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15579. if (generateMipMaps) {
  15580. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15581. }
  15582. // Unbind
  15583. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15584. texture._framebuffer = framebuffer;
  15585. texture._depthStencilBuffer = depthStencilBuffer;
  15586. texture.baseWidth = width;
  15587. texture.baseHeight = height;
  15588. texture.width = width;
  15589. texture.height = height;
  15590. texture.isReady = true;
  15591. texture.samples = 1;
  15592. texture.generateMipMaps = generateMipMaps;
  15593. texture.samplingMode = samplingMode;
  15594. texture.type = type;
  15595. texture._generateDepthBuffer = generateDepthBuffer;
  15596. texture._generateStencilBuffer = generateStencilBuffer;
  15597. texture._attachments = attachments;
  15598. this._internalTexturesCache.push(texture);
  15599. }
  15600. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15601. // Depth texture
  15602. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15603. gl.activeTexture(gl.TEXTURE0);
  15604. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15605. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15606. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15607. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15608. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15609. 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);
  15610. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15611. depthTexture._framebuffer = framebuffer;
  15612. depthTexture.baseWidth = width;
  15613. depthTexture.baseHeight = height;
  15614. depthTexture.width = width;
  15615. depthTexture.height = height;
  15616. depthTexture.isReady = true;
  15617. depthTexture.samples = 1;
  15618. depthTexture.generateMipMaps = generateMipMaps;
  15619. depthTexture.samplingMode = gl.NEAREST;
  15620. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15621. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15622. textures.push(depthTexture);
  15623. this._internalTexturesCache.push(depthTexture);
  15624. }
  15625. gl.drawBuffers(attachments);
  15626. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15627. this.bindUnboundFramebuffer(null);
  15628. this.resetTextureCache();
  15629. return textures;
  15630. };
  15631. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15632. if (samples === void 0) { samples = 1; }
  15633. var depthStencilBuffer = null;
  15634. var gl = this._gl;
  15635. // Create the depth/stencil buffer
  15636. if (generateStencilBuffer) {
  15637. depthStencilBuffer = gl.createRenderbuffer();
  15638. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15639. if (samples > 1) {
  15640. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15641. }
  15642. else {
  15643. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15644. }
  15645. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15646. }
  15647. else if (generateDepthBuffer) {
  15648. depthStencilBuffer = gl.createRenderbuffer();
  15649. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15650. if (samples > 1) {
  15651. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15652. }
  15653. else {
  15654. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15655. }
  15656. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15657. }
  15658. return depthStencilBuffer;
  15659. };
  15660. /**
  15661. * Updates the sample count of a render target texture
  15662. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15663. * @param texture defines the texture to update
  15664. * @param samples defines the sample count to set
  15665. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15666. */
  15667. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15668. if (this.webGLVersion < 2 || !texture) {
  15669. return 1;
  15670. }
  15671. if (texture.samples === samples) {
  15672. return samples;
  15673. }
  15674. var gl = this._gl;
  15675. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15676. // Dispose previous render buffers
  15677. if (texture._depthStencilBuffer) {
  15678. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15679. texture._depthStencilBuffer = null;
  15680. }
  15681. if (texture._MSAAFramebuffer) {
  15682. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15683. texture._MSAAFramebuffer = null;
  15684. }
  15685. if (texture._MSAARenderBuffer) {
  15686. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15687. texture._MSAARenderBuffer = null;
  15688. }
  15689. if (samples > 1) {
  15690. var framebuffer = gl.createFramebuffer();
  15691. if (!framebuffer) {
  15692. throw new Error("Unable to create multi sampled framebuffer");
  15693. }
  15694. texture._MSAAFramebuffer = framebuffer;
  15695. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15696. var colorRenderbuffer = gl.createRenderbuffer();
  15697. if (!colorRenderbuffer) {
  15698. throw new Error("Unable to create multi sampled framebuffer");
  15699. }
  15700. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15701. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15702. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15703. texture._MSAARenderBuffer = colorRenderbuffer;
  15704. }
  15705. else {
  15706. this.bindUnboundFramebuffer(texture._framebuffer);
  15707. }
  15708. texture.samples = samples;
  15709. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15710. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15711. this.bindUnboundFramebuffer(null);
  15712. return samples;
  15713. };
  15714. /**
  15715. * Update the sample count for a given multiple render target texture
  15716. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15717. * @param textures defines the textures to update
  15718. * @param samples defines the sample count to set
  15719. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15720. */
  15721. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15722. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15723. return 1;
  15724. }
  15725. if (textures[0].samples === samples) {
  15726. return samples;
  15727. }
  15728. var gl = this._gl;
  15729. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15730. // Dispose previous render buffers
  15731. if (textures[0]._depthStencilBuffer) {
  15732. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15733. textures[0]._depthStencilBuffer = null;
  15734. }
  15735. if (textures[0]._MSAAFramebuffer) {
  15736. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15737. textures[0]._MSAAFramebuffer = null;
  15738. }
  15739. for (var i = 0; i < textures.length; i++) {
  15740. if (textures[i]._MSAARenderBuffer) {
  15741. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15742. textures[i]._MSAARenderBuffer = null;
  15743. }
  15744. }
  15745. if (samples > 1) {
  15746. var framebuffer = gl.createFramebuffer();
  15747. if (!framebuffer) {
  15748. throw new Error("Unable to create multi sampled framebuffer");
  15749. }
  15750. this.bindUnboundFramebuffer(framebuffer);
  15751. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15752. var attachments = [];
  15753. for (var i = 0; i < textures.length; i++) {
  15754. var texture = textures[i];
  15755. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15756. var colorRenderbuffer = gl.createRenderbuffer();
  15757. if (!colorRenderbuffer) {
  15758. throw new Error("Unable to create multi sampled framebuffer");
  15759. }
  15760. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15761. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15762. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15763. texture._MSAAFramebuffer = framebuffer;
  15764. texture._MSAARenderBuffer = colorRenderbuffer;
  15765. texture.samples = samples;
  15766. texture._depthStencilBuffer = depthStencilBuffer;
  15767. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15768. attachments.push(attachment);
  15769. }
  15770. gl.drawBuffers(attachments);
  15771. }
  15772. else {
  15773. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15774. }
  15775. this.bindUnboundFramebuffer(null);
  15776. return samples;
  15777. };
  15778. /** @hidden */
  15779. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15780. if (faceIndex === void 0) { faceIndex = 0; }
  15781. if (lod === void 0) { lod = 0; }
  15782. var gl = this._gl;
  15783. var target = gl.TEXTURE_2D;
  15784. if (texture.isCube) {
  15785. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15786. }
  15787. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15788. };
  15789. /** @hidden */
  15790. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15791. if (faceIndex === void 0) { faceIndex = 0; }
  15792. if (lod === void 0) { lod = 0; }
  15793. var gl = this._gl;
  15794. var textureType = this._getWebGLTextureType(texture.type);
  15795. var format = this._getInternalFormat(texture.format);
  15796. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15797. this._unpackFlipY(texture.invertY);
  15798. var target = gl.TEXTURE_2D;
  15799. if (texture.isCube) {
  15800. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15801. }
  15802. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15803. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15804. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15805. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15806. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15807. };
  15808. /** @hidden */
  15809. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15810. if (faceIndex === void 0) { faceIndex = 0; }
  15811. if (lod === void 0) { lod = 0; }
  15812. var gl = this._gl;
  15813. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15814. this._bindTextureDirectly(bindTarget, texture, true);
  15815. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15816. this._bindTextureDirectly(bindTarget, null, true);
  15817. };
  15818. /** @hidden */
  15819. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15820. if (faceIndex === void 0) { faceIndex = 0; }
  15821. if (lod === void 0) { lod = 0; }
  15822. var gl = this._gl;
  15823. var textureType = this._getWebGLTextureType(texture.type);
  15824. var format = this._getInternalFormat(texture.format);
  15825. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15826. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15827. this._bindTextureDirectly(bindTarget, texture, true);
  15828. this._unpackFlipY(texture.invertY);
  15829. var target = gl.TEXTURE_2D;
  15830. if (texture.isCube) {
  15831. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15832. }
  15833. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15834. this._bindTextureDirectly(bindTarget, null, true);
  15835. };
  15836. /**
  15837. * Creates a new render target cube texture
  15838. * @param size defines the size of the texture
  15839. * @param options defines the options used to create the texture
  15840. * @returns a new render target cube texture stored in an InternalTexture
  15841. */
  15842. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15843. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15844. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15845. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15846. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15847. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15848. }
  15849. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15850. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15851. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15852. }
  15853. var gl = this._gl;
  15854. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15855. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15856. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15857. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15858. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15859. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15860. }
  15861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15862. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15865. for (var face = 0; face < 6; face++) {
  15866. 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);
  15867. }
  15868. // Create the framebuffer
  15869. var framebuffer = gl.createFramebuffer();
  15870. this.bindUnboundFramebuffer(framebuffer);
  15871. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15872. // MipMaps
  15873. if (fullOptions.generateMipMaps) {
  15874. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15875. }
  15876. // Unbind
  15877. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15878. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15879. this.bindUnboundFramebuffer(null);
  15880. texture._framebuffer = framebuffer;
  15881. texture.width = size;
  15882. texture.height = size;
  15883. texture.isReady = true;
  15884. texture.isCube = true;
  15885. texture.samples = 1;
  15886. texture.generateMipMaps = fullOptions.generateMipMaps;
  15887. texture.samplingMode = fullOptions.samplingMode;
  15888. texture.type = fullOptions.type;
  15889. texture.format = fullOptions.format;
  15890. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15891. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15892. this._internalTexturesCache.push(texture);
  15893. return texture;
  15894. };
  15895. /**
  15896. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15897. * @param rootUrl defines the url where the file to load is located
  15898. * @param scene defines the current scene
  15899. * @param lodScale defines scale to apply to the mip map selection
  15900. * @param lodOffset defines offset to apply to the mip map selection
  15901. * @param onLoad defines an optional callback raised when the texture is loaded
  15902. * @param onError defines an optional callback raised if there is an issue to load the texture
  15903. * @param format defines the format of the data
  15904. * @param forcedExtension defines the extension to use to pick the right loader
  15905. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15906. * @returns the cube texture as an InternalTexture
  15907. */
  15908. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15909. var _this = this;
  15910. if (onLoad === void 0) { onLoad = null; }
  15911. if (onError === void 0) { onError = null; }
  15912. if (forcedExtension === void 0) { forcedExtension = null; }
  15913. if (createPolynomials === void 0) { createPolynomials = true; }
  15914. var callback = function (loadData) {
  15915. if (!loadData) {
  15916. if (onLoad) {
  15917. onLoad(null);
  15918. }
  15919. return;
  15920. }
  15921. var texture = loadData.texture;
  15922. if (!createPolynomials) {
  15923. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15924. }
  15925. else if (loadData.info.sphericalPolynomial) {
  15926. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15927. }
  15928. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15929. if (_this._caps.textureLOD) {
  15930. // Do not add extra process if texture lod is supported.
  15931. if (onLoad) {
  15932. onLoad(texture);
  15933. }
  15934. return;
  15935. }
  15936. var mipSlices = 3;
  15937. var gl = _this._gl;
  15938. var width = loadData.width;
  15939. if (!width) {
  15940. return;
  15941. }
  15942. var textures = [];
  15943. for (var i = 0; i < mipSlices; i++) {
  15944. //compute LOD from even spacing in smoothness (matching shader calculation)
  15945. var smoothness = i / (mipSlices - 1);
  15946. var roughness = 1 - smoothness;
  15947. var minLODIndex = lodOffset; // roughness = 0
  15948. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15949. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15950. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15951. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15952. glTextureFromLod.type = texture.type;
  15953. glTextureFromLod.format = texture.format;
  15954. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15955. glTextureFromLod.height = glTextureFromLod.width;
  15956. glTextureFromLod.isCube = true;
  15957. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15962. if (loadData.isDDS) {
  15963. var info = loadData.info;
  15964. var data = loadData.data;
  15965. _this._unpackFlipY(info.isCompressed);
  15966. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15967. }
  15968. else {
  15969. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15970. }
  15971. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15972. // Wrap in a base texture for easy binding.
  15973. var lodTexture = new BABYLON.BaseTexture(scene);
  15974. lodTexture.isCube = true;
  15975. lodTexture._texture = glTextureFromLod;
  15976. glTextureFromLod.isReady = true;
  15977. textures.push(lodTexture);
  15978. }
  15979. texture._lodTextureHigh = textures[2];
  15980. texture._lodTextureMid = textures[1];
  15981. texture._lodTextureLow = textures[0];
  15982. if (onLoad) {
  15983. onLoad(texture);
  15984. }
  15985. };
  15986. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15987. };
  15988. /**
  15989. * Creates a cube texture
  15990. * @param rootUrl defines the url where the files to load is located
  15991. * @param scene defines the current scene
  15992. * @param files defines the list of files to load (1 per face)
  15993. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15994. * @param onLoad defines an optional callback raised when the texture is loaded
  15995. * @param onError defines an optional callback raised if there is an issue to load the texture
  15996. * @param format defines the format of the data
  15997. * @param forcedExtension defines the extension to use to pick the right loader
  15998. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15999. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16000. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16001. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16002. * @returns the cube texture as an InternalTexture
  16003. */
  16004. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16005. var _this = this;
  16006. if (onLoad === void 0) { onLoad = null; }
  16007. if (onError === void 0) { onError = null; }
  16008. if (forcedExtension === void 0) { forcedExtension = null; }
  16009. if (createPolynomials === void 0) { createPolynomials = false; }
  16010. if (lodScale === void 0) { lodScale = 0; }
  16011. if (lodOffset === void 0) { lodOffset = 0; }
  16012. if (fallback === void 0) { fallback = null; }
  16013. var gl = this._gl;
  16014. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16015. texture.isCube = true;
  16016. texture.url = rootUrl;
  16017. texture.generateMipMaps = !noMipmap;
  16018. texture._lodGenerationScale = lodScale;
  16019. texture._lodGenerationOffset = lodOffset;
  16020. if (!this._doNotHandleContextLost) {
  16021. texture._extension = forcedExtension;
  16022. texture._files = files;
  16023. }
  16024. var lastDot = rootUrl.lastIndexOf('.');
  16025. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16026. var loader = null;
  16027. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16028. var availableLoader = _a[_i];
  16029. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16030. loader = availableLoader;
  16031. break;
  16032. }
  16033. }
  16034. var onInternalError = function (request, exception) {
  16035. if (loader) {
  16036. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16037. if (fallbackUrl) {
  16038. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16039. }
  16040. }
  16041. if (onError && request) {
  16042. onError(request.status + " " + request.statusText, exception);
  16043. }
  16044. };
  16045. if (loader) {
  16046. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16047. var onloaddata = function (data) {
  16048. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16049. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16050. };
  16051. if (files && files.length === 6) {
  16052. if (loader.supportCascades) {
  16053. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16054. }
  16055. else if (onError) {
  16056. onError("Textures type does not support cascades.");
  16057. }
  16058. }
  16059. else {
  16060. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16061. }
  16062. }
  16063. else {
  16064. if (!files) {
  16065. throw new Error("Cannot load cubemap because files were not defined");
  16066. }
  16067. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16068. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16069. var height = width;
  16070. _this._prepareWorkingCanvas();
  16071. if (!_this._workingCanvas || !_this._workingContext) {
  16072. return;
  16073. }
  16074. _this._workingCanvas.width = width;
  16075. _this._workingCanvas.height = height;
  16076. var faces = [
  16077. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16078. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16079. ];
  16080. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16081. _this._unpackFlipY(false);
  16082. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16083. for (var index = 0; index < faces.length; index++) {
  16084. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16085. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16086. }
  16087. if (!noMipmap) {
  16088. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16089. }
  16090. _this._setCubeMapTextureParams(!noMipmap);
  16091. texture.width = width;
  16092. texture.height = height;
  16093. texture.isReady = true;
  16094. if (format) {
  16095. texture.format = format;
  16096. }
  16097. texture.onLoadedObservable.notifyObservers(texture);
  16098. texture.onLoadedObservable.clear();
  16099. if (onLoad) {
  16100. onLoad();
  16101. }
  16102. }, files, onError);
  16103. }
  16104. this._internalTexturesCache.push(texture);
  16105. return texture;
  16106. };
  16107. /**
  16108. * @hidden
  16109. */
  16110. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16111. var gl = this._gl;
  16112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16113. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16114. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16116. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16117. // this.resetTextureCache();
  16118. };
  16119. /**
  16120. * Update a raw cube texture
  16121. * @param texture defines the texture to udpdate
  16122. * @param data defines the data to store
  16123. * @param format defines the data format
  16124. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16125. * @param invertY defines if data must be stored with Y axis inverted
  16126. * @param compression defines the compression used (null by default)
  16127. * @param level defines which level of the texture to update
  16128. */
  16129. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16130. if (compression === void 0) { compression = null; }
  16131. if (level === void 0) { level = 0; }
  16132. texture._bufferViewArray = data;
  16133. texture.format = format;
  16134. texture.type = type;
  16135. texture.invertY = invertY;
  16136. texture._compression = compression;
  16137. var gl = this._gl;
  16138. var textureType = this._getWebGLTextureType(type);
  16139. var internalFormat = this._getInternalFormat(format);
  16140. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16141. var needConversion = false;
  16142. if (internalFormat === gl.RGB) {
  16143. internalFormat = gl.RGBA;
  16144. needConversion = true;
  16145. }
  16146. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16147. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16148. if (texture.width % 4 !== 0) {
  16149. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16150. }
  16151. // Data are known to be in +X +Y +Z -X -Y -Z
  16152. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16153. var faceData = data[faceIndex];
  16154. if (compression) {
  16155. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16156. }
  16157. else {
  16158. if (needConversion) {
  16159. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16160. }
  16161. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16162. }
  16163. }
  16164. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16165. if (isPot && texture.generateMipMaps && level === 0) {
  16166. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16167. }
  16168. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16169. // this.resetTextureCache();
  16170. texture.isReady = true;
  16171. };
  16172. /**
  16173. * Creates a new raw cube texture
  16174. * @param data defines the array of data to use to create each face
  16175. * @param size defines the size of the textures
  16176. * @param format defines the format of the data
  16177. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16178. * @param generateMipMaps defines if the engine should generate the mip levels
  16179. * @param invertY defines if data must be stored with Y axis inverted
  16180. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16181. * @param compression defines the compression used (null by default)
  16182. * @returns the cube texture as an InternalTexture
  16183. */
  16184. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16185. if (compression === void 0) { compression = null; }
  16186. var gl = this._gl;
  16187. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16188. texture.isCube = true;
  16189. texture.format = format;
  16190. texture.type = type;
  16191. if (!this._doNotHandleContextLost) {
  16192. texture._bufferViewArray = data;
  16193. }
  16194. var textureType = this._getWebGLTextureType(type);
  16195. var internalFormat = this._getInternalFormat(format);
  16196. if (internalFormat === gl.RGB) {
  16197. internalFormat = gl.RGBA;
  16198. }
  16199. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16200. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16201. generateMipMaps = false;
  16202. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16203. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16204. }
  16205. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16206. generateMipMaps = false;
  16207. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16208. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16209. }
  16210. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16211. generateMipMaps = false;
  16212. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16213. }
  16214. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16215. generateMipMaps = false;
  16216. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16217. }
  16218. var width = size;
  16219. var height = width;
  16220. texture.width = width;
  16221. texture.height = height;
  16222. // Double check on POT to generate Mips.
  16223. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16224. if (!isPot) {
  16225. generateMipMaps = false;
  16226. }
  16227. // Upload data if needed. The texture won't be ready until then.
  16228. if (data) {
  16229. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16230. }
  16231. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16232. // Filters
  16233. if (data && generateMipMaps) {
  16234. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16235. }
  16236. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16237. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16238. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16239. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16240. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16241. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16242. texture.generateMipMaps = generateMipMaps;
  16243. return texture;
  16244. };
  16245. /**
  16246. * Creates a new raw cube texture from a specified url
  16247. * @param url defines the url where the data is located
  16248. * @param scene defines the current scene
  16249. * @param size defines the size of the textures
  16250. * @param format defines the format of the data
  16251. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16252. * @param noMipmap defines if the engine should avoid generating the mip levels
  16253. * @param callback defines a callback used to extract texture data from loaded data
  16254. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16255. * @param onLoad defines a callback called when texture is loaded
  16256. * @param onError defines a callback called if there is an error
  16257. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16258. * @param invertY defines if data must be stored with Y axis inverted
  16259. * @returns the cube texture as an InternalTexture
  16260. */
  16261. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16262. var _this = this;
  16263. if (onLoad === void 0) { onLoad = null; }
  16264. if (onError === void 0) { onError = null; }
  16265. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16266. if (invertY === void 0) { invertY = false; }
  16267. var gl = this._gl;
  16268. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16269. scene._addPendingData(texture);
  16270. texture.url = url;
  16271. this._internalTexturesCache.push(texture);
  16272. var onerror = function (request, exception) {
  16273. scene._removePendingData(texture);
  16274. if (onError && request) {
  16275. onError(request.status + " " + request.statusText, exception);
  16276. }
  16277. };
  16278. var internalCallback = function (data) {
  16279. var width = texture.width;
  16280. var faceDataArrays = callback(data);
  16281. if (!faceDataArrays) {
  16282. return;
  16283. }
  16284. if (mipmapGenerator) {
  16285. var textureType = _this._getWebGLTextureType(type);
  16286. var internalFormat = _this._getInternalFormat(format);
  16287. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16288. var needConversion = false;
  16289. if (internalFormat === gl.RGB) {
  16290. internalFormat = gl.RGBA;
  16291. needConversion = true;
  16292. }
  16293. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16294. _this._unpackFlipY(false);
  16295. var mipData = mipmapGenerator(faceDataArrays);
  16296. for (var level = 0; level < mipData.length; level++) {
  16297. var mipSize = width >> level;
  16298. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16299. var mipFaceData = mipData[level][faceIndex];
  16300. if (needConversion) {
  16301. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16302. }
  16303. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16304. }
  16305. }
  16306. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16307. }
  16308. else {
  16309. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16310. }
  16311. texture.isReady = true;
  16312. // this.resetTextureCache();
  16313. scene._removePendingData(texture);
  16314. if (onLoad) {
  16315. onLoad();
  16316. }
  16317. };
  16318. this._loadFile(url, function (data) {
  16319. internalCallback(data);
  16320. }, undefined, scene.database, true, onerror);
  16321. return texture;
  16322. };
  16323. ;
  16324. /**
  16325. * Update a raw 3D texture
  16326. * @param texture defines the texture to update
  16327. * @param data defines the data to store
  16328. * @param format defines the data format
  16329. * @param invertY defines if data must be stored with Y axis inverted
  16330. * @param compression defines the used compression (can be null)
  16331. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16332. */
  16333. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16334. if (compression === void 0) { compression = null; }
  16335. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16336. var internalType = this._getWebGLTextureType(textureType);
  16337. var internalFormat = this._getInternalFormat(format);
  16338. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16339. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16340. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16341. if (!this._doNotHandleContextLost) {
  16342. texture._bufferView = data;
  16343. texture.format = format;
  16344. texture.invertY = invertY;
  16345. texture._compression = compression;
  16346. }
  16347. if (texture.width % 4 !== 0) {
  16348. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16349. }
  16350. if (compression && data) {
  16351. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16352. }
  16353. else {
  16354. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16355. }
  16356. if (texture.generateMipMaps) {
  16357. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16358. }
  16359. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16360. // this.resetTextureCache();
  16361. texture.isReady = true;
  16362. };
  16363. /**
  16364. * Creates a new raw 3D texture
  16365. * @param data defines the data used to create the texture
  16366. * @param width defines the width of the texture
  16367. * @param height defines the height of the texture
  16368. * @param depth defines the depth of the texture
  16369. * @param format defines the format of the texture
  16370. * @param generateMipMaps defines if the engine must generate mip levels
  16371. * @param invertY defines if data must be stored with Y axis inverted
  16372. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16373. * @param compression defines the compressed used (can be null)
  16374. * @param textureType defines the compressed used (can be null)
  16375. * @returns a new raw 3D texture (stored in an InternalTexture)
  16376. */
  16377. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16378. if (compression === void 0) { compression = null; }
  16379. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16380. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16381. texture.baseWidth = width;
  16382. texture.baseHeight = height;
  16383. texture.baseDepth = depth;
  16384. texture.width = width;
  16385. texture.height = height;
  16386. texture.depth = depth;
  16387. texture.format = format;
  16388. texture.type = textureType;
  16389. texture.generateMipMaps = generateMipMaps;
  16390. texture.samplingMode = samplingMode;
  16391. texture.is3D = true;
  16392. if (!this._doNotHandleContextLost) {
  16393. texture._bufferView = data;
  16394. }
  16395. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16396. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16397. // Filters
  16398. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16399. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16400. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16401. if (generateMipMaps) {
  16402. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16403. }
  16404. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16405. this._internalTexturesCache.push(texture);
  16406. return texture;
  16407. };
  16408. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16409. var gl = this._gl;
  16410. if (!gl) {
  16411. return;
  16412. }
  16413. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16414. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16415. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16416. if (!noMipmap && !isCompressed) {
  16417. gl.generateMipmap(gl.TEXTURE_2D);
  16418. }
  16419. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16420. // this.resetTextureCache();
  16421. if (scene) {
  16422. scene._removePendingData(texture);
  16423. }
  16424. texture.onLoadedObservable.notifyObservers(texture);
  16425. texture.onLoadedObservable.clear();
  16426. };
  16427. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16428. var _this = this;
  16429. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16430. var maxTextureSize = this.getCaps().maxTextureSize;
  16431. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16432. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16433. var gl = this._gl;
  16434. if (!gl) {
  16435. return;
  16436. }
  16437. if (!texture._webGLTexture) {
  16438. // this.resetTextureCache();
  16439. if (scene) {
  16440. scene._removePendingData(texture);
  16441. }
  16442. return;
  16443. }
  16444. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16445. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16446. texture.baseWidth = width;
  16447. texture.baseHeight = height;
  16448. texture.width = potWidth;
  16449. texture.height = potHeight;
  16450. texture.isReady = true;
  16451. if (processFunction(potWidth, potHeight, function () {
  16452. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16453. })) {
  16454. // Returning as texture needs extra async steps
  16455. return;
  16456. }
  16457. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16458. };
  16459. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16460. // Create new RGBA data container.
  16461. var rgbaData;
  16462. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16463. rgbaData = new Float32Array(width * height * 4);
  16464. }
  16465. else {
  16466. rgbaData = new Uint32Array(width * height * 4);
  16467. }
  16468. // Convert each pixel.
  16469. for (var x = 0; x < width; x++) {
  16470. for (var y = 0; y < height; y++) {
  16471. var index = (y * width + x) * 3;
  16472. var newIndex = (y * width + x) * 4;
  16473. // Map Old Value to new value.
  16474. rgbaData[newIndex + 0] = rgbData[index + 0];
  16475. rgbaData[newIndex + 1] = rgbData[index + 1];
  16476. rgbaData[newIndex + 2] = rgbData[index + 2];
  16477. // Add fully opaque alpha channel.
  16478. rgbaData[newIndex + 3] = 1;
  16479. }
  16480. }
  16481. return rgbaData;
  16482. };
  16483. /** @hidden */
  16484. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16485. var gl = this._gl;
  16486. if (texture._framebuffer) {
  16487. gl.deleteFramebuffer(texture._framebuffer);
  16488. texture._framebuffer = null;
  16489. }
  16490. if (texture._depthStencilBuffer) {
  16491. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16492. texture._depthStencilBuffer = null;
  16493. }
  16494. if (texture._MSAAFramebuffer) {
  16495. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16496. texture._MSAAFramebuffer = null;
  16497. }
  16498. if (texture._MSAARenderBuffer) {
  16499. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16500. texture._MSAARenderBuffer = null;
  16501. }
  16502. };
  16503. /** @hidden */
  16504. Engine.prototype._releaseTexture = function (texture) {
  16505. var gl = this._gl;
  16506. this._releaseFramebufferObjects(texture);
  16507. gl.deleteTexture(texture._webGLTexture);
  16508. // Unbind channels
  16509. this.unbindAllTextures();
  16510. var index = this._internalTexturesCache.indexOf(texture);
  16511. if (index !== -1) {
  16512. this._internalTexturesCache.splice(index, 1);
  16513. }
  16514. // Integrated fixed lod samplers.
  16515. if (texture._lodTextureHigh) {
  16516. texture._lodTextureHigh.dispose();
  16517. }
  16518. if (texture._lodTextureMid) {
  16519. texture._lodTextureMid.dispose();
  16520. }
  16521. if (texture._lodTextureLow) {
  16522. texture._lodTextureLow.dispose();
  16523. }
  16524. // Set output texture of post process to null if the texture has been released/disposed
  16525. this.scenes.forEach(function (scene) {
  16526. scene.postProcesses.forEach(function (postProcess) {
  16527. if (postProcess._outputTexture == texture) {
  16528. postProcess._outputTexture = null;
  16529. }
  16530. });
  16531. scene.cameras.forEach(function (camera) {
  16532. camera._postProcesses.forEach(function (postProcess) {
  16533. if (postProcess) {
  16534. if (postProcess._outputTexture == texture) {
  16535. postProcess._outputTexture = null;
  16536. }
  16537. }
  16538. });
  16539. });
  16540. });
  16541. };
  16542. Engine.prototype.setProgram = function (program) {
  16543. if (this._currentProgram !== program) {
  16544. this._gl.useProgram(program);
  16545. this._currentProgram = program;
  16546. }
  16547. };
  16548. /**
  16549. * Binds an effect to the webGL context
  16550. * @param effect defines the effect to bind
  16551. */
  16552. Engine.prototype.bindSamplers = function (effect) {
  16553. this.setProgram(effect.getProgram());
  16554. var samplers = effect.getSamplers();
  16555. for (var index = 0; index < samplers.length; index++) {
  16556. var uniform = effect.getUniform(samplers[index]);
  16557. if (uniform) {
  16558. this._boundUniforms[index] = uniform;
  16559. }
  16560. }
  16561. this._currentEffect = null;
  16562. };
  16563. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16564. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16565. return;
  16566. }
  16567. // Remove
  16568. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16569. // Bind last to it
  16570. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16571. // Bind to dummy
  16572. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16573. };
  16574. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16575. if (!internalTexture) {
  16576. return -1;
  16577. }
  16578. internalTexture._initialSlot = channel;
  16579. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16580. if (channel !== internalTexture._designatedSlot) {
  16581. this._textureCollisions.addCount(1, false);
  16582. }
  16583. }
  16584. else {
  16585. if (channel !== internalTexture._designatedSlot) {
  16586. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16587. return internalTexture._designatedSlot;
  16588. }
  16589. else {
  16590. // No slot for this texture, let's pick a new one (if we find a free slot)
  16591. if (this._nextFreeTextureSlots.length) {
  16592. return this._nextFreeTextureSlots[0];
  16593. }
  16594. // We need to recycle the oldest bound texture, sorry.
  16595. this._textureCollisions.addCount(1, false);
  16596. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16597. }
  16598. }
  16599. }
  16600. return channel;
  16601. };
  16602. Engine.prototype._linkTrackers = function (previous, next) {
  16603. previous.next = next;
  16604. next.previous = previous;
  16605. };
  16606. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16607. var currentSlot = internalTexture._designatedSlot;
  16608. if (currentSlot === -1) {
  16609. return -1;
  16610. }
  16611. internalTexture._designatedSlot = -1;
  16612. if (this.disableTextureBindingOptimization) {
  16613. return -1;
  16614. }
  16615. // Remove from bound list
  16616. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16617. // Free the slot
  16618. this._boundTexturesCache[currentSlot] = null;
  16619. this._nextFreeTextureSlots.push(currentSlot);
  16620. return currentSlot;
  16621. };
  16622. Engine.prototype._activateCurrentTexture = function () {
  16623. if (this._currentTextureChannel !== this._activeChannel) {
  16624. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16625. this._currentTextureChannel = this._activeChannel;
  16626. }
  16627. };
  16628. /** @hidden */
  16629. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16630. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16631. if (force === void 0) { force = false; }
  16632. var wasPreviouslyBound = false;
  16633. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16634. this._activeChannel = texture._designatedSlot;
  16635. }
  16636. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16637. var isTextureForRendering = texture && texture._initialSlot > -1;
  16638. if (currentTextureBound !== texture || force) {
  16639. if (currentTextureBound) {
  16640. this._removeDesignatedSlot(currentTextureBound);
  16641. }
  16642. this._activateCurrentTexture();
  16643. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16644. this._boundTexturesCache[this._activeChannel] = texture;
  16645. if (texture) {
  16646. if (!this.disableTextureBindingOptimization) {
  16647. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16648. if (slotIndex > -1) {
  16649. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16650. }
  16651. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16652. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16653. }
  16654. texture._designatedSlot = this._activeChannel;
  16655. }
  16656. }
  16657. else if (forTextureDataUpdate) {
  16658. wasPreviouslyBound = true;
  16659. this._activateCurrentTexture();
  16660. }
  16661. if (isTextureForRendering && !forTextureDataUpdate) {
  16662. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16663. }
  16664. return wasPreviouslyBound;
  16665. };
  16666. /** @hidden */
  16667. Engine.prototype._bindTexture = function (channel, texture) {
  16668. if (channel < 0) {
  16669. return;
  16670. }
  16671. if (texture) {
  16672. channel = this._getCorrectTextureChannel(channel, texture);
  16673. }
  16674. this._activeChannel = channel;
  16675. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16676. };
  16677. /**
  16678. * Sets a texture to the webGL context from a postprocess
  16679. * @param channel defines the channel to use
  16680. * @param postProcess defines the source postprocess
  16681. */
  16682. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16683. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16684. };
  16685. /**
  16686. * Binds the output of the passed in post process to the texture channel specified
  16687. * @param channel The channel the texture should be bound to
  16688. * @param postProcess The post process which's output should be bound
  16689. */
  16690. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16691. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16692. };
  16693. /**
  16694. * Unbind all textures from the webGL context
  16695. */
  16696. Engine.prototype.unbindAllTextures = function () {
  16697. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16698. this._activeChannel = channel;
  16699. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16700. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16701. if (this.webGLVersion > 1) {
  16702. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16703. }
  16704. }
  16705. };
  16706. /**
  16707. * Sets a texture to the according uniform.
  16708. * @param channel The texture channel
  16709. * @param uniform The uniform to set
  16710. * @param texture The texture to apply
  16711. */
  16712. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16713. if (channel < 0) {
  16714. return;
  16715. }
  16716. if (uniform) {
  16717. this._boundUniforms[channel] = uniform;
  16718. }
  16719. this._setTexture(channel, texture);
  16720. };
  16721. /**
  16722. * Sets a depth stencil texture from a render target to the according uniform.
  16723. * @param channel The texture channel
  16724. * @param uniform The uniform to set
  16725. * @param texture The render target texture containing the depth stencil texture to apply
  16726. */
  16727. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16728. if (channel < 0) {
  16729. return;
  16730. }
  16731. if (uniform) {
  16732. this._boundUniforms[channel] = uniform;
  16733. }
  16734. if (!texture || !texture.depthStencilTexture) {
  16735. this._setTexture(channel, null);
  16736. }
  16737. else {
  16738. this._setTexture(channel, texture, false, true);
  16739. }
  16740. };
  16741. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16742. var uniform = this._boundUniforms[sourceSlot];
  16743. if (uniform._currentState === destination) {
  16744. return;
  16745. }
  16746. this._gl.uniform1i(uniform, destination);
  16747. uniform._currentState = destination;
  16748. };
  16749. Engine.prototype._getTextureWrapMode = function (mode) {
  16750. switch (mode) {
  16751. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16752. return this._gl.REPEAT;
  16753. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16754. return this._gl.CLAMP_TO_EDGE;
  16755. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16756. return this._gl.MIRRORED_REPEAT;
  16757. }
  16758. return this._gl.REPEAT;
  16759. };
  16760. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16761. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16762. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16763. // Not ready?
  16764. if (!texture) {
  16765. if (this._boundTexturesCache[channel] != null) {
  16766. this._activeChannel = channel;
  16767. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16768. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16769. if (this.webGLVersion > 1) {
  16770. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16771. }
  16772. }
  16773. return false;
  16774. }
  16775. // Video
  16776. if (texture.video) {
  16777. this._activeChannel = channel;
  16778. texture.update();
  16779. }
  16780. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16781. texture.delayLoad();
  16782. return false;
  16783. }
  16784. var internalTexture;
  16785. if (depthStencilTexture) {
  16786. internalTexture = texture.depthStencilTexture;
  16787. }
  16788. else if (texture.isReady()) {
  16789. internalTexture = texture.getInternalTexture();
  16790. }
  16791. else if (texture.isCube) {
  16792. internalTexture = this.emptyCubeTexture;
  16793. }
  16794. else if (texture.is3D) {
  16795. internalTexture = this.emptyTexture3D;
  16796. }
  16797. else {
  16798. internalTexture = this.emptyTexture;
  16799. }
  16800. if (!isPartOfTextureArray) {
  16801. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16802. }
  16803. var needToBind = true;
  16804. if (this._boundTexturesCache[channel] === internalTexture) {
  16805. this._moveBoundTextureOnTop(internalTexture);
  16806. if (!isPartOfTextureArray) {
  16807. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16808. }
  16809. needToBind = false;
  16810. }
  16811. this._activeChannel = channel;
  16812. if (internalTexture && internalTexture.is3D) {
  16813. if (needToBind) {
  16814. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16815. }
  16816. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16817. internalTexture._cachedWrapU = texture.wrapU;
  16818. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16819. }
  16820. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16821. internalTexture._cachedWrapV = texture.wrapV;
  16822. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16823. }
  16824. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16825. internalTexture._cachedWrapR = texture.wrapR;
  16826. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16827. }
  16828. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16829. }
  16830. else if (internalTexture && internalTexture.isCube) {
  16831. if (needToBind) {
  16832. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16833. }
  16834. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16835. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16836. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16837. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16838. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16839. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16840. }
  16841. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16842. }
  16843. else {
  16844. if (needToBind) {
  16845. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16846. }
  16847. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16848. internalTexture._cachedWrapU = texture.wrapU;
  16849. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16850. }
  16851. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16852. internalTexture._cachedWrapV = texture.wrapV;
  16853. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16854. }
  16855. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16856. }
  16857. return true;
  16858. };
  16859. /**
  16860. * Sets an array of texture to the webGL context
  16861. * @param channel defines the channel where the texture array must be set
  16862. * @param uniform defines the associated uniform location
  16863. * @param textures defines the array of textures to bind
  16864. */
  16865. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16866. if (channel < 0 || !uniform) {
  16867. return;
  16868. }
  16869. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16870. this._textureUnits = new Int32Array(textures.length);
  16871. }
  16872. for (var i = 0; i < textures.length; i++) {
  16873. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16874. }
  16875. this._gl.uniform1iv(uniform, this._textureUnits);
  16876. for (var index = 0; index < textures.length; index++) {
  16877. this._setTexture(this._textureUnits[index], textures[index], true);
  16878. }
  16879. };
  16880. /** @hidden */
  16881. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16882. var internalTexture = texture.getInternalTexture();
  16883. if (!internalTexture) {
  16884. return;
  16885. }
  16886. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16887. var value = texture.anisotropicFilteringLevel;
  16888. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16889. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16890. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16891. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16892. }
  16893. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16894. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16895. internalTexture._cachedAnisotropicFilteringLevel = value;
  16896. }
  16897. };
  16898. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16899. this._bindTextureDirectly(target, texture, true, true);
  16900. this._gl.texParameterf(target, parameter, value);
  16901. };
  16902. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16903. if (texture) {
  16904. this._bindTextureDirectly(target, texture, true, true);
  16905. }
  16906. this._gl.texParameteri(target, parameter, value);
  16907. };
  16908. /**
  16909. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16910. * @param x defines the x coordinate of the rectangle where pixels must be read
  16911. * @param y defines the y coordinate of the rectangle where pixels must be read
  16912. * @param width defines the width of the rectangle where pixels must be read
  16913. * @param height defines the height of the rectangle where pixels must be read
  16914. * @returns a Uint8Array containing RGBA colors
  16915. */
  16916. Engine.prototype.readPixels = function (x, y, width, height) {
  16917. var data = new Uint8Array(height * width * 4);
  16918. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16919. return data;
  16920. };
  16921. /**
  16922. * Add an externaly attached data from its key.
  16923. * This method call will fail and return false, if such key already exists.
  16924. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16925. * @param key the unique key that identifies the data
  16926. * @param data the data object to associate to the key for this Engine instance
  16927. * @return true if no such key were already present and the data was added successfully, false otherwise
  16928. */
  16929. Engine.prototype.addExternalData = function (key, data) {
  16930. if (!this._externalData) {
  16931. this._externalData = new BABYLON.StringDictionary();
  16932. }
  16933. return this._externalData.add(key, data);
  16934. };
  16935. /**
  16936. * Get an externaly attached data from its key
  16937. * @param key the unique key that identifies the data
  16938. * @return the associated data, if present (can be null), or undefined if not present
  16939. */
  16940. Engine.prototype.getExternalData = function (key) {
  16941. if (!this._externalData) {
  16942. this._externalData = new BABYLON.StringDictionary();
  16943. }
  16944. return this._externalData.get(key);
  16945. };
  16946. /**
  16947. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16948. * @param key the unique key that identifies the data
  16949. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16950. * @return the associated data, can be null if the factory returned null.
  16951. */
  16952. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16953. if (!this._externalData) {
  16954. this._externalData = new BABYLON.StringDictionary();
  16955. }
  16956. return this._externalData.getOrAddWithFactory(key, factory);
  16957. };
  16958. /**
  16959. * Remove an externaly attached data from the Engine instance
  16960. * @param key the unique key that identifies the data
  16961. * @return true if the data was successfully removed, false if it doesn't exist
  16962. */
  16963. Engine.prototype.removeExternalData = function (key) {
  16964. if (!this._externalData) {
  16965. this._externalData = new BABYLON.StringDictionary();
  16966. }
  16967. return this._externalData.remove(key);
  16968. };
  16969. /**
  16970. * Unbind all vertex attributes from the webGL context
  16971. */
  16972. Engine.prototype.unbindAllAttributes = function () {
  16973. if (this._mustWipeVertexAttributes) {
  16974. this._mustWipeVertexAttributes = false;
  16975. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16976. this._gl.disableVertexAttribArray(i);
  16977. this._vertexAttribArraysEnabled[i] = false;
  16978. this._currentBufferPointers[i].active = false;
  16979. }
  16980. return;
  16981. }
  16982. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16983. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16984. continue;
  16985. }
  16986. this._gl.disableVertexAttribArray(i);
  16987. this._vertexAttribArraysEnabled[i] = false;
  16988. this._currentBufferPointers[i].active = false;
  16989. }
  16990. };
  16991. /**
  16992. * 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
  16993. */
  16994. Engine.prototype.releaseEffects = function () {
  16995. for (var name in this._compiledEffects) {
  16996. this._deleteProgram(this._compiledEffects[name]._program);
  16997. }
  16998. this._compiledEffects = {};
  16999. };
  17000. /**
  17001. * Dispose and release all associated resources
  17002. */
  17003. Engine.prototype.dispose = function () {
  17004. this.hideLoadingUI();
  17005. this.stopRenderLoop();
  17006. // Release postProcesses
  17007. while (this.postProcesses.length) {
  17008. this.postProcesses[0].dispose();
  17009. }
  17010. // Empty texture
  17011. if (this._emptyTexture) {
  17012. this._releaseTexture(this._emptyTexture);
  17013. this._emptyTexture = null;
  17014. }
  17015. if (this._emptyCubeTexture) {
  17016. this._releaseTexture(this._emptyCubeTexture);
  17017. this._emptyCubeTexture = null;
  17018. }
  17019. // Rescale PP
  17020. if (this._rescalePostProcess) {
  17021. this._rescalePostProcess.dispose();
  17022. }
  17023. // Release scenes
  17024. while (this.scenes.length) {
  17025. this.scenes[0].dispose();
  17026. }
  17027. // Release audio engine
  17028. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17029. Engine.audioEngine.dispose();
  17030. }
  17031. // Release effects
  17032. this.releaseEffects();
  17033. // Unbind
  17034. this.unbindAllAttributes();
  17035. this._boundUniforms = [];
  17036. if (this._dummyFramebuffer) {
  17037. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17038. }
  17039. //WebVR
  17040. this.disableVR();
  17041. // Events
  17042. if (BABYLON.Tools.IsWindowObjectExist()) {
  17043. window.removeEventListener("blur", this._onBlur);
  17044. window.removeEventListener("focus", this._onFocus);
  17045. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17046. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17047. if (this._renderingCanvas) {
  17048. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17049. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17050. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17051. if (!this._doNotHandleContextLost) {
  17052. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17053. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17054. }
  17055. }
  17056. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17057. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17058. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17059. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17060. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17061. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17062. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17063. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17064. if (this._onVrDisplayConnect) {
  17065. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17066. if (this._onVrDisplayDisconnect) {
  17067. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17068. }
  17069. if (this._onVrDisplayPresentChange) {
  17070. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17071. }
  17072. this._onVrDisplayConnect = null;
  17073. this._onVrDisplayDisconnect = null;
  17074. }
  17075. }
  17076. // Remove from Instances
  17077. var index = Engine.Instances.indexOf(this);
  17078. if (index >= 0) {
  17079. Engine.Instances.splice(index, 1);
  17080. }
  17081. this._workingCanvas = null;
  17082. this._workingContext = null;
  17083. this._currentBufferPointers = [];
  17084. this._renderingCanvas = null;
  17085. this._currentProgram = null;
  17086. this._bindedRenderFunction = null;
  17087. this.onResizeObservable.clear();
  17088. this.onCanvasBlurObservable.clear();
  17089. this.onCanvasFocusObservable.clear();
  17090. this.onCanvasPointerOutObservable.clear();
  17091. this.onBeginFrameObservable.clear();
  17092. this.onEndFrameObservable.clear();
  17093. BABYLON.Effect.ResetCache();
  17094. // Abort active requests
  17095. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17096. var request = _a[_i];
  17097. request.abort();
  17098. }
  17099. };
  17100. // Loading screen
  17101. /**
  17102. * Display the loading screen
  17103. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17104. */
  17105. Engine.prototype.displayLoadingUI = function () {
  17106. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17107. return;
  17108. }
  17109. var loadingScreen = this.loadingScreen;
  17110. if (loadingScreen) {
  17111. loadingScreen.displayLoadingUI();
  17112. }
  17113. };
  17114. /**
  17115. * Hide the loading screen
  17116. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17117. */
  17118. Engine.prototype.hideLoadingUI = function () {
  17119. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17120. return;
  17121. }
  17122. var loadingScreen = this.loadingScreen;
  17123. if (loadingScreen) {
  17124. loadingScreen.hideLoadingUI();
  17125. }
  17126. };
  17127. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17128. /**
  17129. * Gets the current loading screen object
  17130. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17131. */
  17132. get: function () {
  17133. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17134. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17135. return this._loadingScreen;
  17136. },
  17137. /**
  17138. * Sets the current loading screen object
  17139. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17140. */
  17141. set: function (loadingScreen) {
  17142. this._loadingScreen = loadingScreen;
  17143. },
  17144. enumerable: true,
  17145. configurable: true
  17146. });
  17147. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17148. /**
  17149. * Sets the current loading screen text
  17150. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17151. */
  17152. set: function (text) {
  17153. this.loadingScreen.loadingUIText = text;
  17154. },
  17155. enumerable: true,
  17156. configurable: true
  17157. });
  17158. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17159. /**
  17160. * Sets the current loading screen background color
  17161. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17162. */
  17163. set: function (color) {
  17164. this.loadingScreen.loadingUIBackgroundColor = color;
  17165. },
  17166. enumerable: true,
  17167. configurable: true
  17168. });
  17169. /**
  17170. * Attach a new callback raised when context lost event is fired
  17171. * @param callback defines the callback to call
  17172. */
  17173. Engine.prototype.attachContextLostEvent = function (callback) {
  17174. if (this._renderingCanvas) {
  17175. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17176. }
  17177. };
  17178. /**
  17179. * Attach a new callback raised when context restored event is fired
  17180. * @param callback defines the callback to call
  17181. */
  17182. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17183. if (this._renderingCanvas) {
  17184. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17185. }
  17186. };
  17187. /**
  17188. * Gets the source code of the vertex shader associated with a specific webGL program
  17189. * @param program defines the program to use
  17190. * @returns a string containing the source code of the vertex shader associated with the program
  17191. */
  17192. Engine.prototype.getVertexShaderSource = function (program) {
  17193. var shaders = this._gl.getAttachedShaders(program);
  17194. if (!shaders) {
  17195. return null;
  17196. }
  17197. return this._gl.getShaderSource(shaders[0]);
  17198. };
  17199. /**
  17200. * Gets the source code of the fragment shader associated with a specific webGL program
  17201. * @param program defines the program to use
  17202. * @returns a string containing the source code of the fragment shader associated with the program
  17203. */
  17204. Engine.prototype.getFragmentShaderSource = function (program) {
  17205. var shaders = this._gl.getAttachedShaders(program);
  17206. if (!shaders) {
  17207. return null;
  17208. }
  17209. return this._gl.getShaderSource(shaders[1]);
  17210. };
  17211. /**
  17212. * Get the current error code of the webGL context
  17213. * @returns the error code
  17214. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17215. */
  17216. Engine.prototype.getError = function () {
  17217. return this._gl.getError();
  17218. };
  17219. // FPS
  17220. /**
  17221. * Gets the current framerate
  17222. * @returns a number representing the framerate
  17223. */
  17224. Engine.prototype.getFps = function () {
  17225. return this._fps;
  17226. };
  17227. /**
  17228. * Gets the time spent between current and previous frame
  17229. * @returns a number representing the delta time in ms
  17230. */
  17231. Engine.prototype.getDeltaTime = function () {
  17232. return this._deltaTime;
  17233. };
  17234. Engine.prototype._measureFps = function () {
  17235. this._performanceMonitor.sampleFrame();
  17236. this._fps = this._performanceMonitor.averageFPS;
  17237. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17238. };
  17239. /** @hidden */
  17240. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17241. if (faceIndex === void 0) { faceIndex = -1; }
  17242. if (level === void 0) { level = 0; }
  17243. if (buffer === void 0) { buffer = null; }
  17244. var gl = this._gl;
  17245. if (!this._dummyFramebuffer) {
  17246. var dummy = gl.createFramebuffer();
  17247. if (!dummy) {
  17248. throw new Error("Unable to create dummy framebuffer");
  17249. }
  17250. this._dummyFramebuffer = dummy;
  17251. }
  17252. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17253. if (faceIndex > -1) {
  17254. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17255. }
  17256. else {
  17257. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17258. }
  17259. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17260. switch (readType) {
  17261. case gl.UNSIGNED_BYTE:
  17262. if (!buffer) {
  17263. buffer = new Uint8Array(4 * width * height);
  17264. }
  17265. readType = gl.UNSIGNED_BYTE;
  17266. break;
  17267. default:
  17268. if (!buffer) {
  17269. buffer = new Float32Array(4 * width * height);
  17270. }
  17271. readType = gl.FLOAT;
  17272. break;
  17273. }
  17274. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17275. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17276. return buffer;
  17277. };
  17278. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17279. if (this._webGLVersion > 1) {
  17280. return this._caps.colorBufferFloat;
  17281. }
  17282. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17283. };
  17284. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17285. if (this._webGLVersion > 1) {
  17286. return this._caps.colorBufferFloat;
  17287. }
  17288. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17289. };
  17290. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17291. Engine.prototype._canRenderToFramebuffer = function (type) {
  17292. var gl = this._gl;
  17293. //clear existing errors
  17294. while (gl.getError() !== gl.NO_ERROR) { }
  17295. var successful = true;
  17296. var texture = gl.createTexture();
  17297. gl.bindTexture(gl.TEXTURE_2D, texture);
  17298. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17301. var fb = gl.createFramebuffer();
  17302. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17303. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17304. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17305. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17306. successful = successful && (gl.getError() === gl.NO_ERROR);
  17307. //try render by clearing frame buffer's color buffer
  17308. if (successful) {
  17309. gl.clear(gl.COLOR_BUFFER_BIT);
  17310. successful = successful && (gl.getError() === gl.NO_ERROR);
  17311. }
  17312. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17313. if (successful) {
  17314. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17315. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17316. var readFormat = gl.RGBA;
  17317. var readType = gl.UNSIGNED_BYTE;
  17318. var buffer = new Uint8Array(4);
  17319. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17320. successful = successful && (gl.getError() === gl.NO_ERROR);
  17321. }
  17322. //clean up
  17323. gl.deleteTexture(texture);
  17324. gl.deleteFramebuffer(fb);
  17325. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17326. //clear accumulated errors
  17327. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17328. return successful;
  17329. };
  17330. /** @hidden */
  17331. Engine.prototype._getWebGLTextureType = function (type) {
  17332. if (this._webGLVersion === 1) {
  17333. switch (type) {
  17334. case Engine.TEXTURETYPE_FLOAT:
  17335. return this._gl.FLOAT;
  17336. case Engine.TEXTURETYPE_HALF_FLOAT:
  17337. return this._gl.HALF_FLOAT_OES;
  17338. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17339. return this._gl.UNSIGNED_BYTE;
  17340. }
  17341. return this._gl.UNSIGNED_BYTE;
  17342. }
  17343. switch (type) {
  17344. case Engine.TEXTURETYPE_BYTE:
  17345. return this._gl.BYTE;
  17346. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17347. return this._gl.UNSIGNED_BYTE;
  17348. case Engine.TEXTURETYPE_SHORT:
  17349. return this._gl.SHORT;
  17350. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17351. return this._gl.UNSIGNED_SHORT;
  17352. case Engine.TEXTURETYPE_INT:
  17353. return this._gl.INT;
  17354. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17355. return this._gl.UNSIGNED_INT;
  17356. case Engine.TEXTURETYPE_FLOAT:
  17357. return this._gl.FLOAT;
  17358. case Engine.TEXTURETYPE_HALF_FLOAT:
  17359. return this._gl.HALF_FLOAT;
  17360. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17361. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17362. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17363. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17364. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17365. return this._gl.UNSIGNED_SHORT_5_6_5;
  17366. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17367. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17368. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17369. return this._gl.UNSIGNED_INT_24_8;
  17370. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17371. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17372. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17373. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17374. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17375. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17376. }
  17377. return this._gl.UNSIGNED_BYTE;
  17378. };
  17379. ;
  17380. Engine.prototype._getInternalFormat = function (format) {
  17381. var internalFormat = this._gl.RGBA;
  17382. switch (format) {
  17383. case Engine.TEXTUREFORMAT_ALPHA:
  17384. internalFormat = this._gl.ALPHA;
  17385. break;
  17386. case Engine.TEXTUREFORMAT_LUMINANCE:
  17387. internalFormat = this._gl.LUMINANCE;
  17388. break;
  17389. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17390. internalFormat = this._gl.LUMINANCE_ALPHA;
  17391. break;
  17392. case Engine.TEXTUREFORMAT_RED:
  17393. internalFormat = this._gl.RED;
  17394. break;
  17395. case Engine.TEXTUREFORMAT_RG:
  17396. internalFormat = this._gl.RG;
  17397. break;
  17398. case Engine.TEXTUREFORMAT_RGB:
  17399. internalFormat = this._gl.RGB;
  17400. break;
  17401. case Engine.TEXTUREFORMAT_RGBA:
  17402. internalFormat = this._gl.RGBA;
  17403. break;
  17404. }
  17405. if (this._webGLVersion > 1) {
  17406. switch (format) {
  17407. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17408. internalFormat = this._gl.RED_INTEGER;
  17409. break;
  17410. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17411. internalFormat = this._gl.RG_INTEGER;
  17412. break;
  17413. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17414. internalFormat = this._gl.RGB_INTEGER;
  17415. break;
  17416. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17417. internalFormat = this._gl.RGBA_INTEGER;
  17418. break;
  17419. }
  17420. }
  17421. return internalFormat;
  17422. };
  17423. /** @hidden */
  17424. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17425. if (this._webGLVersion === 1) {
  17426. if (format !== undefined) {
  17427. switch (format) {
  17428. case Engine.TEXTUREFORMAT_ALPHA:
  17429. return this._gl.ALPHA;
  17430. case Engine.TEXTUREFORMAT_LUMINANCE:
  17431. return this._gl.LUMINANCE;
  17432. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17433. return this._gl.LUMINANCE_ALPHA;
  17434. }
  17435. }
  17436. return this._gl.RGBA;
  17437. }
  17438. switch (type) {
  17439. case Engine.TEXTURETYPE_BYTE:
  17440. switch (format) {
  17441. case Engine.TEXTUREFORMAT_RED:
  17442. return this._gl.R8_SNORM;
  17443. case Engine.TEXTUREFORMAT_RG:
  17444. return this._gl.RG8_SNORM;
  17445. case Engine.TEXTUREFORMAT_RGB:
  17446. return this._gl.RGB8_SNORM;
  17447. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17448. return this._gl.R8I;
  17449. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17450. return this._gl.RG8I;
  17451. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17452. return this._gl.RGB8I;
  17453. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17454. return this._gl.RGBA8I;
  17455. default:
  17456. return this._gl.RGBA8_SNORM;
  17457. }
  17458. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17459. switch (format) {
  17460. case Engine.TEXTUREFORMAT_RED:
  17461. return this._gl.R8;
  17462. case Engine.TEXTUREFORMAT_RG:
  17463. return this._gl.RG8;
  17464. case Engine.TEXTUREFORMAT_RGB:
  17465. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17466. case Engine.TEXTUREFORMAT_RGBA:
  17467. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17468. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17469. return this._gl.R8UI;
  17470. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17471. return this._gl.RG8UI;
  17472. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17473. return this._gl.RGB8UI;
  17474. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17475. return this._gl.RGBA8UI;
  17476. default:
  17477. return this._gl.RGBA8;
  17478. }
  17479. case Engine.TEXTURETYPE_SHORT:
  17480. switch (format) {
  17481. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17482. return this._gl.R16I;
  17483. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17484. return this._gl.RG16I;
  17485. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17486. return this._gl.RGB16I;
  17487. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17488. return this._gl.RGBA16I;
  17489. default:
  17490. return this._gl.RGBA16I;
  17491. }
  17492. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17493. switch (format) {
  17494. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17495. return this._gl.R16UI;
  17496. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17497. return this._gl.RG16UI;
  17498. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17499. return this._gl.RGB16UI;
  17500. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17501. return this._gl.RGBA16UI;
  17502. default:
  17503. return this._gl.RGBA16UI;
  17504. }
  17505. case Engine.TEXTURETYPE_INT:
  17506. switch (format) {
  17507. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17508. return this._gl.R32I;
  17509. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17510. return this._gl.RG32I;
  17511. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17512. return this._gl.RGB32I;
  17513. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17514. return this._gl.RGBA32I;
  17515. default:
  17516. return this._gl.RGBA32I;
  17517. }
  17518. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17519. switch (format) {
  17520. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17521. return this._gl.R32UI;
  17522. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17523. return this._gl.RG32UI;
  17524. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17525. return this._gl.RGB32UI;
  17526. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17527. return this._gl.RGBA32UI;
  17528. default:
  17529. return this._gl.RGBA32UI;
  17530. }
  17531. case Engine.TEXTURETYPE_FLOAT:
  17532. switch (format) {
  17533. case Engine.TEXTUREFORMAT_RED:
  17534. return this._gl.R32F; // By default. Other possibility is R16F.
  17535. case Engine.TEXTUREFORMAT_RG:
  17536. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17537. case Engine.TEXTUREFORMAT_RGB:
  17538. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17539. case Engine.TEXTUREFORMAT_RGBA:
  17540. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17541. default:
  17542. return this._gl.RGBA32F;
  17543. }
  17544. case Engine.TEXTURETYPE_HALF_FLOAT:
  17545. switch (format) {
  17546. case Engine.TEXTUREFORMAT_RED:
  17547. return this._gl.R16F;
  17548. case Engine.TEXTUREFORMAT_RG:
  17549. return this._gl.RG16F;
  17550. case Engine.TEXTUREFORMAT_RGB:
  17551. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17552. case Engine.TEXTUREFORMAT_RGBA:
  17553. return this._gl.RGBA16F;
  17554. default:
  17555. return this._gl.RGBA16F;
  17556. }
  17557. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17558. return this._gl.RGB565;
  17559. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17560. return this._gl.R11F_G11F_B10F;
  17561. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17562. return this._gl.RGB9_E5;
  17563. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17564. return this._gl.RGBA4;
  17565. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17566. return this._gl.RGB5_A1;
  17567. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17568. switch (format) {
  17569. case Engine.TEXTUREFORMAT_RGBA:
  17570. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17571. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17572. return this._gl.RGB10_A2UI;
  17573. default:
  17574. return this._gl.RGB10_A2;
  17575. }
  17576. }
  17577. return this._gl.RGBA8;
  17578. };
  17579. ;
  17580. /** @hidden */
  17581. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17582. if (type === Engine.TEXTURETYPE_FLOAT) {
  17583. return this._gl.RGBA32F;
  17584. }
  17585. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17586. return this._gl.RGBA16F;
  17587. }
  17588. return this._gl.RGBA8;
  17589. };
  17590. ;
  17591. /** @hidden */
  17592. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17593. var _this = this;
  17594. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17595. this._activeRequests.push(request);
  17596. request.onCompleteObservable.add(function (request) {
  17597. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17598. });
  17599. return request;
  17600. };
  17601. /** @hidden */
  17602. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17603. var _this = this;
  17604. return new Promise(function (resolve, reject) {
  17605. _this._loadFile(url, function (data) {
  17606. resolve(data);
  17607. }, undefined, database, useArrayBuffer, function (request, exception) {
  17608. reject(exception);
  17609. });
  17610. });
  17611. };
  17612. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17613. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17614. var onload = function (data) {
  17615. loadedFiles[index] = data;
  17616. loadedFiles._internalCount++;
  17617. if (loadedFiles._internalCount === 6) {
  17618. onfinish(loadedFiles);
  17619. }
  17620. };
  17621. var onerror = function (request, exception) {
  17622. if (onErrorCallBack && request) {
  17623. onErrorCallBack(request.status + " " + request.statusText, exception);
  17624. }
  17625. };
  17626. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17627. };
  17628. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17629. if (onError === void 0) { onError = null; }
  17630. var loadedFiles = [];
  17631. loadedFiles._internalCount = 0;
  17632. for (var index = 0; index < 6; index++) {
  17633. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17634. }
  17635. };
  17636. // Statics
  17637. /**
  17638. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17639. * @returns true if the engine can be created
  17640. * @ignorenaming
  17641. */
  17642. Engine.isSupported = function () {
  17643. try {
  17644. var tempcanvas = document.createElement("canvas");
  17645. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17646. return gl != null && !!window.WebGLRenderingContext;
  17647. }
  17648. catch (e) {
  17649. return false;
  17650. }
  17651. };
  17652. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17653. Engine.ExceptionList = [
  17654. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17655. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17656. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17657. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17658. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17659. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17660. ];
  17661. /** Gets the list of created engines */
  17662. Engine.Instances = new Array();
  17663. /**
  17664. * Hidden
  17665. */
  17666. Engine._TextureLoaders = [];
  17667. // Const statics
  17668. /** Defines that alpha blending is disabled */
  17669. Engine.ALPHA_DISABLE = 0;
  17670. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17671. Engine.ALPHA_ADD = 1;
  17672. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17673. Engine.ALPHA_COMBINE = 2;
  17674. /** Defines that alpha blending to DEST - SRC * DEST */
  17675. Engine.ALPHA_SUBTRACT = 3;
  17676. /** Defines that alpha blending to SRC * DEST */
  17677. Engine.ALPHA_MULTIPLY = 4;
  17678. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17679. Engine.ALPHA_MAXIMIZED = 5;
  17680. /** Defines that alpha blending to SRC + DEST */
  17681. Engine.ALPHA_ONEONE = 6;
  17682. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17683. Engine.ALPHA_PREMULTIPLIED = 7;
  17684. /**
  17685. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17686. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17687. */
  17688. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17689. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17690. Engine.ALPHA_INTERPOLATE = 9;
  17691. /**
  17692. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17693. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17694. */
  17695. Engine.ALPHA_SCREENMODE = 10;
  17696. /** Defines that the ressource is not delayed*/
  17697. Engine.DELAYLOADSTATE_NONE = 0;
  17698. /** Defines that the ressource was successfully delay loaded */
  17699. Engine.DELAYLOADSTATE_LOADED = 1;
  17700. /** Defines that the ressource is currently delay loading */
  17701. Engine.DELAYLOADSTATE_LOADING = 2;
  17702. /** Defines that the ressource is delayed and has not started loading */
  17703. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17704. // Depht or Stencil test Constants.
  17705. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17706. Engine.NEVER = 0x0200;
  17707. /** 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 */
  17708. Engine.ALWAYS = 0x0207;
  17709. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17710. Engine.LESS = 0x0201;
  17711. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17712. Engine.EQUAL = 0x0202;
  17713. /** 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 */
  17714. Engine.LEQUAL = 0x0203;
  17715. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17716. Engine.GREATER = 0x0204;
  17717. /** 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 */
  17718. Engine.GEQUAL = 0x0206;
  17719. /** 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 */
  17720. Engine.NOTEQUAL = 0x0205;
  17721. // Stencil Actions Constants.
  17722. /** Passed to stencilOperation to specify that stencil value must be kept */
  17723. Engine.KEEP = 0x1E00;
  17724. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17725. Engine.REPLACE = 0x1E01;
  17726. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17727. Engine.INCR = 0x1E02;
  17728. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17729. Engine.DECR = 0x1E03;
  17730. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17731. Engine.INVERT = 0x150A;
  17732. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17733. Engine.INCR_WRAP = 0x8507;
  17734. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17735. Engine.DECR_WRAP = 0x8508;
  17736. /** Texture is not repeating outside of 0..1 UVs */
  17737. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17738. /** Texture is repeating outside of 0..1 UVs */
  17739. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17740. /** Texture is repeating and mirrored */
  17741. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17742. /** ALPHA */
  17743. Engine.TEXTUREFORMAT_ALPHA = 0;
  17744. /** LUMINANCE */
  17745. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17746. /** LUMINANCE_ALPHA */
  17747. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17748. /** RGB */
  17749. Engine.TEXTUREFORMAT_RGB = 4;
  17750. /** RGBA */
  17751. Engine.TEXTUREFORMAT_RGBA = 5;
  17752. /** RED */
  17753. Engine.TEXTUREFORMAT_RED = 6;
  17754. /** RED (2nd reference) */
  17755. Engine.TEXTUREFORMAT_R = 6;
  17756. /** RG */
  17757. Engine.TEXTUREFORMAT_RG = 7;
  17758. /** RED_INTEGER */
  17759. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17760. /** RED_INTEGER (2nd reference) */
  17761. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17762. /** RG_INTEGER */
  17763. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17764. /** RGB_INTEGER */
  17765. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17766. /** RGBA_INTEGER */
  17767. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17768. /** UNSIGNED_BYTE */
  17769. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17770. /** UNSIGNED_BYTE (2nd reference) */
  17771. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17772. /** FLOAT */
  17773. Engine.TEXTURETYPE_FLOAT = 1;
  17774. /** HALF_FLOAT */
  17775. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17776. /** BYTE */
  17777. Engine.TEXTURETYPE_BYTE = 3;
  17778. /** SHORT */
  17779. Engine.TEXTURETYPE_SHORT = 4;
  17780. /** UNSIGNED_SHORT */
  17781. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17782. /** INT */
  17783. Engine.TEXTURETYPE_INT = 6;
  17784. /** UNSIGNED_INT */
  17785. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17786. /** UNSIGNED_SHORT_4_4_4_4 */
  17787. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17788. /** UNSIGNED_SHORT_5_5_5_1 */
  17789. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17790. /** UNSIGNED_SHORT_5_6_5 */
  17791. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17792. /** UNSIGNED_INT_2_10_10_10_REV */
  17793. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17794. /** UNSIGNED_INT_24_8 */
  17795. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17796. /** UNSIGNED_INT_10F_11F_11F_REV */
  17797. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17798. /** UNSIGNED_INT_5_9_9_9_REV */
  17799. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17800. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17801. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17802. /** nearest is mag = nearest and min = nearest and mip = linear */
  17803. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17804. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17805. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17806. /** Trilinear is mag = linear and min = linear and mip = linear */
  17807. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17808. /** nearest is mag = nearest and min = nearest and mip = linear */
  17809. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17810. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17811. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17812. /** Trilinear is mag = linear and min = linear and mip = linear */
  17813. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17814. /** mag = nearest and min = nearest and mip = nearest */
  17815. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17816. /** mag = nearest and min = linear and mip = nearest */
  17817. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17818. /** mag = nearest and min = linear and mip = linear */
  17819. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17820. /** mag = nearest and min = linear and mip = none */
  17821. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17822. /** mag = nearest and min = nearest and mip = none */
  17823. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17824. /** mag = linear and min = nearest and mip = nearest */
  17825. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17826. /** mag = linear and min = nearest and mip = linear */
  17827. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17828. /** mag = linear and min = linear and mip = none */
  17829. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17830. /** mag = linear and min = nearest and mip = none */
  17831. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17832. /** Explicit coordinates mode */
  17833. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17834. /** Spherical coordinates mode */
  17835. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17836. /** Planar coordinates mode */
  17837. Engine.TEXTURE_PLANAR_MODE = 2;
  17838. /** Cubic coordinates mode */
  17839. Engine.TEXTURE_CUBIC_MODE = 3;
  17840. /** Projection coordinates mode */
  17841. Engine.TEXTURE_PROJECTION_MODE = 4;
  17842. /** Skybox coordinates mode */
  17843. Engine.TEXTURE_SKYBOX_MODE = 5;
  17844. /** Inverse Cubic coordinates mode */
  17845. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17846. /** Equirectangular coordinates mode */
  17847. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17848. /** Equirectangular Fixed coordinates mode */
  17849. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17850. /** Equirectangular Fixed Mirrored coordinates mode */
  17851. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17852. // Texture rescaling mode
  17853. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17854. Engine.SCALEMODE_FLOOR = 1;
  17855. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17856. Engine.SCALEMODE_NEAREST = 2;
  17857. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17858. Engine.SCALEMODE_CEILING = 3;
  17859. // Updatable statics so stick with vars here
  17860. /**
  17861. * Gets or sets the epsilon value used by collision engine
  17862. */
  17863. Engine.CollisionsEpsilon = 0.001;
  17864. /**
  17865. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17866. */
  17867. Engine.CodeRepository = "src/";
  17868. /**
  17869. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17870. */
  17871. Engine.ShadersRepository = "src/Shaders/";
  17872. return Engine;
  17873. }());
  17874. BABYLON.Engine = Engine;
  17875. })(BABYLON || (BABYLON = {}));
  17876. //# sourceMappingURL=babylon.engine.js.map
  17877. var BABYLON;
  17878. (function (BABYLON) {
  17879. /**
  17880. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17881. */
  17882. var Node = /** @class */ (function () {
  17883. /**
  17884. * Creates a new Node
  17885. * @param {string} name - the name and id to be given to this node
  17886. * @param {BABYLON.Scene} the scene this node will be added to
  17887. */
  17888. function Node(name, scene) {
  17889. if (scene === void 0) { scene = null; }
  17890. /**
  17891. * Gets or sets a string used to store user defined state for the node
  17892. */
  17893. this.state = "";
  17894. /**
  17895. * Gets or sets an object used to store user defined information for the node
  17896. */
  17897. this.metadata = null;
  17898. /**
  17899. * Gets or sets a boolean used to define if the node must be serialized
  17900. */
  17901. this.doNotSerialize = false;
  17902. /** @hidden */
  17903. this._isDisposed = false;
  17904. /**
  17905. * Gets a list of Animations associated with the node
  17906. */
  17907. this.animations = new Array();
  17908. this._ranges = {};
  17909. this._isEnabled = true;
  17910. this._isParentEnabled = true;
  17911. this._isReady = true;
  17912. /** @hidden */
  17913. this._currentRenderId = -1;
  17914. this._parentRenderId = -1;
  17915. this._childRenderId = -1;
  17916. /** @hidden */
  17917. this._worldMatrix = BABYLON.Matrix.Identity();
  17918. /** @hidden */
  17919. this._worldMatrixDeterminant = 0;
  17920. this._animationPropertiesOverride = null;
  17921. /**
  17922. * An event triggered when the mesh is disposed
  17923. */
  17924. this.onDisposeObservable = new BABYLON.Observable();
  17925. // Behaviors
  17926. this._behaviors = new Array();
  17927. this.name = name;
  17928. this.id = name;
  17929. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17930. this.uniqueId = this._scene.getUniqueId();
  17931. this._initCache();
  17932. this._scene.rootNodes.push(this);
  17933. }
  17934. /**
  17935. * Add a new node constructor
  17936. * @param type defines the type name of the node to construct
  17937. * @param constructorFunc defines the constructor function
  17938. */
  17939. Node.AddNodeConstructor = function (type, constructorFunc) {
  17940. this._NodeConstructors[type] = constructorFunc;
  17941. };
  17942. /**
  17943. * Returns a node constructor based on type name
  17944. * @param type defines the type name
  17945. * @param name defines the new node name
  17946. * @param scene defines the hosting scene
  17947. * @param options defines optional options to transmit to constructors
  17948. * @returns the new constructor or null
  17949. */
  17950. Node.Construct = function (type, name, scene, options) {
  17951. var constructorFunc = this._NodeConstructors[type];
  17952. if (!constructorFunc) {
  17953. return null;
  17954. }
  17955. return constructorFunc(name, scene, options);
  17956. };
  17957. /**
  17958. * Gets a boolean indicating if the node has been disposed
  17959. * @returns true if the node was disposed
  17960. */
  17961. Node.prototype.isDisposed = function () {
  17962. return this._isDisposed;
  17963. };
  17964. Object.defineProperty(Node.prototype, "parent", {
  17965. get: function () {
  17966. return this._parentNode;
  17967. },
  17968. /**
  17969. * Gets or sets the parent of the node
  17970. */
  17971. set: function (parent) {
  17972. if (this._parentNode === parent) {
  17973. return;
  17974. }
  17975. var previousParentNode = this._parentNode;
  17976. // Remove self from list of children of parent
  17977. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17978. var index = this._parentNode._children.indexOf(this);
  17979. if (index !== -1) {
  17980. this._parentNode._children.splice(index, 1);
  17981. }
  17982. if (!parent) {
  17983. // Need to add this node to the rootNodes
  17984. this._scene.rootNodes.push(this);
  17985. }
  17986. }
  17987. // Store new parent
  17988. this._parentNode = parent;
  17989. // Add as child to new parent
  17990. if (this._parentNode) {
  17991. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17992. this._parentNode._children = new Array();
  17993. }
  17994. this._parentNode._children.push(this);
  17995. if (!previousParentNode) {
  17996. // Need to remove from rootNodes
  17997. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17998. if (rootNodeIndex > -1) {
  17999. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18000. }
  18001. }
  18002. }
  18003. // Enabled state
  18004. this._syncParentEnabledState();
  18005. },
  18006. enumerable: true,
  18007. configurable: true
  18008. });
  18009. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18010. /**
  18011. * Gets or sets the animation properties override
  18012. */
  18013. get: function () {
  18014. if (!this._animationPropertiesOverride) {
  18015. return this._scene.animationPropertiesOverride;
  18016. }
  18017. return this._animationPropertiesOverride;
  18018. },
  18019. set: function (value) {
  18020. this._animationPropertiesOverride = value;
  18021. },
  18022. enumerable: true,
  18023. configurable: true
  18024. });
  18025. /**
  18026. * Gets a string idenfifying the name of the class
  18027. * @returns "Node" string
  18028. */
  18029. Node.prototype.getClassName = function () {
  18030. return "Node";
  18031. };
  18032. Object.defineProperty(Node.prototype, "onDispose", {
  18033. /**
  18034. * Sets a callback that will be raised when the node will be disposed
  18035. */
  18036. set: function (callback) {
  18037. if (this._onDisposeObserver) {
  18038. this.onDisposeObservable.remove(this._onDisposeObserver);
  18039. }
  18040. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18041. },
  18042. enumerable: true,
  18043. configurable: true
  18044. });
  18045. /**
  18046. * Gets the scene of the node
  18047. * @returns a {BABYLON.Scene}
  18048. */
  18049. Node.prototype.getScene = function () {
  18050. return this._scene;
  18051. };
  18052. /**
  18053. * Gets the engine of the node
  18054. * @returns a {BABYLON.Engine}
  18055. */
  18056. Node.prototype.getEngine = function () {
  18057. return this._scene.getEngine();
  18058. };
  18059. /**
  18060. * Attach a behavior to the node
  18061. * @see http://doc.babylonjs.com/features/behaviour
  18062. * @param behavior defines the behavior to attach
  18063. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18064. * @returns the current Node
  18065. */
  18066. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18067. var _this = this;
  18068. if (attachImmediately === void 0) { attachImmediately = false; }
  18069. var index = this._behaviors.indexOf(behavior);
  18070. if (index !== -1) {
  18071. return this;
  18072. }
  18073. behavior.init();
  18074. if (this._scene.isLoading && !attachImmediately) {
  18075. // We defer the attach when the scene will be loaded
  18076. this._scene.onDataLoadedObservable.addOnce(function () {
  18077. behavior.attach(_this);
  18078. });
  18079. }
  18080. else {
  18081. behavior.attach(this);
  18082. }
  18083. this._behaviors.push(behavior);
  18084. return this;
  18085. };
  18086. /**
  18087. * Remove an attached behavior
  18088. * @see http://doc.babylonjs.com/features/behaviour
  18089. * @param behavior defines the behavior to attach
  18090. * @returns the current Node
  18091. */
  18092. Node.prototype.removeBehavior = function (behavior) {
  18093. var index = this._behaviors.indexOf(behavior);
  18094. if (index === -1) {
  18095. return this;
  18096. }
  18097. this._behaviors[index].detach();
  18098. this._behaviors.splice(index, 1);
  18099. return this;
  18100. };
  18101. Object.defineProperty(Node.prototype, "behaviors", {
  18102. /**
  18103. * Gets the list of attached behaviors
  18104. * @see http://doc.babylonjs.com/features/behaviour
  18105. */
  18106. get: function () {
  18107. return this._behaviors;
  18108. },
  18109. enumerable: true,
  18110. configurable: true
  18111. });
  18112. /**
  18113. * Gets an attached behavior by name
  18114. * @param name defines the name of the behavior to look for
  18115. * @see http://doc.babylonjs.com/features/behaviour
  18116. * @returns null if behavior was not found else the requested behavior
  18117. */
  18118. Node.prototype.getBehaviorByName = function (name) {
  18119. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18120. var behavior = _a[_i];
  18121. if (behavior.name === name) {
  18122. return behavior;
  18123. }
  18124. }
  18125. return null;
  18126. };
  18127. /**
  18128. * Returns the latest update of the World matrix
  18129. * @returns a Matrix
  18130. */
  18131. Node.prototype.getWorldMatrix = function () {
  18132. if (this._currentRenderId !== this._scene.getRenderId()) {
  18133. this.computeWorldMatrix();
  18134. }
  18135. return this._worldMatrix;
  18136. };
  18137. /** @hidden */
  18138. Node.prototype._getWorldMatrixDeterminant = function () {
  18139. return this._worldMatrixDeterminant;
  18140. };
  18141. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18142. /**
  18143. * Returns directly the latest state of the mesh World matrix.
  18144. * A Matrix is returned.
  18145. */
  18146. get: function () {
  18147. return this._worldMatrix;
  18148. },
  18149. enumerable: true,
  18150. configurable: true
  18151. });
  18152. // override it in derived class if you add new variables to the cache
  18153. // and call the parent class method
  18154. /** @hidden */
  18155. Node.prototype._initCache = function () {
  18156. this._cache = {};
  18157. this._cache.parent = undefined;
  18158. };
  18159. /** @hidden */
  18160. Node.prototype.updateCache = function (force) {
  18161. if (!force && this.isSynchronized())
  18162. return;
  18163. this._cache.parent = this.parent;
  18164. this._updateCache();
  18165. };
  18166. // override it in derived class if you add new variables to the cache
  18167. // and call the parent class method if !ignoreParentClass
  18168. /** @hidden */
  18169. Node.prototype._updateCache = function (ignoreParentClass) {
  18170. };
  18171. // override it in derived class if you add new variables to the cache
  18172. /** @hidden */
  18173. Node.prototype._isSynchronized = function () {
  18174. return true;
  18175. };
  18176. /** @hidden */
  18177. Node.prototype._markSyncedWithParent = function () {
  18178. if (this._parentNode) {
  18179. this._parentRenderId = this._parentNode._childRenderId;
  18180. }
  18181. };
  18182. /** @hidden */
  18183. Node.prototype.isSynchronizedWithParent = function () {
  18184. if (!this._parentNode) {
  18185. return true;
  18186. }
  18187. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18188. return false;
  18189. }
  18190. return this._parentNode.isSynchronized();
  18191. };
  18192. /** @hidden */
  18193. Node.prototype.isSynchronized = function () {
  18194. if (this._cache.parent != this._parentNode) {
  18195. this._cache.parent = this._parentNode;
  18196. return false;
  18197. }
  18198. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18199. return false;
  18200. }
  18201. return this._isSynchronized();
  18202. };
  18203. /**
  18204. * Is this node ready to be used/rendered
  18205. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18206. * @return true if the node is ready
  18207. */
  18208. Node.prototype.isReady = function (completeCheck) {
  18209. if (completeCheck === void 0) { completeCheck = false; }
  18210. return this._isReady;
  18211. };
  18212. /**
  18213. * Is this node enabled?
  18214. * 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
  18215. * @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
  18216. * @return whether this node (and its parent) is enabled
  18217. */
  18218. Node.prototype.isEnabled = function (checkAncestors) {
  18219. if (checkAncestors === void 0) { checkAncestors = true; }
  18220. if (checkAncestors === false) {
  18221. return this._isEnabled;
  18222. }
  18223. if (!this._isEnabled) {
  18224. return false;
  18225. }
  18226. return this._isParentEnabled;
  18227. };
  18228. /** @hidden */
  18229. Node.prototype._syncParentEnabledState = function () {
  18230. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18231. if (this._children) {
  18232. this._children.forEach(function (c) {
  18233. c._syncParentEnabledState(); // Force children to update accordingly
  18234. });
  18235. }
  18236. };
  18237. /**
  18238. * Set the enabled state of this node
  18239. * @param value defines the new enabled state
  18240. */
  18241. Node.prototype.setEnabled = function (value) {
  18242. this._isEnabled = value;
  18243. this._syncParentEnabledState();
  18244. };
  18245. /**
  18246. * Is this node a descendant of the given node?
  18247. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18248. * @param ancestor defines the parent node to inspect
  18249. * @returns a boolean indicating if this node is a descendant of the given node
  18250. */
  18251. Node.prototype.isDescendantOf = function (ancestor) {
  18252. if (this.parent) {
  18253. if (this.parent === ancestor) {
  18254. return true;
  18255. }
  18256. return this.parent.isDescendantOf(ancestor);
  18257. }
  18258. return false;
  18259. };
  18260. /** @hidden */
  18261. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18262. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18263. if (!this._children) {
  18264. return;
  18265. }
  18266. for (var index = 0; index < this._children.length; index++) {
  18267. var item = this._children[index];
  18268. if (!predicate || predicate(item)) {
  18269. results.push(item);
  18270. }
  18271. if (!directDescendantsOnly) {
  18272. item._getDescendants(results, false, predicate);
  18273. }
  18274. }
  18275. };
  18276. /**
  18277. * Will return all nodes that have this node as ascendant
  18278. * @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
  18279. * @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
  18280. * @return all children nodes of all types
  18281. */
  18282. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18283. var results = new Array();
  18284. this._getDescendants(results, directDescendantsOnly, predicate);
  18285. return results;
  18286. };
  18287. /**
  18288. * Get all child-meshes of this node
  18289. * @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
  18290. * @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
  18291. * @returns an array of {BABYLON.AbstractMesh}
  18292. */
  18293. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18294. var results = [];
  18295. this._getDescendants(results, directDescendantsOnly, function (node) {
  18296. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18297. });
  18298. return results;
  18299. };
  18300. /**
  18301. * Get all child-transformNodes of this node
  18302. * @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
  18303. * @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
  18304. * @returns an array of {BABYLON.TransformNode}
  18305. */
  18306. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18307. var results = [];
  18308. this._getDescendants(results, directDescendantsOnly, function (node) {
  18309. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18310. });
  18311. return results;
  18312. };
  18313. /**
  18314. * Get all direct children of this node
  18315. * @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
  18316. * @returns an array of {BABYLON.Node}
  18317. */
  18318. Node.prototype.getChildren = function (predicate) {
  18319. return this.getDescendants(true, predicate);
  18320. };
  18321. /** @hidden */
  18322. Node.prototype._setReady = function (state) {
  18323. if (state === this._isReady) {
  18324. return;
  18325. }
  18326. if (!state) {
  18327. this._isReady = false;
  18328. return;
  18329. }
  18330. if (this.onReady) {
  18331. this.onReady(this);
  18332. }
  18333. this._isReady = true;
  18334. };
  18335. /**
  18336. * Get an animation by name
  18337. * @param name defines the name of the animation to look for
  18338. * @returns null if not found else the requested animation
  18339. */
  18340. Node.prototype.getAnimationByName = function (name) {
  18341. for (var i = 0; i < this.animations.length; i++) {
  18342. var animation = this.animations[i];
  18343. if (animation.name === name) {
  18344. return animation;
  18345. }
  18346. }
  18347. return null;
  18348. };
  18349. /**
  18350. * Creates an animation range for this node
  18351. * @param name defines the name of the range
  18352. * @param from defines the starting key
  18353. * @param to defines the end key
  18354. */
  18355. Node.prototype.createAnimationRange = function (name, from, to) {
  18356. // check name not already in use
  18357. if (!this._ranges[name]) {
  18358. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18359. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18360. if (this.animations[i]) {
  18361. this.animations[i].createRange(name, from, to);
  18362. }
  18363. }
  18364. }
  18365. };
  18366. /**
  18367. * Delete a specific animation range
  18368. * @param name defines the name of the range to delete
  18369. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18370. */
  18371. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18372. if (deleteFrames === void 0) { deleteFrames = true; }
  18373. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18374. if (this.animations[i]) {
  18375. this.animations[i].deleteRange(name, deleteFrames);
  18376. }
  18377. }
  18378. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18379. };
  18380. /**
  18381. * Get an animation range by name
  18382. * @param name defines the name of the animation range to look for
  18383. * @returns null if not found else the requested animation range
  18384. */
  18385. Node.prototype.getAnimationRange = function (name) {
  18386. return this._ranges[name];
  18387. };
  18388. /**
  18389. * Will start the animation sequence
  18390. * @param name defines the range frames for animation sequence
  18391. * @param loop defines if the animation should loop (false by default)
  18392. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18393. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18394. * @returns the object created for this animation. If range does not exist, it will return null
  18395. */
  18396. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18397. var range = this.getAnimationRange(name);
  18398. if (!range) {
  18399. return null;
  18400. }
  18401. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18402. };
  18403. /**
  18404. * Serialize animation ranges into a JSON compatible object
  18405. * @returns serialization object
  18406. */
  18407. Node.prototype.serializeAnimationRanges = function () {
  18408. var serializationRanges = [];
  18409. for (var name in this._ranges) {
  18410. var localRange = this._ranges[name];
  18411. if (!localRange) {
  18412. continue;
  18413. }
  18414. var range = {};
  18415. range.name = name;
  18416. range.from = localRange.from;
  18417. range.to = localRange.to;
  18418. serializationRanges.push(range);
  18419. }
  18420. return serializationRanges;
  18421. };
  18422. /**
  18423. * Computes the world matrix of the node
  18424. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18425. * @returns the world matrix
  18426. */
  18427. Node.prototype.computeWorldMatrix = function (force) {
  18428. if (!this._worldMatrix) {
  18429. this._worldMatrix = BABYLON.Matrix.Identity();
  18430. }
  18431. return this._worldMatrix;
  18432. };
  18433. /**
  18434. * Releases resources associated with this node.
  18435. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18436. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18437. */
  18438. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18439. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18440. if (!doNotRecurse) {
  18441. var nodes = this.getDescendants(true);
  18442. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18443. var node = nodes_1[_i];
  18444. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18445. }
  18446. }
  18447. else {
  18448. var transformNodes = this.getChildTransformNodes(true);
  18449. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18450. var transformNode = transformNodes_1[_a];
  18451. transformNode.parent = null;
  18452. transformNode.computeWorldMatrix(true);
  18453. }
  18454. }
  18455. if (!this.parent) {
  18456. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18457. if (rootNodeIndex > -1) {
  18458. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18459. }
  18460. }
  18461. else {
  18462. this.parent = null;
  18463. }
  18464. // Callback
  18465. this.onDisposeObservable.notifyObservers(this);
  18466. this.onDisposeObservable.clear();
  18467. // Behaviors
  18468. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18469. var behavior = _c[_b];
  18470. behavior.detach();
  18471. }
  18472. this._behaviors = [];
  18473. this._isDisposed = true;
  18474. };
  18475. /**
  18476. * Parse animation range data from a serialization object and store them into a given node
  18477. * @param node defines where to store the animation ranges
  18478. * @param parsedNode defines the serialization object to read data from
  18479. * @param scene defines the hosting scene
  18480. */
  18481. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18482. if (parsedNode.ranges) {
  18483. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18484. var data = parsedNode.ranges[index];
  18485. node.createAnimationRange(data.name, data.from, data.to);
  18486. }
  18487. }
  18488. };
  18489. Node._NodeConstructors = {};
  18490. __decorate([
  18491. BABYLON.serialize()
  18492. ], Node.prototype, "name", void 0);
  18493. __decorate([
  18494. BABYLON.serialize()
  18495. ], Node.prototype, "id", void 0);
  18496. __decorate([
  18497. BABYLON.serialize()
  18498. ], Node.prototype, "uniqueId", void 0);
  18499. __decorate([
  18500. BABYLON.serialize()
  18501. ], Node.prototype, "state", void 0);
  18502. __decorate([
  18503. BABYLON.serialize()
  18504. ], Node.prototype, "metadata", void 0);
  18505. return Node;
  18506. }());
  18507. BABYLON.Node = Node;
  18508. })(BABYLON || (BABYLON = {}));
  18509. //# sourceMappingURL=babylon.node.js.map
  18510. var BABYLON;
  18511. (function (BABYLON) {
  18512. // This matrix is used as a value to reset the bounding box.
  18513. var _identityMatrix = BABYLON.Matrix.Identity();
  18514. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18515. /**
  18516. * Class used to store bounding sphere information
  18517. */
  18518. var BoundingSphere = /** @class */ (function () {
  18519. /**
  18520. * Creates a new bounding sphere
  18521. * @param min defines the minimum vector (in local space)
  18522. * @param max defines the maximum vector (in local space)
  18523. */
  18524. function BoundingSphere(min, max) {
  18525. this.center = BABYLON.Vector3.Zero();
  18526. this.centerWorld = BABYLON.Vector3.Zero();
  18527. this.reConstruct(min, max);
  18528. }
  18529. /**
  18530. * Recreates the entire bounding sphere from scratch
  18531. * @param min defines the new minimum vector (in local space)
  18532. * @param max defines the new maximum vector (in local space)
  18533. */
  18534. BoundingSphere.prototype.reConstruct = function (min, max) {
  18535. this.minimum = min.clone();
  18536. this.maximum = max.clone();
  18537. var distance = BABYLON.Vector3.Distance(min, max);
  18538. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18539. this.radius = distance * 0.5;
  18540. this.centerWorld.set(0, 0, 0);
  18541. this._update(_identityMatrix);
  18542. };
  18543. /**
  18544. * Scale the current bounding sphere by applying a scale factor
  18545. * @param factor defines the scale factor to apply
  18546. * @returns the current bounding box
  18547. */
  18548. BoundingSphere.prototype.scale = function (factor) {
  18549. var newRadius = this.radius * factor;
  18550. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18551. var min = this.center.subtract(_tempRadiusVector);
  18552. var max = this.center.add(_tempRadiusVector);
  18553. this.reConstruct(min, max);
  18554. return this;
  18555. };
  18556. // Methods
  18557. /** @hidden */
  18558. BoundingSphere.prototype._update = function (world) {
  18559. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18560. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18561. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18562. };
  18563. /**
  18564. * Tests if the bounding sphere is intersecting the frustum planes
  18565. * @param frustumPlanes defines the frustum planes to test
  18566. * @returns true if there is an intersection
  18567. */
  18568. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18569. for (var i = 0; i < 6; i++) {
  18570. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18571. return false;
  18572. }
  18573. return true;
  18574. };
  18575. /**
  18576. * Tests if a point is inside the bounding sphere
  18577. * @param point defines the point to test
  18578. * @returns true if the point is inside the bounding sphere
  18579. */
  18580. BoundingSphere.prototype.intersectsPoint = function (point) {
  18581. var x = this.centerWorld.x - point.x;
  18582. var y = this.centerWorld.y - point.y;
  18583. var z = this.centerWorld.z - point.z;
  18584. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18585. if (this.radiusWorld < distance)
  18586. return false;
  18587. return true;
  18588. };
  18589. // Statics
  18590. /**
  18591. * Checks if two sphere intersct
  18592. * @param sphere0 sphere 0
  18593. * @param sphere1 sphere 1
  18594. * @returns true if the speres intersect
  18595. */
  18596. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18597. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18598. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18599. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18600. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18601. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18602. return false;
  18603. return true;
  18604. };
  18605. return BoundingSphere;
  18606. }());
  18607. BABYLON.BoundingSphere = BoundingSphere;
  18608. })(BABYLON || (BABYLON = {}));
  18609. //# sourceMappingURL=babylon.boundingSphere.js.map
  18610. var BABYLON;
  18611. (function (BABYLON) {
  18612. /**
  18613. * Class used to store bounding box information
  18614. */
  18615. var BoundingBox = /** @class */ (function () {
  18616. /**
  18617. * Creates a new bounding box
  18618. * @param min defines the minimum vector (in local space)
  18619. * @param max defines the maximum vector (in local space)
  18620. */
  18621. function BoundingBox(min, max) {
  18622. /**
  18623. * Gets the 8 vectors representing the bounding box in world space
  18624. */
  18625. this.vectorsWorld = new Array();
  18626. this.reConstruct(min, max);
  18627. }
  18628. // Methods
  18629. /**
  18630. * Recreates the entire bounding box from scratch
  18631. * @param min defines the new minimum vector (in local space)
  18632. * @param max defines the new maximum vector (in local space)
  18633. */
  18634. BoundingBox.prototype.reConstruct = function (min, max) {
  18635. this.minimum = min.clone();
  18636. this.maximum = max.clone();
  18637. // Bounding vectors
  18638. this.vectors = [
  18639. this.minimum.clone(),
  18640. this.maximum.clone(),
  18641. this.minimum.clone(),
  18642. this.minimum.clone(),
  18643. this.minimum.clone(),
  18644. this.maximum.clone(),
  18645. this.maximum.clone(),
  18646. this.maximum.clone()
  18647. ];
  18648. this.vectors[2].x = this.maximum.x;
  18649. this.vectors[3].y = this.maximum.y;
  18650. this.vectors[4].z = this.maximum.z;
  18651. this.vectors[5].z = this.minimum.z;
  18652. this.vectors[6].x = this.minimum.x;
  18653. this.vectors[7].y = this.minimum.y;
  18654. // OBB
  18655. this.center = this.maximum.add(this.minimum).scale(0.5);
  18656. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18657. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18658. // World
  18659. for (var index = 0; index < this.vectors.length; index++) {
  18660. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18661. }
  18662. this.minimumWorld = BABYLON.Vector3.Zero();
  18663. this.maximumWorld = BABYLON.Vector3.Zero();
  18664. this.centerWorld = BABYLON.Vector3.Zero();
  18665. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18666. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18667. };
  18668. /**
  18669. * Scale the current bounding box by applying a scale factor
  18670. * @param factor defines the scale factor to apply
  18671. * @returns the current bounding box
  18672. */
  18673. BoundingBox.prototype.scale = function (factor) {
  18674. var diff = this.maximum.subtract(this.minimum);
  18675. var distance = diff.length() * factor;
  18676. diff.normalize();
  18677. var newRadius = diff.scale(distance / 2);
  18678. var min = this.center.subtract(newRadius);
  18679. var max = this.center.add(newRadius);
  18680. this.reConstruct(min, max);
  18681. return this;
  18682. };
  18683. /**
  18684. * Gets the world matrix of the bounding box
  18685. * @returns a matrix
  18686. */
  18687. BoundingBox.prototype.getWorldMatrix = function () {
  18688. return this._worldMatrix;
  18689. };
  18690. /**
  18691. * Sets the world matrix stored in the bounding box
  18692. * @param matrix defines the matrix to store
  18693. * @returns current bounding box
  18694. */
  18695. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18696. this._worldMatrix.copyFrom(matrix);
  18697. return this;
  18698. };
  18699. /** @hidden */
  18700. BoundingBox.prototype._update = function (world) {
  18701. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18702. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18703. for (var index = 0; index < this.vectors.length; index++) {
  18704. var v = this.vectorsWorld[index];
  18705. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18706. if (v.x < this.minimumWorld.x)
  18707. this.minimumWorld.x = v.x;
  18708. if (v.y < this.minimumWorld.y)
  18709. this.minimumWorld.y = v.y;
  18710. if (v.z < this.minimumWorld.z)
  18711. this.minimumWorld.z = v.z;
  18712. if (v.x > this.maximumWorld.x)
  18713. this.maximumWorld.x = v.x;
  18714. if (v.y > this.maximumWorld.y)
  18715. this.maximumWorld.y = v.y;
  18716. if (v.z > this.maximumWorld.z)
  18717. this.maximumWorld.z = v.z;
  18718. }
  18719. // Extend
  18720. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18721. this.extendSizeWorld.scaleInPlace(0.5);
  18722. // OBB
  18723. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18724. this.centerWorld.scaleInPlace(0.5);
  18725. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18726. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18727. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18728. this._worldMatrix = world;
  18729. };
  18730. /**
  18731. * Tests if the bounding box is intersecting the frustum planes
  18732. * @param frustumPlanes defines the frustum planes to test
  18733. * @returns true if there is an intersection
  18734. */
  18735. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18736. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18737. };
  18738. /**
  18739. * Tests if the bounding box is entirely inside the frustum planes
  18740. * @param frustumPlanes defines the frustum planes to test
  18741. * @returns true if there is an inclusion
  18742. */
  18743. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18744. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18745. };
  18746. /**
  18747. * Tests if a point is inside the bounding box
  18748. * @param point defines the point to test
  18749. * @returns true if the point is inside the bounding box
  18750. */
  18751. BoundingBox.prototype.intersectsPoint = function (point) {
  18752. var delta = -BABYLON.Epsilon;
  18753. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18754. return false;
  18755. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18756. return false;
  18757. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18758. return false;
  18759. return true;
  18760. };
  18761. /**
  18762. * Tests if the bounding box intersects with a bounding sphere
  18763. * @param sphere defines the sphere to test
  18764. * @returns true if there is an intersection
  18765. */
  18766. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18767. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18768. };
  18769. /**
  18770. * Tests if the bounding box intersects with a box defined by a min and max vectors
  18771. * @param min defines the min vector to use
  18772. * @param max defines the max vector to use
  18773. * @returns true if there is an intersection
  18774. */
  18775. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18776. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18777. return false;
  18778. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18779. return false;
  18780. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18781. return false;
  18782. return true;
  18783. };
  18784. // Statics
  18785. /**
  18786. * Tests if two bounding boxes are intersections
  18787. * @param box0 defines the first box to test
  18788. * @param box1 defines the second box to test
  18789. * @returns true if there is an intersection
  18790. */
  18791. BoundingBox.Intersects = function (box0, box1) {
  18792. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18793. return false;
  18794. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18795. return false;
  18796. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18797. return false;
  18798. return true;
  18799. };
  18800. /**
  18801. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  18802. * @param minPoint defines the minimum vector of the bounding box
  18803. * @param maxPoint defines the maximum vector of the bounding box
  18804. * @param sphereCenter defines the sphere center
  18805. * @param sphereRadius defines the sphere radius
  18806. * @returns true if there is an intersection
  18807. */
  18808. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18809. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18810. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18811. return (num <= (sphereRadius * sphereRadius));
  18812. };
  18813. /**
  18814. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  18815. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18816. * @param frustumPlanes defines the frustum planes to test
  18817. * @return true if there is an inclusion
  18818. */
  18819. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18820. for (var p = 0; p < 6; p++) {
  18821. for (var i = 0; i < 8; i++) {
  18822. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18823. return false;
  18824. }
  18825. }
  18826. }
  18827. return true;
  18828. };
  18829. /**
  18830. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  18831. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18832. * @param frustumPlanes defines the frustum planes to test
  18833. * @return true if there is an intersection
  18834. */
  18835. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18836. for (var p = 0; p < 6; p++) {
  18837. var inCount = 8;
  18838. for (var i = 0; i < 8; i++) {
  18839. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18840. --inCount;
  18841. }
  18842. else {
  18843. break;
  18844. }
  18845. }
  18846. if (inCount === 0)
  18847. return false;
  18848. }
  18849. return true;
  18850. };
  18851. return BoundingBox;
  18852. }());
  18853. BABYLON.BoundingBox = BoundingBox;
  18854. })(BABYLON || (BABYLON = {}));
  18855. //# sourceMappingURL=babylon.boundingBox.js.map
  18856. var BABYLON;
  18857. (function (BABYLON) {
  18858. var computeBoxExtents = function (axis, box) {
  18859. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18860. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18861. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18862. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18863. var r = r0 + r1 + r2;
  18864. return {
  18865. min: p - r,
  18866. max: p + r
  18867. };
  18868. };
  18869. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18870. var axisOverlap = function (axis, box0, box1) {
  18871. var result0 = computeBoxExtents(axis, box0);
  18872. var result1 = computeBoxExtents(axis, box1);
  18873. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18874. };
  18875. /**
  18876. * Info for a bounding data of a mesh
  18877. */
  18878. var BoundingInfo = /** @class */ (function () {
  18879. /**
  18880. * Constructs bounding info
  18881. * @param minimum min vector of the bounding box/sphere
  18882. * @param maximum max vector of the bounding box/sphere
  18883. */
  18884. function BoundingInfo(
  18885. /**
  18886. * min vector of the bounding box/sphere
  18887. */
  18888. minimum,
  18889. /**
  18890. * max vector of the bounding box/sphere
  18891. */
  18892. maximum) {
  18893. this.minimum = minimum;
  18894. this.maximum = maximum;
  18895. this._isLocked = false;
  18896. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18897. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18898. }
  18899. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18900. /**
  18901. * If the info is locked and won't be updated to avoid perf overhead
  18902. */
  18903. get: function () {
  18904. return this._isLocked;
  18905. },
  18906. set: function (value) {
  18907. this._isLocked = value;
  18908. },
  18909. enumerable: true,
  18910. configurable: true
  18911. });
  18912. // Methods
  18913. /**
  18914. * Updates the boudning sphere and box
  18915. * @param world world matrix to be used to update
  18916. */
  18917. BoundingInfo.prototype.update = function (world) {
  18918. if (this._isLocked) {
  18919. return;
  18920. }
  18921. this.boundingBox._update(world);
  18922. this.boundingSphere._update(world);
  18923. };
  18924. /**
  18925. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18926. * @param center New center of the bounding info
  18927. * @param extend New extend of the bounding info
  18928. * @returns the current bounding info
  18929. */
  18930. BoundingInfo.prototype.centerOn = function (center, extend) {
  18931. this.minimum = center.subtract(extend);
  18932. this.maximum = center.add(extend);
  18933. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18934. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18935. return this;
  18936. };
  18937. /**
  18938. * Scale the current bounding info by applying a scale factor
  18939. * @param factor defines the scale factor to apply
  18940. * @returns the current bounding info
  18941. */
  18942. BoundingInfo.prototype.scale = function (factor) {
  18943. this.boundingBox.scale(factor);
  18944. this.boundingSphere.scale(factor);
  18945. return this;
  18946. };
  18947. /**
  18948. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18949. * @param frustumPlanes defines the frustum to test
  18950. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18951. * @returns true if the bounding info is in the frustum planes
  18952. */
  18953. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18954. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18955. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18956. return false;
  18957. }
  18958. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18959. return true;
  18960. }
  18961. return this.boundingBox.isInFrustum(frustumPlanes);
  18962. };
  18963. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18964. /**
  18965. * Gets the world distance between the min and max points of the bounding box
  18966. */
  18967. get: function () {
  18968. var boundingBox = this.boundingBox;
  18969. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18970. return size.length();
  18971. },
  18972. enumerable: true,
  18973. configurable: true
  18974. });
  18975. /**
  18976. * Checks if a cullable object (mesh...) is in the camera frustum
  18977. * Unlike isInFrustum this cheks the full bounding box
  18978. * @param frustumPlanes Camera near/planes
  18979. * @returns true if the object is in frustum otherwise false
  18980. */
  18981. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18982. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18983. };
  18984. /** @hidden */
  18985. BoundingInfo.prototype._checkCollision = function (collider) {
  18986. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18987. };
  18988. /**
  18989. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  18990. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  18991. * @param point the point to check intersection with
  18992. * @returns if the point intersects
  18993. */
  18994. BoundingInfo.prototype.intersectsPoint = function (point) {
  18995. if (!this.boundingSphere.centerWorld) {
  18996. return false;
  18997. }
  18998. if (!this.boundingSphere.intersectsPoint(point)) {
  18999. return false;
  19000. }
  19001. if (!this.boundingBox.intersectsPoint(point)) {
  19002. return false;
  19003. }
  19004. return true;
  19005. };
  19006. /**
  19007. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19008. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19009. * @param boundingInfo the bounding info to check intersection with
  19010. * @param precise if the intersection should be done using OBB
  19011. * @returns if the bounding info intersects
  19012. */
  19013. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19014. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19015. return false;
  19016. }
  19017. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19018. return false;
  19019. }
  19020. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19021. return false;
  19022. }
  19023. if (!precise) {
  19024. return true;
  19025. }
  19026. var box0 = this.boundingBox;
  19027. var box1 = boundingInfo.boundingBox;
  19028. if (!axisOverlap(box0.directions[0], box0, box1))
  19029. return false;
  19030. if (!axisOverlap(box0.directions[1], box0, box1))
  19031. return false;
  19032. if (!axisOverlap(box0.directions[2], box0, box1))
  19033. return false;
  19034. if (!axisOverlap(box1.directions[0], box0, box1))
  19035. return false;
  19036. if (!axisOverlap(box1.directions[1], box0, box1))
  19037. return false;
  19038. if (!axisOverlap(box1.directions[2], box0, box1))
  19039. return false;
  19040. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19041. return false;
  19042. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19043. return false;
  19044. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19045. return false;
  19046. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19047. return false;
  19048. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19049. return false;
  19050. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19051. return false;
  19052. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19053. return false;
  19054. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19055. return false;
  19056. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19057. return false;
  19058. return true;
  19059. };
  19060. return BoundingInfo;
  19061. }());
  19062. BABYLON.BoundingInfo = BoundingInfo;
  19063. })(BABYLON || (BABYLON = {}));
  19064. //# sourceMappingURL=babylon.boundingInfo.js.map
  19065. var BABYLON;
  19066. (function (BABYLON) {
  19067. var TransformNode = /** @class */ (function (_super) {
  19068. __extends(TransformNode, _super);
  19069. function TransformNode(name, scene, isPure) {
  19070. if (scene === void 0) { scene = null; }
  19071. if (isPure === void 0) { isPure = true; }
  19072. var _this = _super.call(this, name, scene) || this;
  19073. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19074. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19075. _this._up = new BABYLON.Vector3(0, 1, 0);
  19076. _this._right = new BABYLON.Vector3(1, 0, 0);
  19077. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19078. // Properties
  19079. _this._position = BABYLON.Vector3.Zero();
  19080. _this._rotation = BABYLON.Vector3.Zero();
  19081. _this._scaling = BABYLON.Vector3.One();
  19082. _this._isDirty = false;
  19083. /**
  19084. * Set the billboard mode. Default is 0.
  19085. *
  19086. * | Value | Type | Description |
  19087. * | --- | --- | --- |
  19088. * | 0 | BILLBOARDMODE_NONE | |
  19089. * | 1 | BILLBOARDMODE_X | |
  19090. * | 2 | BILLBOARDMODE_Y | |
  19091. * | 4 | BILLBOARDMODE_Z | |
  19092. * | 7 | BILLBOARDMODE_ALL | |
  19093. *
  19094. */
  19095. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19096. _this.scalingDeterminant = 1;
  19097. _this.infiniteDistance = false;
  19098. /**
  19099. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19100. * By default the system will update normals to compensate
  19101. */
  19102. _this.ignoreNonUniformScaling = false;
  19103. _this._localWorld = BABYLON.Matrix.Zero();
  19104. _this._absolutePosition = BABYLON.Vector3.Zero();
  19105. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19106. _this._postMultiplyPivotMatrix = false;
  19107. _this._isWorldMatrixFrozen = false;
  19108. /**
  19109. * An event triggered after the world matrix is updated
  19110. */
  19111. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19112. _this._nonUniformScaling = false;
  19113. if (isPure) {
  19114. _this.getScene().addTransformNode(_this);
  19115. }
  19116. return _this;
  19117. }
  19118. /**
  19119. * Gets a string identifying the name of the class
  19120. * @returns "TransformNode" string
  19121. */
  19122. TransformNode.prototype.getClassName = function () {
  19123. return "TransformNode";
  19124. };
  19125. Object.defineProperty(TransformNode.prototype, "position", {
  19126. /**
  19127. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19128. */
  19129. get: function () {
  19130. return this._position;
  19131. },
  19132. set: function (newPosition) {
  19133. this._position = newPosition;
  19134. this._isDirty = true;
  19135. },
  19136. enumerable: true,
  19137. configurable: true
  19138. });
  19139. Object.defineProperty(TransformNode.prototype, "rotation", {
  19140. /**
  19141. * 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)).
  19142. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19143. */
  19144. get: function () {
  19145. return this._rotation;
  19146. },
  19147. set: function (newRotation) {
  19148. this._rotation = newRotation;
  19149. this._isDirty = true;
  19150. },
  19151. enumerable: true,
  19152. configurable: true
  19153. });
  19154. Object.defineProperty(TransformNode.prototype, "scaling", {
  19155. /**
  19156. * 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)).
  19157. */
  19158. get: function () {
  19159. return this._scaling;
  19160. },
  19161. set: function (newScaling) {
  19162. this._scaling = newScaling;
  19163. this._isDirty = true;
  19164. },
  19165. enumerable: true,
  19166. configurable: true
  19167. });
  19168. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19169. /**
  19170. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19171. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19172. */
  19173. get: function () {
  19174. return this._rotationQuaternion;
  19175. },
  19176. set: function (quaternion) {
  19177. this._rotationQuaternion = quaternion;
  19178. //reset the rotation vector.
  19179. if (quaternion && this.rotation.length()) {
  19180. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19181. }
  19182. },
  19183. enumerable: true,
  19184. configurable: true
  19185. });
  19186. Object.defineProperty(TransformNode.prototype, "forward", {
  19187. /**
  19188. * The forward direction of that transform in world space.
  19189. */
  19190. get: function () {
  19191. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19192. },
  19193. enumerable: true,
  19194. configurable: true
  19195. });
  19196. Object.defineProperty(TransformNode.prototype, "up", {
  19197. /**
  19198. * The up direction of that transform in world space.
  19199. */
  19200. get: function () {
  19201. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19202. },
  19203. enumerable: true,
  19204. configurable: true
  19205. });
  19206. Object.defineProperty(TransformNode.prototype, "right", {
  19207. /**
  19208. * The right direction of that transform in world space.
  19209. */
  19210. get: function () {
  19211. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19212. },
  19213. enumerable: true,
  19214. configurable: true
  19215. });
  19216. /**
  19217. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19218. * Returns the TransformNode.
  19219. */
  19220. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19221. this._poseMatrix.copyFrom(matrix);
  19222. return this;
  19223. };
  19224. /**
  19225. * Returns the mesh Pose matrix.
  19226. * Returned object : Matrix
  19227. */
  19228. TransformNode.prototype.getPoseMatrix = function () {
  19229. return this._poseMatrix;
  19230. };
  19231. /** @hidden */
  19232. TransformNode.prototype._isSynchronized = function () {
  19233. if (this._isDirty) {
  19234. return false;
  19235. }
  19236. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19237. return false;
  19238. if (this._cache.pivotMatrixUpdated) {
  19239. return false;
  19240. }
  19241. if (this.infiniteDistance) {
  19242. return false;
  19243. }
  19244. if (!this._cache.position.equals(this._position))
  19245. return false;
  19246. if (this._rotationQuaternion) {
  19247. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19248. return false;
  19249. }
  19250. if (!this._cache.rotation.equals(this._rotation))
  19251. return false;
  19252. if (!this._cache.scaling.equals(this._scaling))
  19253. return false;
  19254. return true;
  19255. };
  19256. /** @hidden */
  19257. TransformNode.prototype._initCache = function () {
  19258. _super.prototype._initCache.call(this);
  19259. this._cache.localMatrixUpdated = false;
  19260. this._cache.position = BABYLON.Vector3.Zero();
  19261. this._cache.scaling = BABYLON.Vector3.Zero();
  19262. this._cache.rotation = BABYLON.Vector3.Zero();
  19263. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19264. this._cache.billboardMode = -1;
  19265. };
  19266. TransformNode.prototype.markAsDirty = function (property) {
  19267. if (property === "rotation") {
  19268. this.rotationQuaternion = null;
  19269. }
  19270. this._currentRenderId = Number.MAX_VALUE;
  19271. this._isDirty = true;
  19272. return this;
  19273. };
  19274. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19275. /**
  19276. * Returns the current mesh absolute position.
  19277. * Returns a Vector3.
  19278. */
  19279. get: function () {
  19280. return this._absolutePosition;
  19281. },
  19282. enumerable: true,
  19283. configurable: true
  19284. });
  19285. /**
  19286. * Sets a new matrix to apply before all other transformation
  19287. * @param matrix defines the transform matrix
  19288. * @returns the current TransformNode
  19289. */
  19290. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19291. return this.setPivotMatrix(matrix, false);
  19292. };
  19293. /**
  19294. * Sets a new pivot matrix to the current node
  19295. * @param matrix defines the new pivot matrix to use
  19296. * @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
  19297. * @returns the current TransformNode
  19298. */
  19299. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19300. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19301. this._pivotMatrix = matrix.clone();
  19302. this._cache.pivotMatrixUpdated = true;
  19303. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19304. if (this._postMultiplyPivotMatrix) {
  19305. if (!this._pivotMatrixInverse) {
  19306. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19307. }
  19308. else {
  19309. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19310. }
  19311. }
  19312. return this;
  19313. };
  19314. /**
  19315. * Returns the mesh pivot matrix.
  19316. * Default : Identity.
  19317. * A Matrix is returned.
  19318. */
  19319. TransformNode.prototype.getPivotMatrix = function () {
  19320. return this._pivotMatrix;
  19321. };
  19322. /**
  19323. * Prevents the World matrix to be computed any longer.
  19324. * Returns the TransformNode.
  19325. */
  19326. TransformNode.prototype.freezeWorldMatrix = function () {
  19327. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19328. this.computeWorldMatrix(true);
  19329. this._isWorldMatrixFrozen = true;
  19330. return this;
  19331. };
  19332. /**
  19333. * Allows back the World matrix computation.
  19334. * Returns the TransformNode.
  19335. */
  19336. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19337. this._isWorldMatrixFrozen = false;
  19338. this.computeWorldMatrix(true);
  19339. return this;
  19340. };
  19341. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19342. /**
  19343. * True if the World matrix has been frozen.
  19344. * Returns a boolean.
  19345. */
  19346. get: function () {
  19347. return this._isWorldMatrixFrozen;
  19348. },
  19349. enumerable: true,
  19350. configurable: true
  19351. });
  19352. /**
  19353. * Retuns the mesh absolute position in the World.
  19354. * Returns a Vector3.
  19355. */
  19356. TransformNode.prototype.getAbsolutePosition = function () {
  19357. this.computeWorldMatrix();
  19358. return this._absolutePosition;
  19359. };
  19360. /**
  19361. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19362. * Returns the TransformNode.
  19363. */
  19364. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19365. if (!absolutePosition) {
  19366. return this;
  19367. }
  19368. var absolutePositionX;
  19369. var absolutePositionY;
  19370. var absolutePositionZ;
  19371. if (absolutePosition.x === undefined) {
  19372. if (arguments.length < 3) {
  19373. return this;
  19374. }
  19375. absolutePositionX = arguments[0];
  19376. absolutePositionY = arguments[1];
  19377. absolutePositionZ = arguments[2];
  19378. }
  19379. else {
  19380. absolutePositionX = absolutePosition.x;
  19381. absolutePositionY = absolutePosition.y;
  19382. absolutePositionZ = absolutePosition.z;
  19383. }
  19384. if (this.parent) {
  19385. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19386. invertParentWorldMatrix.invert();
  19387. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19388. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19389. }
  19390. else {
  19391. this.position.x = absolutePositionX;
  19392. this.position.y = absolutePositionY;
  19393. this.position.z = absolutePositionZ;
  19394. }
  19395. return this;
  19396. };
  19397. /**
  19398. * Sets the mesh position in its local space.
  19399. * Returns the TransformNode.
  19400. */
  19401. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19402. this.computeWorldMatrix();
  19403. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19404. return this;
  19405. };
  19406. /**
  19407. * Returns the mesh position in the local space from the current World matrix values.
  19408. * Returns a new Vector3.
  19409. */
  19410. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19411. this.computeWorldMatrix();
  19412. var invLocalWorldMatrix = this._localWorld.clone();
  19413. invLocalWorldMatrix.invert();
  19414. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19415. };
  19416. /**
  19417. * Translates the mesh along the passed Vector3 in its local space.
  19418. * Returns the TransformNode.
  19419. */
  19420. TransformNode.prototype.locallyTranslate = function (vector3) {
  19421. this.computeWorldMatrix(true);
  19422. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19423. return this;
  19424. };
  19425. /**
  19426. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19427. * @param targetPoint the position (must be in same space as current mesh) to look at
  19428. * @param yawCor optional yaw (y-axis) correction in radians
  19429. * @param pitchCor optional pitch (x-axis) correction in radians
  19430. * @param rollCor optional roll (z-axis) correction in radians
  19431. * @param space the choosen space of the target
  19432. * @returns the TransformNode.
  19433. */
  19434. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19435. if (yawCor === void 0) { yawCor = 0; }
  19436. if (pitchCor === void 0) { pitchCor = 0; }
  19437. if (rollCor === void 0) { rollCor = 0; }
  19438. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19439. var dv = TransformNode._lookAtVectorCache;
  19440. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19441. targetPoint.subtractToRef(pos, dv);
  19442. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19443. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19444. var pitch = Math.atan2(dv.y, len);
  19445. if (this.rotationQuaternion) {
  19446. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19447. }
  19448. else {
  19449. this.rotation.x = pitch + pitchCor;
  19450. this.rotation.y = yaw + yawCor;
  19451. this.rotation.z = rollCor;
  19452. }
  19453. return this;
  19454. };
  19455. /**
  19456. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19457. * This Vector3 is expressed in the World space.
  19458. */
  19459. TransformNode.prototype.getDirection = function (localAxis) {
  19460. var result = BABYLON.Vector3.Zero();
  19461. this.getDirectionToRef(localAxis, result);
  19462. return result;
  19463. };
  19464. /**
  19465. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19466. * localAxis is expressed in the mesh local space.
  19467. * result is computed in the Wordl space from the mesh World matrix.
  19468. * Returns the TransformNode.
  19469. */
  19470. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19471. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19472. return this;
  19473. };
  19474. /**
  19475. * Sets a new pivot point to the current node
  19476. * @param point defines the new pivot point to use
  19477. * @param space defines if the point is in world or local space (local by default)
  19478. * @returns the current TransformNode
  19479. */
  19480. TransformNode.prototype.setPivotPoint = function (point, space) {
  19481. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19482. if (this.getScene().getRenderId() == 0) {
  19483. this.computeWorldMatrix(true);
  19484. }
  19485. var wm = this.getWorldMatrix();
  19486. if (space == BABYLON.Space.WORLD) {
  19487. var tmat = BABYLON.Tmp.Matrix[0];
  19488. wm.invertToRef(tmat);
  19489. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19490. }
  19491. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19492. };
  19493. /**
  19494. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19495. */
  19496. TransformNode.prototype.getPivotPoint = function () {
  19497. var point = BABYLON.Vector3.Zero();
  19498. this.getPivotPointToRef(point);
  19499. return point;
  19500. };
  19501. /**
  19502. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19503. * Returns the TransformNode.
  19504. */
  19505. TransformNode.prototype.getPivotPointToRef = function (result) {
  19506. result.x = -this._pivotMatrix.m[12];
  19507. result.y = -this._pivotMatrix.m[13];
  19508. result.z = -this._pivotMatrix.m[14];
  19509. return this;
  19510. };
  19511. /**
  19512. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19513. */
  19514. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19515. var point = BABYLON.Vector3.Zero();
  19516. this.getAbsolutePivotPointToRef(point);
  19517. return point;
  19518. };
  19519. /**
  19520. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19521. * Returns the TransformNode.
  19522. */
  19523. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19524. result.x = this._pivotMatrix.m[12];
  19525. result.y = this._pivotMatrix.m[13];
  19526. result.z = this._pivotMatrix.m[14];
  19527. this.getPivotPointToRef(result);
  19528. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19529. return this;
  19530. };
  19531. /**
  19532. * Defines the passed node as the parent of the current node.
  19533. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19534. * Returns the TransformNode.
  19535. */
  19536. TransformNode.prototype.setParent = function (node) {
  19537. if (!node && !this.parent) {
  19538. return this;
  19539. }
  19540. if (!node) {
  19541. var rotation = BABYLON.Tmp.Quaternion[0];
  19542. var position = BABYLON.Tmp.Vector3[0];
  19543. var scale = BABYLON.Tmp.Vector3[1];
  19544. if (this.parent && this.parent.computeWorldMatrix) {
  19545. this.parent.computeWorldMatrix(true);
  19546. }
  19547. this.computeWorldMatrix(true);
  19548. this.getWorldMatrix().decompose(scale, rotation, position);
  19549. if (this.rotationQuaternion) {
  19550. this.rotationQuaternion.copyFrom(rotation);
  19551. }
  19552. else {
  19553. rotation.toEulerAnglesToRef(this.rotation);
  19554. }
  19555. this.scaling.x = scale.x;
  19556. this.scaling.y = scale.y;
  19557. this.scaling.z = scale.z;
  19558. this.position.x = position.x;
  19559. this.position.y = position.y;
  19560. this.position.z = position.z;
  19561. }
  19562. else {
  19563. var rotation = BABYLON.Tmp.Quaternion[0];
  19564. var position = BABYLON.Tmp.Vector3[0];
  19565. var scale = BABYLON.Tmp.Vector3[1];
  19566. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19567. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19568. this.computeWorldMatrix(true);
  19569. node.computeWorldMatrix(true);
  19570. node.getWorldMatrix().invertToRef(invParentMatrix);
  19571. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19572. diffMatrix.decompose(scale, rotation, position);
  19573. if (this.rotationQuaternion) {
  19574. this.rotationQuaternion.copyFrom(rotation);
  19575. }
  19576. else {
  19577. rotation.toEulerAnglesToRef(this.rotation);
  19578. }
  19579. this.position.x = position.x;
  19580. this.position.y = position.y;
  19581. this.position.z = position.z;
  19582. this.scaling.x = scale.x;
  19583. this.scaling.y = scale.y;
  19584. this.scaling.z = scale.z;
  19585. }
  19586. this.parent = node;
  19587. return this;
  19588. };
  19589. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19590. get: function () {
  19591. return this._nonUniformScaling;
  19592. },
  19593. enumerable: true,
  19594. configurable: true
  19595. });
  19596. /** @hidden */
  19597. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19598. if (this._nonUniformScaling === value) {
  19599. return false;
  19600. }
  19601. this._nonUniformScaling = value;
  19602. return true;
  19603. };
  19604. /**
  19605. * Attach the current TransformNode to another TransformNode associated with a bone
  19606. * @param bone Bone affecting the TransformNode
  19607. * @param affectedTransformNode TransformNode associated with the bone
  19608. */
  19609. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19610. this._transformToBoneReferal = affectedTransformNode;
  19611. this.parent = bone;
  19612. if (bone.getWorldMatrix().determinant() < 0) {
  19613. this.scalingDeterminant *= -1;
  19614. }
  19615. return this;
  19616. };
  19617. TransformNode.prototype.detachFromBone = function () {
  19618. if (!this.parent) {
  19619. return this;
  19620. }
  19621. if (this.parent.getWorldMatrix().determinant() < 0) {
  19622. this.scalingDeterminant *= -1;
  19623. }
  19624. this._transformToBoneReferal = null;
  19625. this.parent = null;
  19626. return this;
  19627. };
  19628. /**
  19629. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19630. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19631. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19632. * The passed axis is also normalized.
  19633. * Returns the TransformNode.
  19634. */
  19635. TransformNode.prototype.rotate = function (axis, amount, space) {
  19636. axis.normalize();
  19637. if (!this.rotationQuaternion) {
  19638. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19639. this.rotation = BABYLON.Vector3.Zero();
  19640. }
  19641. var rotationQuaternion;
  19642. if (!space || space === BABYLON.Space.LOCAL) {
  19643. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19644. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19645. }
  19646. else {
  19647. if (this.parent) {
  19648. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19649. invertParentWorldMatrix.invert();
  19650. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19651. }
  19652. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19653. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19654. }
  19655. return this;
  19656. };
  19657. /**
  19658. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19659. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19660. * The passed axis is also normalized.
  19661. * Returns the TransformNode.
  19662. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19663. */
  19664. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19665. axis.normalize();
  19666. if (!this.rotationQuaternion) {
  19667. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19668. this.rotation.copyFromFloats(0, 0, 0);
  19669. }
  19670. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19671. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19672. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19673. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19674. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19675. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19676. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19677. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19678. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19679. return this;
  19680. };
  19681. /**
  19682. * Translates the mesh along the axis vector for the passed distance in the given space.
  19683. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19684. * Returns the TransformNode.
  19685. */
  19686. TransformNode.prototype.translate = function (axis, distance, space) {
  19687. var displacementVector = axis.scale(distance);
  19688. if (!space || space === BABYLON.Space.LOCAL) {
  19689. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19690. this.setPositionWithLocalVector(tempV3);
  19691. }
  19692. else {
  19693. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19694. }
  19695. return this;
  19696. };
  19697. /**
  19698. * Adds a rotation step to the mesh current rotation.
  19699. * x, y, z are Euler angles expressed in radians.
  19700. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19701. * This means this rotation is made in the mesh local space only.
  19702. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19703. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19704. * ```javascript
  19705. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19706. * ```
  19707. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19708. * 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.
  19709. * Returns the TransformNode.
  19710. */
  19711. TransformNode.prototype.addRotation = function (x, y, z) {
  19712. var rotationQuaternion;
  19713. if (this.rotationQuaternion) {
  19714. rotationQuaternion = this.rotationQuaternion;
  19715. }
  19716. else {
  19717. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19718. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19719. }
  19720. var accumulation = BABYLON.Tmp.Quaternion[0];
  19721. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19722. rotationQuaternion.multiplyInPlace(accumulation);
  19723. if (!this.rotationQuaternion) {
  19724. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19725. }
  19726. return this;
  19727. };
  19728. /**
  19729. * Computes the world matrix of the node
  19730. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19731. * @returns the world matrix
  19732. */
  19733. TransformNode.prototype.computeWorldMatrix = function (force) {
  19734. if (this._isWorldMatrixFrozen) {
  19735. return this._worldMatrix;
  19736. }
  19737. if (!force && this.isSynchronized()) {
  19738. this._currentRenderId = this.getScene().getRenderId();
  19739. return this._worldMatrix;
  19740. }
  19741. this._updateCache();
  19742. this._cache.position.copyFrom(this.position);
  19743. this._cache.scaling.copyFrom(this.scaling);
  19744. this._cache.pivotMatrixUpdated = false;
  19745. this._cache.billboardMode = this.billboardMode;
  19746. this._currentRenderId = this.getScene().getRenderId();
  19747. this._childRenderId = this.getScene().getRenderId();
  19748. this._isDirty = false;
  19749. // Scaling
  19750. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19751. // Rotation
  19752. //rotate, if quaternion is set and rotation was used
  19753. if (this.rotationQuaternion) {
  19754. var len = this.rotation.length();
  19755. if (len) {
  19756. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19757. this.rotation.copyFromFloats(0, 0, 0);
  19758. }
  19759. }
  19760. if (this.rotationQuaternion) {
  19761. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19762. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19763. }
  19764. else {
  19765. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19766. this._cache.rotation.copyFrom(this.rotation);
  19767. }
  19768. // Translation
  19769. var camera = this.getScene().activeCamera;
  19770. if (this.infiniteDistance && !this.parent && camera) {
  19771. var cameraWorldMatrix = camera.getWorldMatrix();
  19772. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19773. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19774. }
  19775. else {
  19776. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19777. }
  19778. // Composing transformations
  19779. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19780. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19781. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19782. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19783. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19784. // Need to decompose each rotation here
  19785. var currentPosition = BABYLON.Tmp.Vector3[3];
  19786. if (this.parent && this.parent.getWorldMatrix) {
  19787. if (this._transformToBoneReferal) {
  19788. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19789. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19790. }
  19791. else {
  19792. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19793. }
  19794. }
  19795. else {
  19796. currentPosition.copyFrom(this.position);
  19797. }
  19798. currentPosition.subtractInPlace(camera.globalPosition);
  19799. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19800. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19801. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19802. }
  19803. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19804. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19805. }
  19806. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19807. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19808. }
  19809. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19810. }
  19811. else {
  19812. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19813. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19814. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19815. }
  19816. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19817. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19818. }
  19819. // Post multiply inverse of pivotMatrix
  19820. if (this._postMultiplyPivotMatrix) {
  19821. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19822. }
  19823. // Local world
  19824. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19825. // Parent
  19826. if (this.parent && this.parent.getWorldMatrix) {
  19827. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19828. if (this._transformToBoneReferal) {
  19829. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19830. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19831. }
  19832. else {
  19833. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19834. }
  19835. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19836. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19837. this._worldMatrix.copyFrom(this._localWorld);
  19838. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19839. }
  19840. else {
  19841. if (this._transformToBoneReferal) {
  19842. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19843. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19844. }
  19845. else {
  19846. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19847. }
  19848. }
  19849. this._markSyncedWithParent();
  19850. }
  19851. else {
  19852. this._worldMatrix.copyFrom(this._localWorld);
  19853. }
  19854. // Normal matrix
  19855. if (!this.ignoreNonUniformScaling) {
  19856. if (this.scaling.isNonUniform) {
  19857. this._updateNonUniformScalingState(true);
  19858. }
  19859. else if (this.parent && this.parent._nonUniformScaling) {
  19860. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19861. }
  19862. else {
  19863. this._updateNonUniformScalingState(false);
  19864. }
  19865. }
  19866. else {
  19867. this._updateNonUniformScalingState(false);
  19868. }
  19869. this._afterComputeWorldMatrix();
  19870. // Absolute position
  19871. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19872. // Callbacks
  19873. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19874. if (!this._poseMatrix) {
  19875. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19876. }
  19877. // Cache the determinant
  19878. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19879. return this._worldMatrix;
  19880. };
  19881. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19882. };
  19883. /**
  19884. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19885. * @param func: callback function to add
  19886. *
  19887. * Returns the TransformNode.
  19888. */
  19889. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19890. this.onAfterWorldMatrixUpdateObservable.add(func);
  19891. return this;
  19892. };
  19893. /**
  19894. * Removes a registered callback function.
  19895. * Returns the TransformNode.
  19896. */
  19897. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19898. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19899. return this;
  19900. };
  19901. /**
  19902. * Clone the current transform node
  19903. * Returns the new transform node
  19904. * @param name Name of the new clone
  19905. * @param newParent New parent for the clone
  19906. * @param doNotCloneChildren Do not clone children hierarchy
  19907. */
  19908. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19909. var _this = this;
  19910. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19911. result.name = name;
  19912. result.id = name;
  19913. if (newParent) {
  19914. result.parent = newParent;
  19915. }
  19916. if (!doNotCloneChildren) {
  19917. // Children
  19918. var directDescendants = this.getDescendants(true);
  19919. for (var index = 0; index < directDescendants.length; index++) {
  19920. var child = directDescendants[index];
  19921. if (child.clone) {
  19922. child.clone(name + "." + child.name, result);
  19923. }
  19924. }
  19925. }
  19926. return result;
  19927. };
  19928. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19929. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19930. serializationObject.type = this.getClassName();
  19931. // Parent
  19932. if (this.parent) {
  19933. serializationObject.parentId = this.parent.id;
  19934. }
  19935. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19936. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19937. }
  19938. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19939. serializationObject.isEnabled = this.isEnabled();
  19940. // Parent
  19941. if (this.parent) {
  19942. serializationObject.parentId = this.parent.id;
  19943. }
  19944. return serializationObject;
  19945. };
  19946. // Statics
  19947. /**
  19948. * Returns a new TransformNode object parsed from the source provided.
  19949. * The parameter `parsedMesh` is the source.
  19950. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19951. */
  19952. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19953. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19954. if (BABYLON.Tags) {
  19955. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19956. }
  19957. if (parsedTransformNode.localMatrix) {
  19958. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19959. }
  19960. else if (parsedTransformNode.pivotMatrix) {
  19961. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19962. }
  19963. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19964. // Parent
  19965. if (parsedTransformNode.parentId) {
  19966. transformNode._waitingParentId = parsedTransformNode.parentId;
  19967. }
  19968. return transformNode;
  19969. };
  19970. /**
  19971. * Releases resources associated with this transform node.
  19972. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19973. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19974. */
  19975. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19976. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19977. // Animations
  19978. this.getScene().stopAnimation(this);
  19979. // Remove from scene
  19980. this.getScene().removeTransformNode(this);
  19981. this.onAfterWorldMatrixUpdateObservable.clear();
  19982. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19983. };
  19984. // Statics
  19985. TransformNode.BILLBOARDMODE_NONE = 0;
  19986. TransformNode.BILLBOARDMODE_X = 1;
  19987. TransformNode.BILLBOARDMODE_Y = 2;
  19988. TransformNode.BILLBOARDMODE_Z = 4;
  19989. TransformNode.BILLBOARDMODE_ALL = 7;
  19990. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19991. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19992. __decorate([
  19993. BABYLON.serializeAsVector3("position")
  19994. ], TransformNode.prototype, "_position", void 0);
  19995. __decorate([
  19996. BABYLON.serializeAsVector3("rotation")
  19997. ], TransformNode.prototype, "_rotation", void 0);
  19998. __decorate([
  19999. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20000. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20001. __decorate([
  20002. BABYLON.serializeAsVector3("scaling")
  20003. ], TransformNode.prototype, "_scaling", void 0);
  20004. __decorate([
  20005. BABYLON.serialize()
  20006. ], TransformNode.prototype, "billboardMode", void 0);
  20007. __decorate([
  20008. BABYLON.serialize()
  20009. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20010. __decorate([
  20011. BABYLON.serialize()
  20012. ], TransformNode.prototype, "infiniteDistance", void 0);
  20013. __decorate([
  20014. BABYLON.serialize()
  20015. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20016. return TransformNode;
  20017. }(BABYLON.Node));
  20018. BABYLON.TransformNode = TransformNode;
  20019. })(BABYLON || (BABYLON = {}));
  20020. //# sourceMappingURL=babylon.transformNode.js.map
  20021. var BABYLON;
  20022. (function (BABYLON) {
  20023. /** @hidden */
  20024. var _FacetDataStorage = /** @class */ (function () {
  20025. function _FacetDataStorage() {
  20026. this.facetNb = 0; // facet number
  20027. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20028. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20029. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20030. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20031. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20032. this.subDiv = {
  20033. max: 1,
  20034. X: 1,
  20035. Y: 1,
  20036. Z: 1
  20037. };
  20038. this.facetDepthSort = false; // is the facet depth sort to be computed
  20039. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20040. }
  20041. return _FacetDataStorage;
  20042. }());
  20043. /**
  20044. * Class used to store all common mesh properties
  20045. */
  20046. var AbstractMesh = /** @class */ (function (_super) {
  20047. __extends(AbstractMesh, _super);
  20048. // Constructor
  20049. /**
  20050. * Creates a new AbstractMesh
  20051. * @param name defines the name of the mesh
  20052. * @param scene defines the hosting scene
  20053. */
  20054. function AbstractMesh(name, scene) {
  20055. if (scene === void 0) { scene = null; }
  20056. var _this = _super.call(this, name, scene, false) || this;
  20057. _this._facetData = new _FacetDataStorage();
  20058. /** Gets ot sets the culling strategy to use to find visible meshes */
  20059. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20060. // Events
  20061. /**
  20062. * An event triggered when this mesh collides with another one
  20063. */
  20064. _this.onCollideObservable = new BABYLON.Observable();
  20065. /**
  20066. * An event triggered when the collision's position changes
  20067. */
  20068. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20069. /**
  20070. * An event triggered when material is changed
  20071. */
  20072. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20073. // Properties
  20074. /**
  20075. * Gets or sets the orientation for POV movement & rotation
  20076. */
  20077. _this.definedFacingForward = true;
  20078. _this._visibility = 1.0;
  20079. /** Gets or sets the alpha index used to sort transparent meshes
  20080. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20081. */
  20082. _this.alphaIndex = Number.MAX_VALUE;
  20083. /**
  20084. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20085. */
  20086. _this.isVisible = true;
  20087. /**
  20088. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20089. */
  20090. _this.isPickable = true;
  20091. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20092. _this.showSubMeshesBoundingBox = false;
  20093. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20094. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20095. */
  20096. _this.isBlocker = false;
  20097. /**
  20098. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20099. */
  20100. _this.enablePointerMoveEvents = false;
  20101. /**
  20102. * Specifies the rendering group id for this mesh (0 by default)
  20103. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20104. */
  20105. _this.renderingGroupId = 0;
  20106. _this._receiveShadows = false;
  20107. /** Defines color to use when rendering outline */
  20108. _this.outlineColor = BABYLON.Color3.Red();
  20109. /** Define width to use when rendering outline */
  20110. _this.outlineWidth = 0.02;
  20111. /** Defines color to use when rendering overlay */
  20112. _this.overlayColor = BABYLON.Color3.Red();
  20113. /** Defines alpha to use when rendering overlay */
  20114. _this.overlayAlpha = 0.5;
  20115. _this._hasVertexAlpha = false;
  20116. _this._useVertexColors = true;
  20117. _this._computeBonesUsingShaders = true;
  20118. _this._numBoneInfluencers = 4;
  20119. _this._applyFog = true;
  20120. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20121. _this.useOctreeForRenderingSelection = true;
  20122. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20123. _this.useOctreeForPicking = true;
  20124. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20125. _this.useOctreeForCollisions = true;
  20126. _this._layerMask = 0x0FFFFFFF;
  20127. /**
  20128. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20129. */
  20130. _this.alwaysSelectAsActiveMesh = false;
  20131. /**
  20132. * Gets or sets the current action manager
  20133. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20134. */
  20135. _this.actionManager = null;
  20136. // Collisions
  20137. _this._checkCollisions = false;
  20138. _this._collisionMask = -1;
  20139. _this._collisionGroup = -1;
  20140. /**
  20141. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20142. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20143. */
  20144. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20145. /**
  20146. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20147. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20148. */
  20149. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20150. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20151. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20152. // Edges
  20153. /**
  20154. * Defines edge width used when edgesRenderer is enabled
  20155. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20156. */
  20157. _this.edgesWidth = 1;
  20158. /**
  20159. * Defines edge color used when edgesRenderer is enabled
  20160. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20161. */
  20162. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20163. // Cache
  20164. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  20165. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  20166. /** @hidden */
  20167. _this._renderId = 0;
  20168. /** @hidden */
  20169. _this._intersectionsInProgress = new Array();
  20170. /** @hidden */
  20171. _this._unIndexed = false;
  20172. /** @hidden */
  20173. _this._lightSources = new Array();
  20174. /**
  20175. * An event triggered when the mesh is rebuilt.
  20176. */
  20177. _this.onRebuildObservable = new BABYLON.Observable();
  20178. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20179. if (collidedMesh === void 0) { collidedMesh = null; }
  20180. //TODO move this to the collision coordinator!
  20181. if (_this.getScene().workerCollisions)
  20182. newPosition.multiplyInPlace(_this._collider._radius);
  20183. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20184. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20185. _this.position.addInPlace(_this._diffPositionForCollisions);
  20186. }
  20187. if (collidedMesh) {
  20188. _this.onCollideObservable.notifyObservers(collidedMesh);
  20189. }
  20190. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20191. };
  20192. _this.getScene().addMesh(_this);
  20193. _this._resyncLightSources();
  20194. return _this;
  20195. }
  20196. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20197. /**
  20198. * No billboard
  20199. */
  20200. get: function () {
  20201. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20202. },
  20203. enumerable: true,
  20204. configurable: true
  20205. });
  20206. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20207. /** Billboard on X axis */
  20208. get: function () {
  20209. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20210. },
  20211. enumerable: true,
  20212. configurable: true
  20213. });
  20214. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20215. /** Billboard on Y axis */
  20216. get: function () {
  20217. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20218. },
  20219. enumerable: true,
  20220. configurable: true
  20221. });
  20222. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20223. /** Billboard on Z axis */
  20224. get: function () {
  20225. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20226. },
  20227. enumerable: true,
  20228. configurable: true
  20229. });
  20230. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20231. /** Billboard on all axes */
  20232. get: function () {
  20233. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20234. },
  20235. enumerable: true,
  20236. configurable: true
  20237. });
  20238. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20239. /**
  20240. * Gets the number of facets in the mesh
  20241. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20242. */
  20243. get: function () {
  20244. return this._facetData.facetNb;
  20245. },
  20246. enumerable: true,
  20247. configurable: true
  20248. });
  20249. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20250. /**
  20251. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20252. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20253. */
  20254. get: function () {
  20255. return this._facetData.partitioningSubdivisions;
  20256. },
  20257. set: function (nb) {
  20258. this._facetData.partitioningSubdivisions = nb;
  20259. },
  20260. enumerable: true,
  20261. configurable: true
  20262. });
  20263. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20264. /**
  20265. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20266. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20267. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20268. */
  20269. get: function () {
  20270. return this._facetData.partitioningBBoxRatio;
  20271. },
  20272. set: function (ratio) {
  20273. this._facetData.partitioningBBoxRatio = ratio;
  20274. },
  20275. enumerable: true,
  20276. configurable: true
  20277. });
  20278. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20279. /**
  20280. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20281. * Works only for updatable meshes.
  20282. * Doesn't work with multi-materials
  20283. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20284. */
  20285. get: function () {
  20286. return this._facetData.facetDepthSort;
  20287. },
  20288. set: function (sort) {
  20289. this._facetData.facetDepthSort = sort;
  20290. },
  20291. enumerable: true,
  20292. configurable: true
  20293. });
  20294. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20295. /**
  20296. * The location (Vector3) where the facet depth sort must be computed from.
  20297. * By default, the active camera position.
  20298. * Used only when facet depth sort is enabled
  20299. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20300. */
  20301. get: function () {
  20302. return this._facetData.facetDepthSortFrom;
  20303. },
  20304. set: function (location) {
  20305. this._facetData.facetDepthSortFrom = location;
  20306. },
  20307. enumerable: true,
  20308. configurable: true
  20309. });
  20310. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20311. /**
  20312. * gets a boolean indicating if facetData is enabled
  20313. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20314. */
  20315. get: function () {
  20316. return this._facetData.facetDataEnabled;
  20317. },
  20318. enumerable: true,
  20319. configurable: true
  20320. });
  20321. /** @hidden */
  20322. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20323. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20324. return false;
  20325. }
  20326. this._markSubMeshesAsMiscDirty();
  20327. return true;
  20328. };
  20329. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20330. /** Set a function to call when this mesh collides with another one */
  20331. set: function (callback) {
  20332. if (this._onCollideObserver) {
  20333. this.onCollideObservable.remove(this._onCollideObserver);
  20334. }
  20335. this._onCollideObserver = this.onCollideObservable.add(callback);
  20336. },
  20337. enumerable: true,
  20338. configurable: true
  20339. });
  20340. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20341. /** Set a function to call when the collision's position changes */
  20342. set: function (callback) {
  20343. if (this._onCollisionPositionChangeObserver) {
  20344. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20345. }
  20346. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20347. },
  20348. enumerable: true,
  20349. configurable: true
  20350. });
  20351. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20352. /**
  20353. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20354. */
  20355. get: function () {
  20356. return this._visibility;
  20357. },
  20358. /**
  20359. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20360. */
  20361. set: function (value) {
  20362. if (this._visibility === value) {
  20363. return;
  20364. }
  20365. this._visibility = value;
  20366. this._markSubMeshesAsMiscDirty();
  20367. },
  20368. enumerable: true,
  20369. configurable: true
  20370. });
  20371. Object.defineProperty(AbstractMesh.prototype, "material", {
  20372. /** Gets or sets current material */
  20373. get: function () {
  20374. return this._material;
  20375. },
  20376. set: function (value) {
  20377. if (this._material === value) {
  20378. return;
  20379. }
  20380. this._material = value;
  20381. if (this.onMaterialChangedObservable.hasObservers) {
  20382. this.onMaterialChangedObservable.notifyObservers(this);
  20383. }
  20384. if (!this.subMeshes) {
  20385. return;
  20386. }
  20387. this._unBindEffect();
  20388. },
  20389. enumerable: true,
  20390. configurable: true
  20391. });
  20392. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20393. /**
  20394. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20395. * @see http://doc.babylonjs.com/babylon101/shadows
  20396. */
  20397. get: function () {
  20398. return this._receiveShadows;
  20399. },
  20400. set: function (value) {
  20401. if (this._receiveShadows === value) {
  20402. return;
  20403. }
  20404. this._receiveShadows = value;
  20405. this._markSubMeshesAsLightDirty();
  20406. },
  20407. enumerable: true,
  20408. configurable: true
  20409. });
  20410. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20411. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20412. get: function () {
  20413. return this._hasVertexAlpha;
  20414. },
  20415. set: function (value) {
  20416. if (this._hasVertexAlpha === value) {
  20417. return;
  20418. }
  20419. this._hasVertexAlpha = value;
  20420. this._markSubMeshesAsAttributesDirty();
  20421. this._markSubMeshesAsMiscDirty();
  20422. },
  20423. enumerable: true,
  20424. configurable: true
  20425. });
  20426. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20427. /** 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) */
  20428. get: function () {
  20429. return this._useVertexColors;
  20430. },
  20431. set: function (value) {
  20432. if (this._useVertexColors === value) {
  20433. return;
  20434. }
  20435. this._useVertexColors = value;
  20436. this._markSubMeshesAsAttributesDirty();
  20437. },
  20438. enumerable: true,
  20439. configurable: true
  20440. });
  20441. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20442. /**
  20443. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20444. */
  20445. get: function () {
  20446. return this._computeBonesUsingShaders;
  20447. },
  20448. set: function (value) {
  20449. if (this._computeBonesUsingShaders === value) {
  20450. return;
  20451. }
  20452. this._computeBonesUsingShaders = value;
  20453. this._markSubMeshesAsAttributesDirty();
  20454. },
  20455. enumerable: true,
  20456. configurable: true
  20457. });
  20458. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20459. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20460. get: function () {
  20461. return this._numBoneInfluencers;
  20462. },
  20463. set: function (value) {
  20464. if (this._numBoneInfluencers === value) {
  20465. return;
  20466. }
  20467. this._numBoneInfluencers = value;
  20468. this._markSubMeshesAsAttributesDirty();
  20469. },
  20470. enumerable: true,
  20471. configurable: true
  20472. });
  20473. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20474. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20475. get: function () {
  20476. return this._applyFog;
  20477. },
  20478. set: function (value) {
  20479. if (this._applyFog === value) {
  20480. return;
  20481. }
  20482. this._applyFog = value;
  20483. this._markSubMeshesAsMiscDirty();
  20484. },
  20485. enumerable: true,
  20486. configurable: true
  20487. });
  20488. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20489. /**
  20490. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20491. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20492. */
  20493. get: function () {
  20494. return this._layerMask;
  20495. },
  20496. set: function (value) {
  20497. if (value === this._layerMask) {
  20498. return;
  20499. }
  20500. this._layerMask = value;
  20501. this._resyncLightSources();
  20502. },
  20503. enumerable: true,
  20504. configurable: true
  20505. });
  20506. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20507. /**
  20508. * Gets or sets a collision mask used to mask collisions (default is -1).
  20509. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20510. */
  20511. get: function () {
  20512. return this._collisionMask;
  20513. },
  20514. set: function (mask) {
  20515. this._collisionMask = !isNaN(mask) ? mask : -1;
  20516. },
  20517. enumerable: true,
  20518. configurable: true
  20519. });
  20520. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20521. /**
  20522. * Gets or sets the current collision group mask (-1 by default).
  20523. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20524. */
  20525. get: function () {
  20526. return this._collisionGroup;
  20527. },
  20528. set: function (mask) {
  20529. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20530. },
  20531. enumerable: true,
  20532. configurable: true
  20533. });
  20534. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20535. /** @hidden */
  20536. get: function () {
  20537. return null;
  20538. },
  20539. enumerable: true,
  20540. configurable: true
  20541. });
  20542. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20543. get: function () {
  20544. return this._skeleton;
  20545. },
  20546. /**
  20547. * Gets or sets a skeleton to apply skining transformations
  20548. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20549. */
  20550. set: function (value) {
  20551. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20552. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20553. }
  20554. if (value && value.needInitialSkinMatrix) {
  20555. value._registerMeshWithPoseMatrix(this);
  20556. }
  20557. this._skeleton = value;
  20558. if (!this._skeleton) {
  20559. this._bonesTransformMatrices = null;
  20560. }
  20561. this._markSubMeshesAsAttributesDirty();
  20562. },
  20563. enumerable: true,
  20564. configurable: true
  20565. });
  20566. /**
  20567. * Returns the string "AbstractMesh"
  20568. * @returns "AbstractMesh"
  20569. */
  20570. AbstractMesh.prototype.getClassName = function () {
  20571. return "AbstractMesh";
  20572. };
  20573. /**
  20574. * Gets a string representation of the current mesh
  20575. * @param fullDetails defines a boolean indicating if full details must be included
  20576. * @returns a string representation of the current mesh
  20577. */
  20578. AbstractMesh.prototype.toString = function (fullDetails) {
  20579. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20580. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20581. if (this._skeleton) {
  20582. ret += ", skeleton: " + this._skeleton.name;
  20583. }
  20584. if (fullDetails) {
  20585. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20586. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20587. }
  20588. return ret;
  20589. };
  20590. /** @hidden */
  20591. AbstractMesh.prototype._rebuild = function () {
  20592. this.onRebuildObservable.notifyObservers(this);
  20593. if (this._occlusionQuery) {
  20594. this._occlusionQuery = null;
  20595. }
  20596. if (!this.subMeshes) {
  20597. return;
  20598. }
  20599. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20600. var subMesh = _a[_i];
  20601. subMesh._rebuild();
  20602. }
  20603. };
  20604. /** @hidden */
  20605. AbstractMesh.prototype._resyncLightSources = function () {
  20606. this._lightSources.length = 0;
  20607. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20608. var light = _a[_i];
  20609. if (!light.isEnabled()) {
  20610. continue;
  20611. }
  20612. if (light.canAffectMesh(this)) {
  20613. this._lightSources.push(light);
  20614. }
  20615. }
  20616. this._markSubMeshesAsLightDirty();
  20617. };
  20618. /** @hidden */
  20619. AbstractMesh.prototype._resyncLighSource = function (light) {
  20620. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20621. var index = this._lightSources.indexOf(light);
  20622. if (index === -1) {
  20623. if (!isIn) {
  20624. return;
  20625. }
  20626. this._lightSources.push(light);
  20627. }
  20628. else {
  20629. if (isIn) {
  20630. return;
  20631. }
  20632. this._lightSources.splice(index, 1);
  20633. }
  20634. this._markSubMeshesAsLightDirty();
  20635. };
  20636. /** @hidden */
  20637. AbstractMesh.prototype._unBindEffect = function () {
  20638. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20639. var subMesh = _a[_i];
  20640. subMesh.setEffect(null);
  20641. }
  20642. };
  20643. /** @hidden */
  20644. AbstractMesh.prototype._removeLightSource = function (light) {
  20645. var index = this._lightSources.indexOf(light);
  20646. if (index === -1) {
  20647. return;
  20648. }
  20649. this._lightSources.splice(index, 1);
  20650. this._markSubMeshesAsLightDirty();
  20651. };
  20652. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20653. if (!this.subMeshes) {
  20654. return;
  20655. }
  20656. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20657. var subMesh = _a[_i];
  20658. if (subMesh._materialDefines) {
  20659. func(subMesh._materialDefines);
  20660. }
  20661. }
  20662. };
  20663. /** @hidden */
  20664. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20665. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20666. };
  20667. /** @hidden */
  20668. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20669. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20670. };
  20671. /** @hidden */
  20672. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20673. if (!this.subMeshes) {
  20674. return;
  20675. }
  20676. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20677. var subMesh = _a[_i];
  20678. var material = subMesh.getMaterial();
  20679. if (material) {
  20680. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20681. }
  20682. }
  20683. };
  20684. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20685. /**
  20686. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20687. */
  20688. get: function () {
  20689. return this._scaling;
  20690. },
  20691. set: function (newScaling) {
  20692. this._scaling = newScaling;
  20693. if (this.physicsImpostor) {
  20694. this.physicsImpostor.forceUpdate();
  20695. }
  20696. },
  20697. enumerable: true,
  20698. configurable: true
  20699. });
  20700. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20701. // Methods
  20702. /**
  20703. * Returns true if the mesh is blocked. Implemented by child classes
  20704. */
  20705. get: function () {
  20706. return false;
  20707. },
  20708. enumerable: true,
  20709. configurable: true
  20710. });
  20711. /**
  20712. * Returns the mesh itself by default. Implemented by child classes
  20713. * @param camera defines the camera to use to pick the right LOD level
  20714. * @returns the currentAbstractMesh
  20715. */
  20716. AbstractMesh.prototype.getLOD = function (camera) {
  20717. return this;
  20718. };
  20719. /**
  20720. * Returns 0 by default. Implemented by child classes
  20721. * @returns an integer
  20722. */
  20723. AbstractMesh.prototype.getTotalVertices = function () {
  20724. return 0;
  20725. };
  20726. /**
  20727. * Returns null by default. Implemented by child classes
  20728. * @returns null
  20729. */
  20730. AbstractMesh.prototype.getIndices = function () {
  20731. return null;
  20732. };
  20733. /**
  20734. * Returns the array of the requested vertex data kind. Implemented by child classes
  20735. * @param kind defines the vertex data kind to use
  20736. * @returns null
  20737. */
  20738. AbstractMesh.prototype.getVerticesData = function (kind) {
  20739. return null;
  20740. };
  20741. /**
  20742. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20743. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20744. * Note that a new underlying VertexBuffer object is created each call.
  20745. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20746. * @param kind defines vertex data kind:
  20747. * * BABYLON.VertexBuffer.PositionKind
  20748. * * BABYLON.VertexBuffer.UVKind
  20749. * * BABYLON.VertexBuffer.UV2Kind
  20750. * * BABYLON.VertexBuffer.UV3Kind
  20751. * * BABYLON.VertexBuffer.UV4Kind
  20752. * * BABYLON.VertexBuffer.UV5Kind
  20753. * * BABYLON.VertexBuffer.UV6Kind
  20754. * * BABYLON.VertexBuffer.ColorKind
  20755. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20756. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20757. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20758. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20759. * @param data defines the data source
  20760. * @param updatable defines if the data must be flagged as updatable (or static)
  20761. * @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
  20762. * @returns the current mesh
  20763. */
  20764. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20765. return this;
  20766. };
  20767. /**
  20768. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20769. * If the mesh has no geometry, it is simply returned as it is.
  20770. * @param kind defines vertex data kind:
  20771. * * BABYLON.VertexBuffer.PositionKind
  20772. * * BABYLON.VertexBuffer.UVKind
  20773. * * BABYLON.VertexBuffer.UV2Kind
  20774. * * BABYLON.VertexBuffer.UV3Kind
  20775. * * BABYLON.VertexBuffer.UV4Kind
  20776. * * BABYLON.VertexBuffer.UV5Kind
  20777. * * BABYLON.VertexBuffer.UV6Kind
  20778. * * BABYLON.VertexBuffer.ColorKind
  20779. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20780. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20781. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20782. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20783. * @param data defines the data source
  20784. * @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
  20785. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20786. * @returns the current mesh
  20787. */
  20788. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20789. return this;
  20790. };
  20791. /**
  20792. * Sets the mesh indices,
  20793. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20794. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20795. * @param totalVertices Defines the total number of vertices
  20796. * @returns the current mesh
  20797. */
  20798. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20799. return this;
  20800. };
  20801. /**
  20802. * Gets a boolean indicating if specific vertex data is present
  20803. * @param kind defines the vertex data kind to use
  20804. * @returns true is data kind is present
  20805. */
  20806. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20807. return false;
  20808. };
  20809. /**
  20810. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20811. * @returns a BoundingInfo
  20812. */
  20813. AbstractMesh.prototype.getBoundingInfo = function () {
  20814. if (this._masterMesh) {
  20815. return this._masterMesh.getBoundingInfo();
  20816. }
  20817. if (!this._boundingInfo) {
  20818. // this._boundingInfo is being created here
  20819. this._updateBoundingInfo();
  20820. }
  20821. // cannot be null.
  20822. return this._boundingInfo;
  20823. };
  20824. /**
  20825. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20826. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20827. * @returns the current mesh
  20828. */
  20829. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20830. if (includeDescendants === void 0) { includeDescendants = true; }
  20831. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20832. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20833. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20834. if (maxDimension === 0) {
  20835. return this;
  20836. }
  20837. var scale = 1 / maxDimension;
  20838. this.scaling.scaleInPlace(scale);
  20839. return this;
  20840. };
  20841. /**
  20842. * Overwrite the current bounding info
  20843. * @param boundingInfo defines the new bounding info
  20844. * @returns the current mesh
  20845. */
  20846. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20847. this._boundingInfo = boundingInfo;
  20848. return this;
  20849. };
  20850. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20851. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20852. get: function () {
  20853. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20854. },
  20855. enumerable: true,
  20856. configurable: true
  20857. });
  20858. /** @hidden */
  20859. AbstractMesh.prototype._preActivate = function () {
  20860. };
  20861. /** @hidden */
  20862. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20863. };
  20864. /** @hidden */
  20865. AbstractMesh.prototype._activate = function (renderId) {
  20866. this._renderId = renderId;
  20867. };
  20868. /**
  20869. * Gets the current world matrix
  20870. * @returns a Matrix
  20871. */
  20872. AbstractMesh.prototype.getWorldMatrix = function () {
  20873. if (this._masterMesh) {
  20874. return this._masterMesh.getWorldMatrix();
  20875. }
  20876. return _super.prototype.getWorldMatrix.call(this);
  20877. };
  20878. /** @hidden */
  20879. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20880. if (this._masterMesh) {
  20881. return this._masterMesh._getWorldMatrixDeterminant();
  20882. }
  20883. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20884. };
  20885. // ================================== Point of View Movement =================================
  20886. /**
  20887. * Perform relative position change from the point of view of behind the front of the mesh.
  20888. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20889. * Supports definition of mesh facing forward or backward
  20890. * @param amountRight defines the distance on the right axis
  20891. * @param amountUp defines the distance on the up axis
  20892. * @param amountForward defines the distance on the forward axis
  20893. * @returns the current mesh
  20894. */
  20895. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20896. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20897. return this;
  20898. };
  20899. /**
  20900. * Calculate relative position change from the point of view of behind the front of the mesh.
  20901. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20902. * Supports definition of mesh facing forward or backward
  20903. * @param amountRight defines the distance on the right axis
  20904. * @param amountUp defines the distance on the up axis
  20905. * @param amountForward defines the distance on the forward axis
  20906. * @returns the new displacement vector
  20907. */
  20908. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20909. var rotMatrix = new BABYLON.Matrix();
  20910. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20911. rotQuaternion.toRotationMatrix(rotMatrix);
  20912. var translationDelta = BABYLON.Vector3.Zero();
  20913. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20914. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20915. return translationDelta;
  20916. };
  20917. // ================================== Point of View Rotation =================================
  20918. /**
  20919. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20920. * Supports definition of mesh facing forward or backward
  20921. * @param flipBack defines the flip
  20922. * @param twirlClockwise defines the twirl
  20923. * @param tiltRight defines the tilt
  20924. * @returns the current mesh
  20925. */
  20926. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20927. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20928. return this;
  20929. };
  20930. /**
  20931. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20932. * Supports definition of mesh facing forward or backward.
  20933. * @param flipBack defines the flip
  20934. * @param twirlClockwise defines the twirl
  20935. * @param tiltRight defines the tilt
  20936. * @returns the new rotation vector
  20937. */
  20938. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20939. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20940. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20941. };
  20942. /**
  20943. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20944. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20945. * @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
  20946. * @returns the new bounding vectors
  20947. */
  20948. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20949. if (includeDescendants === void 0) { includeDescendants = true; }
  20950. if (predicate === void 0) { predicate = null; }
  20951. // Ensures that all world matrix will be recomputed.
  20952. this.getScene().incrementRenderId();
  20953. this.computeWorldMatrix(true);
  20954. var min;
  20955. var max;
  20956. var boundingInfo = this.getBoundingInfo();
  20957. if (!this.subMeshes) {
  20958. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20959. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20960. }
  20961. else {
  20962. min = boundingInfo.boundingBox.minimumWorld;
  20963. max = boundingInfo.boundingBox.maximumWorld;
  20964. }
  20965. if (includeDescendants) {
  20966. var descendants = this.getDescendants(false);
  20967. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20968. var descendant = descendants_1[_i];
  20969. var childMesh = descendant;
  20970. childMesh.computeWorldMatrix(true);
  20971. // Filters meshes based on custom predicate function.
  20972. if (predicate && !predicate(childMesh)) {
  20973. continue;
  20974. }
  20975. //make sure we have the needed params to get mix and max
  20976. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20977. continue;
  20978. }
  20979. var childBoundingInfo = childMesh.getBoundingInfo();
  20980. var boundingBox = childBoundingInfo.boundingBox;
  20981. var minBox = boundingBox.minimumWorld;
  20982. var maxBox = boundingBox.maximumWorld;
  20983. BABYLON.Tools.CheckExtends(minBox, min, max);
  20984. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20985. }
  20986. }
  20987. return {
  20988. min: min,
  20989. max: max
  20990. };
  20991. };
  20992. /** @hidden */
  20993. AbstractMesh.prototype._updateBoundingInfo = function () {
  20994. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20995. this._boundingInfo.update(this.worldMatrixFromCache);
  20996. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20997. return this;
  20998. };
  20999. /** @hidden */
  21000. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21001. if (!this.subMeshes) {
  21002. return this;
  21003. }
  21004. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21005. var subMesh = this.subMeshes[subIndex];
  21006. if (!subMesh.IsGlobal) {
  21007. subMesh.updateBoundingInfo(matrix);
  21008. }
  21009. }
  21010. return this;
  21011. };
  21012. /** @hidden */
  21013. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21014. // Bounding info
  21015. this._updateBoundingInfo();
  21016. };
  21017. /**
  21018. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21019. * A mesh is in the frustum if its bounding box intersects the frustum
  21020. * @param frustumPlanes defines the frustum to test
  21021. * @returns true if the mesh is in the frustum planes
  21022. */
  21023. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21024. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21025. };
  21026. /**
  21027. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21028. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21029. * @param frustumPlanes defines the frustum to test
  21030. * @returns true if the mesh is completely in the frustum planes
  21031. */
  21032. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21033. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21034. };
  21035. /**
  21036. * True if the mesh intersects another mesh or a SolidParticle object
  21037. * @param mesh defines a target mesh or SolidParticle to test
  21038. * @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)
  21039. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21040. * @returns true if there is an intersection
  21041. */
  21042. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21043. if (precise === void 0) { precise = false; }
  21044. if (!this._boundingInfo || !mesh._boundingInfo) {
  21045. return false;
  21046. }
  21047. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21048. return true;
  21049. }
  21050. if (includeDescendants) {
  21051. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21052. var child = _a[_i];
  21053. if (child.intersectsMesh(mesh, precise, true)) {
  21054. return true;
  21055. }
  21056. }
  21057. }
  21058. return false;
  21059. };
  21060. /**
  21061. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21062. * @param point defines the point to test
  21063. * @returns true if there is an intersection
  21064. */
  21065. AbstractMesh.prototype.intersectsPoint = function (point) {
  21066. if (!this._boundingInfo) {
  21067. return false;
  21068. }
  21069. return this._boundingInfo.intersectsPoint(point);
  21070. };
  21071. /**
  21072. * Gets the position of the current mesh in camera space
  21073. * @param camera defines the camera to use
  21074. * @returns a position
  21075. */
  21076. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21077. if (camera === void 0) { camera = null; }
  21078. if (!camera) {
  21079. camera = this.getScene().activeCamera;
  21080. }
  21081. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21082. };
  21083. /**
  21084. * Returns the distance from the mesh to the active camera
  21085. * @param camera defines the camera to use
  21086. * @returns the distance
  21087. */
  21088. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21089. if (camera === void 0) { camera = null; }
  21090. if (!camera) {
  21091. camera = this.getScene().activeCamera;
  21092. }
  21093. return this.absolutePosition.subtract(camera.position).length();
  21094. };
  21095. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21096. // Collisions
  21097. /**
  21098. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21099. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21100. */
  21101. get: function () {
  21102. return this._checkCollisions;
  21103. },
  21104. set: function (collisionEnabled) {
  21105. this._checkCollisions = collisionEnabled;
  21106. if (this.getScene().workerCollisions) {
  21107. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21108. }
  21109. },
  21110. enumerable: true,
  21111. configurable: true
  21112. });
  21113. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21114. /**
  21115. * Gets Collider object used to compute collisions (not physics)
  21116. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21117. */
  21118. get: function () {
  21119. return this._collider;
  21120. },
  21121. enumerable: true,
  21122. configurable: true
  21123. });
  21124. /**
  21125. * Move the mesh using collision engine
  21126. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21127. * @param displacement defines the requested displacement vector
  21128. * @returns the current mesh
  21129. */
  21130. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21131. var globalPosition = this.getAbsolutePosition();
  21132. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21133. if (!this._collider) {
  21134. this._collider = new BABYLON.Collider();
  21135. }
  21136. this._collider._radius = this.ellipsoid;
  21137. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21138. return this;
  21139. };
  21140. // Collisions
  21141. /** @hidden */
  21142. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21143. this._generatePointsArray();
  21144. if (!this._positions) {
  21145. return this;
  21146. }
  21147. // Transformation
  21148. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21149. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21150. subMesh._lastColliderWorldVertices = [];
  21151. subMesh._trianglePlanes = [];
  21152. var start = subMesh.verticesStart;
  21153. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21154. for (var i = start; i < end; i++) {
  21155. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21156. }
  21157. }
  21158. // Collide
  21159. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21160. if (collider.collisionFound) {
  21161. collider.collidedMesh = this;
  21162. }
  21163. return this;
  21164. };
  21165. /** @hidden */
  21166. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21167. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21168. var len = subMeshes.length;
  21169. for (var index = 0; index < len; index++) {
  21170. var subMesh = subMeshes.data[index];
  21171. // Bounding test
  21172. if (len > 1 && !subMesh._checkCollision(collider))
  21173. continue;
  21174. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21175. }
  21176. return this;
  21177. };
  21178. /** @hidden */
  21179. AbstractMesh.prototype._checkCollision = function (collider) {
  21180. // Bounding box test
  21181. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21182. return this;
  21183. // Transformation matrix
  21184. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  21185. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  21186. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  21187. return this;
  21188. };
  21189. // Picking
  21190. /** @hidden */
  21191. AbstractMesh.prototype._generatePointsArray = function () {
  21192. return false;
  21193. };
  21194. /**
  21195. * Checks if the passed Ray intersects with the mesh
  21196. * @param ray defines the ray to use
  21197. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21198. * @returns the picking info
  21199. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21200. */
  21201. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21202. var pickingInfo = new BABYLON.PickingInfo();
  21203. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21204. return pickingInfo;
  21205. }
  21206. if (!this._generatePointsArray()) {
  21207. return pickingInfo;
  21208. }
  21209. var intersectInfo = null;
  21210. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21211. var len = subMeshes.length;
  21212. for (var index = 0; index < len; index++) {
  21213. var subMesh = subMeshes.data[index];
  21214. // Bounding test
  21215. if (len > 1 && !subMesh.canIntersects(ray))
  21216. continue;
  21217. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21218. if (currentIntersectInfo) {
  21219. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21220. intersectInfo = currentIntersectInfo;
  21221. intersectInfo.subMeshId = index;
  21222. if (fastCheck) {
  21223. break;
  21224. }
  21225. }
  21226. }
  21227. }
  21228. if (intersectInfo) {
  21229. // Get picked point
  21230. var world = this.getWorldMatrix();
  21231. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21232. var direction = ray.direction.clone();
  21233. direction = direction.scale(intersectInfo.distance);
  21234. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21235. var pickedPoint = worldOrigin.add(worldDirection);
  21236. // Return result
  21237. pickingInfo.hit = true;
  21238. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21239. pickingInfo.pickedPoint = pickedPoint;
  21240. pickingInfo.pickedMesh = this;
  21241. pickingInfo.bu = intersectInfo.bu || 0;
  21242. pickingInfo.bv = intersectInfo.bv || 0;
  21243. pickingInfo.faceId = intersectInfo.faceId;
  21244. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21245. return pickingInfo;
  21246. }
  21247. return pickingInfo;
  21248. };
  21249. /**
  21250. * Clones the current mesh
  21251. * @param name defines the mesh name
  21252. * @param newParent defines the new mesh parent
  21253. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21254. * @returns the new mesh
  21255. */
  21256. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21257. return null;
  21258. };
  21259. /**
  21260. * Disposes all the submeshes of the current meshnp
  21261. * @returns the current mesh
  21262. */
  21263. AbstractMesh.prototype.releaseSubMeshes = function () {
  21264. if (this.subMeshes) {
  21265. while (this.subMeshes.length) {
  21266. this.subMeshes[0].dispose();
  21267. }
  21268. }
  21269. else {
  21270. this.subMeshes = new Array();
  21271. }
  21272. return this;
  21273. };
  21274. /**
  21275. * Releases resources associated with this abstract mesh.
  21276. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21277. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21278. */
  21279. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21280. var _this = this;
  21281. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21282. var index;
  21283. // Smart Array Retainers.
  21284. this.getScene().freeActiveMeshes();
  21285. this.getScene().freeRenderingGroups();
  21286. // Action manager
  21287. if (this.actionManager !== undefined && this.actionManager !== null) {
  21288. this.actionManager.dispose();
  21289. this.actionManager = null;
  21290. }
  21291. // Skeleton
  21292. this._skeleton = null;
  21293. // Intersections in progress
  21294. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21295. var other = this._intersectionsInProgress[index];
  21296. var pos = other._intersectionsInProgress.indexOf(this);
  21297. other._intersectionsInProgress.splice(pos, 1);
  21298. }
  21299. this._intersectionsInProgress = [];
  21300. // Lights
  21301. var lights = this.getScene().lights;
  21302. lights.forEach(function (light) {
  21303. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21304. if (meshIndex !== -1) {
  21305. light.includedOnlyMeshes.splice(meshIndex, 1);
  21306. }
  21307. meshIndex = light.excludedMeshes.indexOf(_this);
  21308. if (meshIndex !== -1) {
  21309. light.excludedMeshes.splice(meshIndex, 1);
  21310. }
  21311. // Shadow generators
  21312. var generator = light.getShadowGenerator();
  21313. if (generator) {
  21314. var shadowMap = generator.getShadowMap();
  21315. if (shadowMap && shadowMap.renderList) {
  21316. meshIndex = shadowMap.renderList.indexOf(_this);
  21317. if (meshIndex !== -1) {
  21318. shadowMap.renderList.splice(meshIndex, 1);
  21319. }
  21320. }
  21321. }
  21322. });
  21323. // SubMeshes
  21324. if (this.getClassName() !== "InstancedMesh") {
  21325. this.releaseSubMeshes();
  21326. }
  21327. // Query
  21328. var engine = this.getScene().getEngine();
  21329. if (this._occlusionQuery) {
  21330. this.isOcclusionQueryInProgress = false;
  21331. engine.deleteQuery(this._occlusionQuery);
  21332. this._occlusionQuery = null;
  21333. }
  21334. // Engine
  21335. engine.wipeCaches();
  21336. // Remove from scene
  21337. this.getScene().removeMesh(this);
  21338. if (disposeMaterialAndTextures) {
  21339. if (this.material) {
  21340. this.material.dispose(false, true);
  21341. }
  21342. }
  21343. if (!doNotRecurse) {
  21344. // Particles
  21345. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21346. if (this.getScene().particleSystems[index].emitter === this) {
  21347. this.getScene().particleSystems[index].dispose();
  21348. index--;
  21349. }
  21350. }
  21351. }
  21352. // facet data
  21353. if (this._facetData.facetDataEnabled) {
  21354. this.disableFacetData();
  21355. }
  21356. this.onAfterWorldMatrixUpdateObservable.clear();
  21357. this.onCollideObservable.clear();
  21358. this.onCollisionPositionChangeObservable.clear();
  21359. this.onRebuildObservable.clear();
  21360. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21361. };
  21362. /**
  21363. * Adds the passed mesh as a child to the current mesh
  21364. * @param mesh defines the child mesh
  21365. * @returns the current mesh
  21366. */
  21367. AbstractMesh.prototype.addChild = function (mesh) {
  21368. mesh.setParent(this);
  21369. return this;
  21370. };
  21371. /**
  21372. * Removes the passed mesh from the current mesh children list
  21373. * @param mesh defines the child mesh
  21374. * @returns the current mesh
  21375. */
  21376. AbstractMesh.prototype.removeChild = function (mesh) {
  21377. mesh.setParent(null);
  21378. return this;
  21379. };
  21380. // Facet data
  21381. /** @hidden */
  21382. AbstractMesh.prototype._initFacetData = function () {
  21383. var data = this._facetData;
  21384. if (!data.facetNormals) {
  21385. data.facetNormals = new Array();
  21386. }
  21387. if (!data.facetPositions) {
  21388. data.facetPositions = new Array();
  21389. }
  21390. if (!data.facetPartitioning) {
  21391. data.facetPartitioning = new Array();
  21392. }
  21393. data.facetNb = (this.getIndices().length / 3) | 0;
  21394. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21395. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21396. for (var f = 0; f < data.facetNb; f++) {
  21397. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21398. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21399. }
  21400. data.facetDataEnabled = true;
  21401. return this;
  21402. };
  21403. /**
  21404. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21405. * This method can be called within the render loop.
  21406. * 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
  21407. * @returns the current mesh
  21408. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21409. */
  21410. AbstractMesh.prototype.updateFacetData = function () {
  21411. var data = this._facetData;
  21412. if (!data.facetDataEnabled) {
  21413. this._initFacetData();
  21414. }
  21415. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21416. var indices = this.getIndices();
  21417. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21418. var bInfo = this.getBoundingInfo();
  21419. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  21420. // init arrays, matrix and sort function on first call
  21421. data.facetDepthSortEnabled = true;
  21422. if (indices instanceof Uint16Array) {
  21423. data.depthSortedIndices = new Uint16Array(indices);
  21424. }
  21425. else if (indices instanceof Uint32Array) {
  21426. data.depthSortedIndices = new Uint32Array(indices);
  21427. }
  21428. else {
  21429. var needs32bits = false;
  21430. for (var i = 0; i < indices.length; i++) {
  21431. if (indices[i] > 65535) {
  21432. needs32bits = true;
  21433. break;
  21434. }
  21435. }
  21436. if (needs32bits) {
  21437. data.depthSortedIndices = new Uint32Array(indices);
  21438. }
  21439. else {
  21440. data.depthSortedIndices = new Uint16Array(indices);
  21441. }
  21442. }
  21443. data.facetDepthSortFunction = function (f1, f2) {
  21444. return (f2.sqDistance - f1.sqDistance);
  21445. };
  21446. if (!data.facetDepthSortFrom) {
  21447. var camera = this.getScene().activeCamera;
  21448. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21449. }
  21450. data.depthSortedFacets = [];
  21451. for (var f = 0; f < data.facetNb; f++) {
  21452. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21453. data.depthSortedFacets.push(depthSortedFacet);
  21454. }
  21455. data.invertedMatrix = BABYLON.Matrix.Identity();
  21456. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21457. }
  21458. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21459. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21460. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21461. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  21462. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  21463. data.subDiv.max = data.partitioningSubdivisions;
  21464. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21465. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  21466. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  21467. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  21468. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  21469. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  21470. // set the parameters for ComputeNormals()
  21471. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  21472. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  21473. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21474. data.facetParameters.bInfo = bInfo;
  21475. data.facetParameters.bbSize = data.bbSize;
  21476. data.facetParameters.subDiv = data.subDiv;
  21477. data.facetParameters.ratio = this.partitioningBBoxRatio;
  21478. data.facetParameters.depthSort = data.facetDepthSort;
  21479. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21480. this.computeWorldMatrix(true);
  21481. this._worldMatrix.invertToRef(data.invertedMatrix);
  21482. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  21483. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  21484. }
  21485. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  21486. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  21487. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21488. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  21489. var l = (data.depthSortedIndices.length / 3) | 0;
  21490. for (var f = 0; f < l; f++) {
  21491. var sind = data.depthSortedFacets[f].ind;
  21492. data.depthSortedIndices[f * 3] = indices[sind];
  21493. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21494. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21495. }
  21496. this.updateIndices(data.depthSortedIndices);
  21497. }
  21498. return this;
  21499. };
  21500. /**
  21501. * Returns the facetLocalNormals array.
  21502. * The normals are expressed in the mesh local spac
  21503. * @returns an array of Vector3
  21504. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21505. */
  21506. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21507. if (!this._facetData.facetNormals) {
  21508. this.updateFacetData();
  21509. }
  21510. return this._facetData.facetNormals;
  21511. };
  21512. /**
  21513. * Returns the facetLocalPositions array.
  21514. * The facet positions are expressed in the mesh local space
  21515. * @returns an array of Vector3
  21516. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21517. */
  21518. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21519. if (!this._facetData.facetPositions) {
  21520. this.updateFacetData();
  21521. }
  21522. return this._facetData.facetPositions;
  21523. };
  21524. /**
  21525. * Returns the facetLocalPartioning array
  21526. * @returns an array of array of numbers
  21527. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21528. */
  21529. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21530. if (!this._facetData.facetPartitioning) {
  21531. this.updateFacetData();
  21532. }
  21533. return this._facetData.facetPartitioning;
  21534. };
  21535. /**
  21536. * Returns the i-th facet position in the world system.
  21537. * This method allocates a new Vector3 per call
  21538. * @param i defines the facet index
  21539. * @returns a new Vector3
  21540. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21541. */
  21542. AbstractMesh.prototype.getFacetPosition = function (i) {
  21543. var pos = BABYLON.Vector3.Zero();
  21544. this.getFacetPositionToRef(i, pos);
  21545. return pos;
  21546. };
  21547. /**
  21548. * Sets the reference Vector3 with the i-th facet position in the world system
  21549. * @param i defines the facet index
  21550. * @param ref defines the target vector
  21551. * @returns the current mesh
  21552. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21553. */
  21554. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21555. var localPos = (this.getFacetLocalPositions())[i];
  21556. var world = this.getWorldMatrix();
  21557. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21558. return this;
  21559. };
  21560. /**
  21561. * Returns the i-th facet normal in the world system.
  21562. * This method allocates a new Vector3 per call
  21563. * @param i defines the facet index
  21564. * @returns a new Vector3
  21565. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21566. */
  21567. AbstractMesh.prototype.getFacetNormal = function (i) {
  21568. var norm = BABYLON.Vector3.Zero();
  21569. this.getFacetNormalToRef(i, norm);
  21570. return norm;
  21571. };
  21572. /**
  21573. * Sets the reference Vector3 with the i-th facet normal in the world system
  21574. * @param i defines the facet index
  21575. * @param ref defines the target vector
  21576. * @returns the current mesh
  21577. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21578. */
  21579. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21580. var localNorm = (this.getFacetLocalNormals())[i];
  21581. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21582. return this;
  21583. };
  21584. /**
  21585. * 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)
  21586. * @param x defines x coordinate
  21587. * @param y defines y coordinate
  21588. * @param z defines z coordinate
  21589. * @returns the array of facet indexes
  21590. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21591. */
  21592. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21593. var bInfo = this.getBoundingInfo();
  21594. var data = this._facetData;
  21595. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  21596. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  21597. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  21598. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  21599. return null;
  21600. }
  21601. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  21602. };
  21603. /**
  21604. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21605. * @param projected sets as the (x,y,z) world projection on the facet
  21606. * @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
  21607. * @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
  21608. * @param x defines x coordinate
  21609. * @param y defines y coordinate
  21610. * @param z defines z coordinate
  21611. * @returns the face index if found (or null instead)
  21612. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21613. */
  21614. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21615. if (checkFace === void 0) { checkFace = false; }
  21616. if (facing === void 0) { facing = true; }
  21617. var world = this.getWorldMatrix();
  21618. var invMat = BABYLON.Tmp.Matrix[5];
  21619. world.invertToRef(invMat);
  21620. var invVect = BABYLON.Tmp.Vector3[8];
  21621. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21622. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21623. if (projected) {
  21624. // tranform the local computed projected vector to world coordinates
  21625. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21626. }
  21627. return closest;
  21628. };
  21629. /**
  21630. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21631. * @param projected sets as the (x,y,z) local projection on the facet
  21632. * @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
  21633. * @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
  21634. * @param x defines x coordinate
  21635. * @param y defines y coordinate
  21636. * @param z defines z coordinate
  21637. * @returns the face index if found (or null instead)
  21638. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21639. */
  21640. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21641. if (checkFace === void 0) { checkFace = false; }
  21642. if (facing === void 0) { facing = true; }
  21643. var closest = null;
  21644. var tmpx = 0.0;
  21645. var tmpy = 0.0;
  21646. var tmpz = 0.0;
  21647. var d = 0.0; // tmp dot facet normal * facet position
  21648. var t0 = 0.0;
  21649. var projx = 0.0;
  21650. var projy = 0.0;
  21651. var projz = 0.0;
  21652. // Get all the facets in the same partitioning block than (x, y, z)
  21653. var facetPositions = this.getFacetLocalPositions();
  21654. var facetNormals = this.getFacetLocalNormals();
  21655. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21656. if (!facetsInBlock) {
  21657. return null;
  21658. }
  21659. // Get the closest facet to (x, y, z)
  21660. var shortest = Number.MAX_VALUE; // init distance vars
  21661. var tmpDistance = shortest;
  21662. var fib; // current facet in the block
  21663. var norm; // current facet normal
  21664. var p0; // current facet barycenter position
  21665. // loop on all the facets in the current partitioning block
  21666. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21667. fib = facetsInBlock[idx];
  21668. norm = facetNormals[fib];
  21669. p0 = facetPositions[fib];
  21670. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21671. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21672. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21673. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21674. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21675. projx = x + norm.x * t0;
  21676. projy = y + norm.y * t0;
  21677. projz = z + norm.z * t0;
  21678. tmpx = projx - x;
  21679. tmpy = projy - y;
  21680. tmpz = projz - z;
  21681. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21682. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21683. shortest = tmpDistance;
  21684. closest = fib;
  21685. if (projected) {
  21686. projected.x = projx;
  21687. projected.y = projy;
  21688. projected.z = projz;
  21689. }
  21690. }
  21691. }
  21692. }
  21693. return closest;
  21694. };
  21695. /**
  21696. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21697. * @returns the parameters
  21698. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21699. */
  21700. AbstractMesh.prototype.getFacetDataParameters = function () {
  21701. return this._facetData.facetParameters;
  21702. };
  21703. /**
  21704. * Disables the feature FacetData and frees the related memory
  21705. * @returns the current mesh
  21706. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21707. */
  21708. AbstractMesh.prototype.disableFacetData = function () {
  21709. if (this._facetData.facetDataEnabled) {
  21710. this._facetData.facetDataEnabled = false;
  21711. this._facetData.facetPositions = new Array();
  21712. this._facetData.facetNormals = new Array();
  21713. this._facetData.facetPartitioning = new Array();
  21714. this._facetData.facetParameters = null;
  21715. this._facetData.depthSortedIndices = new Uint32Array(0);
  21716. }
  21717. return this;
  21718. };
  21719. /**
  21720. * Updates the AbstractMesh indices array
  21721. * @param indices defines the data source
  21722. * @returns the current mesh
  21723. */
  21724. AbstractMesh.prototype.updateIndices = function (indices) {
  21725. return this;
  21726. };
  21727. /**
  21728. * Creates new normals data for the mesh
  21729. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21730. * @returns the current mesh
  21731. */
  21732. AbstractMesh.prototype.createNormals = function (updatable) {
  21733. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21734. var indices = this.getIndices();
  21735. var normals;
  21736. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21737. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21738. }
  21739. else {
  21740. normals = [];
  21741. }
  21742. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21743. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21744. return this;
  21745. };
  21746. /**
  21747. * Align the mesh with a normal
  21748. * @param normal defines the normal to use
  21749. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21750. * @returns the current mesh
  21751. */
  21752. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21753. if (!upDirection) {
  21754. upDirection = BABYLON.Axis.Y;
  21755. }
  21756. var axisX = BABYLON.Tmp.Vector3[0];
  21757. var axisZ = BABYLON.Tmp.Vector3[1];
  21758. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21759. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21760. if (this.rotationQuaternion) {
  21761. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21762. }
  21763. else {
  21764. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21765. }
  21766. return this;
  21767. };
  21768. /** @hidden */
  21769. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21770. return false;
  21771. };
  21772. /** No occlusion */
  21773. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21774. /** Occlusion set to optimisitic */
  21775. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21776. /** Occlusion set to strict */
  21777. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21778. /** Use an accurante occlusion algorithm */
  21779. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21780. /** Use a conservative occlusion algorithm */
  21781. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21782. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21783. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21784. /** Culling strategy with bounding sphere only and then frustum culling */
  21785. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21786. return AbstractMesh;
  21787. }(BABYLON.TransformNode));
  21788. BABYLON.AbstractMesh = AbstractMesh;
  21789. })(BABYLON || (BABYLON = {}));
  21790. //# sourceMappingURL=babylon.abstractMesh.js.map
  21791. var BABYLON;
  21792. (function (BABYLON) {
  21793. /**
  21794. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21795. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21796. * 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.
  21797. */
  21798. var Light = /** @class */ (function (_super) {
  21799. __extends(Light, _super);
  21800. /**
  21801. * Creates a Light object in the scene.
  21802. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21803. * @param name The firendly name of the light
  21804. * @param scene The scene the light belongs too
  21805. */
  21806. function Light(name, scene) {
  21807. var _this = _super.call(this, name, scene) || this;
  21808. /**
  21809. * Diffuse gives the basic color to an object.
  21810. */
  21811. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21812. /**
  21813. * Specular produces a highlight color on an object.
  21814. * Note: This is note affecting PBR materials.
  21815. */
  21816. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21817. /**
  21818. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21819. * falling off base on range or angle.
  21820. * This can be set to any values in Light.FALLOFF_x.
  21821. *
  21822. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21823. * other types of materials.
  21824. */
  21825. _this.falloffType = Light.FALLOFF_DEFAULT;
  21826. /**
  21827. * Strength of the light.
  21828. * Note: By default it is define in the framework own unit.
  21829. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21830. */
  21831. _this.intensity = 1.0;
  21832. _this._range = Number.MAX_VALUE;
  21833. _this._inverseSquaredRange = 0;
  21834. /**
  21835. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21836. * of light.
  21837. */
  21838. _this._photometricScale = 1.0;
  21839. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21840. _this._radius = 0.00001;
  21841. /**
  21842. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21843. * exceeding the number allowed of the materials.
  21844. */
  21845. _this.renderPriority = 0;
  21846. _this._shadowEnabled = true;
  21847. _this._excludeWithLayerMask = 0;
  21848. _this._includeOnlyWithLayerMask = 0;
  21849. _this._lightmapMode = 0;
  21850. /**
  21851. * @hidden Internal use only.
  21852. */
  21853. _this._excludedMeshesIds = new Array();
  21854. /**
  21855. * @hidden Internal use only.
  21856. */
  21857. _this._includedOnlyMeshesIds = new Array();
  21858. _this.getScene().addLight(_this);
  21859. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21860. _this._buildUniformLayout();
  21861. _this.includedOnlyMeshes = new Array();
  21862. _this.excludedMeshes = new Array();
  21863. _this._resyncMeshes();
  21864. return _this;
  21865. }
  21866. Object.defineProperty(Light.prototype, "range", {
  21867. /**
  21868. * Defines how far from the source the light is impacting in scene units.
  21869. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21870. */
  21871. get: function () {
  21872. return this._range;
  21873. },
  21874. /**
  21875. * Defines how far from the source the light is impacting in scene units.
  21876. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21877. */
  21878. set: function (value) {
  21879. this._range = value;
  21880. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21881. },
  21882. enumerable: true,
  21883. configurable: true
  21884. });
  21885. Object.defineProperty(Light.prototype, "intensityMode", {
  21886. /**
  21887. * Gets the photometric scale used to interpret the intensity.
  21888. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21889. */
  21890. get: function () {
  21891. return this._intensityMode;
  21892. },
  21893. /**
  21894. * Sets the photometric scale used to interpret the intensity.
  21895. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21896. */
  21897. set: function (value) {
  21898. this._intensityMode = value;
  21899. this._computePhotometricScale();
  21900. },
  21901. enumerable: true,
  21902. configurable: true
  21903. });
  21904. ;
  21905. ;
  21906. Object.defineProperty(Light.prototype, "radius", {
  21907. /**
  21908. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21909. */
  21910. get: function () {
  21911. return this._radius;
  21912. },
  21913. /**
  21914. * sets the light radius used by PBR Materials to simulate soft area lights.
  21915. */
  21916. set: function (value) {
  21917. this._radius = value;
  21918. this._computePhotometricScale();
  21919. },
  21920. enumerable: true,
  21921. configurable: true
  21922. });
  21923. ;
  21924. ;
  21925. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21926. /**
  21927. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21928. * the current shadow generator.
  21929. */
  21930. get: function () {
  21931. return this._shadowEnabled;
  21932. },
  21933. /**
  21934. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21935. * the current shadow generator.
  21936. */
  21937. set: function (value) {
  21938. if (this._shadowEnabled === value) {
  21939. return;
  21940. }
  21941. this._shadowEnabled = value;
  21942. this._markMeshesAsLightDirty();
  21943. },
  21944. enumerable: true,
  21945. configurable: true
  21946. });
  21947. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21948. /**
  21949. * Gets the only meshes impacted by this light.
  21950. */
  21951. get: function () {
  21952. return this._includedOnlyMeshes;
  21953. },
  21954. /**
  21955. * Sets the only meshes impacted by this light.
  21956. */
  21957. set: function (value) {
  21958. this._includedOnlyMeshes = value;
  21959. this._hookArrayForIncludedOnly(value);
  21960. },
  21961. enumerable: true,
  21962. configurable: true
  21963. });
  21964. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21965. /**
  21966. * Gets the meshes not impacted by this light.
  21967. */
  21968. get: function () {
  21969. return this._excludedMeshes;
  21970. },
  21971. /**
  21972. * Sets the meshes not impacted by this light.
  21973. */
  21974. set: function (value) {
  21975. this._excludedMeshes = value;
  21976. this._hookArrayForExcluded(value);
  21977. },
  21978. enumerable: true,
  21979. configurable: true
  21980. });
  21981. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21982. /**
  21983. * Gets the layer id use to find what meshes are not impacted by the light.
  21984. * Inactive if 0
  21985. */
  21986. get: function () {
  21987. return this._excludeWithLayerMask;
  21988. },
  21989. /**
  21990. * Sets the layer id use to find what meshes are not impacted by the light.
  21991. * Inactive if 0
  21992. */
  21993. set: function (value) {
  21994. this._excludeWithLayerMask = value;
  21995. this._resyncMeshes();
  21996. },
  21997. enumerable: true,
  21998. configurable: true
  21999. });
  22000. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22001. /**
  22002. * Gets the layer id use to find what meshes are impacted by the light.
  22003. * Inactive if 0
  22004. */
  22005. get: function () {
  22006. return this._includeOnlyWithLayerMask;
  22007. },
  22008. /**
  22009. * Sets the layer id use to find what meshes are impacted by the light.
  22010. * Inactive if 0
  22011. */
  22012. set: function (value) {
  22013. this._includeOnlyWithLayerMask = value;
  22014. this._resyncMeshes();
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. Object.defineProperty(Light.prototype, "lightmapMode", {
  22020. /**
  22021. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22022. */
  22023. get: function () {
  22024. return this._lightmapMode;
  22025. },
  22026. /**
  22027. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22028. */
  22029. set: function (value) {
  22030. if (this._lightmapMode === value) {
  22031. return;
  22032. }
  22033. this._lightmapMode = value;
  22034. this._markMeshesAsLightDirty();
  22035. },
  22036. enumerable: true,
  22037. configurable: true
  22038. });
  22039. /**
  22040. * Returns the string "Light".
  22041. * @returns the class name
  22042. */
  22043. Light.prototype.getClassName = function () {
  22044. return "Light";
  22045. };
  22046. /**
  22047. * Converts the light information to a readable string for debug purpose.
  22048. * @param fullDetails Supports for multiple levels of logging within scene loading
  22049. * @returns the human readable light info
  22050. */
  22051. Light.prototype.toString = function (fullDetails) {
  22052. var ret = "Name: " + this.name;
  22053. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22054. if (this.animations) {
  22055. for (var i = 0; i < this.animations.length; i++) {
  22056. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22057. }
  22058. }
  22059. if (fullDetails) {
  22060. }
  22061. return ret;
  22062. };
  22063. /** @hidden */
  22064. Light.prototype._syncParentEnabledState = function () {
  22065. _super.prototype._syncParentEnabledState.call(this);
  22066. this._resyncMeshes();
  22067. };
  22068. /**
  22069. * Set the enabled state of this node.
  22070. * @param value - the new enabled state
  22071. */
  22072. Light.prototype.setEnabled = function (value) {
  22073. _super.prototype.setEnabled.call(this, value);
  22074. this._resyncMeshes();
  22075. };
  22076. /**
  22077. * Returns the Light associated shadow generator if any.
  22078. * @return the associated shadow generator.
  22079. */
  22080. Light.prototype.getShadowGenerator = function () {
  22081. return this._shadowGenerator;
  22082. };
  22083. /**
  22084. * Returns a Vector3, the absolute light position in the World.
  22085. * @returns the world space position of the light
  22086. */
  22087. Light.prototype.getAbsolutePosition = function () {
  22088. return BABYLON.Vector3.Zero();
  22089. };
  22090. /**
  22091. * Specifies if the light will affect the passed mesh.
  22092. * @param mesh The mesh to test against the light
  22093. * @return true the mesh is affected otherwise, false.
  22094. */
  22095. Light.prototype.canAffectMesh = function (mesh) {
  22096. if (!mesh) {
  22097. return true;
  22098. }
  22099. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22100. return false;
  22101. }
  22102. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22103. return false;
  22104. }
  22105. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22106. return false;
  22107. }
  22108. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22109. return false;
  22110. }
  22111. return true;
  22112. };
  22113. /**
  22114. * Sort function to order lights for rendering.
  22115. * @param a First Light object to compare to second.
  22116. * @param b Second Light object to compare first.
  22117. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22118. */
  22119. Light.CompareLightsPriority = function (a, b) {
  22120. //shadow-casting lights have priority over non-shadow-casting lights
  22121. //the renderPrioirty is a secondary sort criterion
  22122. if (a.shadowEnabled !== b.shadowEnabled) {
  22123. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22124. }
  22125. return b.renderPriority - a.renderPriority;
  22126. };
  22127. /**
  22128. * Releases resources associated with this node.
  22129. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22130. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22131. */
  22132. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22133. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22134. if (this._shadowGenerator) {
  22135. this._shadowGenerator.dispose();
  22136. this._shadowGenerator = null;
  22137. }
  22138. // Animations
  22139. this.getScene().stopAnimation(this);
  22140. // Remove from meshes
  22141. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22142. var mesh = _a[_i];
  22143. mesh._removeLightSource(this);
  22144. }
  22145. this._uniformBuffer.dispose();
  22146. // Remove from scene
  22147. this.getScene().removeLight(this);
  22148. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22149. };
  22150. /**
  22151. * Returns the light type ID (integer).
  22152. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22153. */
  22154. Light.prototype.getTypeID = function () {
  22155. return 0;
  22156. };
  22157. /**
  22158. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22159. * @returns the scaled intensity in intensity mode unit
  22160. */
  22161. Light.prototype.getScaledIntensity = function () {
  22162. return this._photometricScale * this.intensity;
  22163. };
  22164. /**
  22165. * Returns a new Light object, named "name", from the current one.
  22166. * @param name The name of the cloned light
  22167. * @returns the new created light
  22168. */
  22169. Light.prototype.clone = function (name) {
  22170. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22171. if (!constructor) {
  22172. return null;
  22173. }
  22174. return BABYLON.SerializationHelper.Clone(constructor, this);
  22175. };
  22176. /**
  22177. * Serializes the current light into a Serialization object.
  22178. * @returns the serialized object.
  22179. */
  22180. Light.prototype.serialize = function () {
  22181. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22182. // Type
  22183. serializationObject.type = this.getTypeID();
  22184. // Parent
  22185. if (this.parent) {
  22186. serializationObject.parentId = this.parent.id;
  22187. }
  22188. // Inclusion / exclusions
  22189. if (this.excludedMeshes.length > 0) {
  22190. serializationObject.excludedMeshesIds = [];
  22191. this.excludedMeshes.forEach(function (mesh) {
  22192. serializationObject.excludedMeshesIds.push(mesh.id);
  22193. });
  22194. }
  22195. if (this.includedOnlyMeshes.length > 0) {
  22196. serializationObject.includedOnlyMeshesIds = [];
  22197. this.includedOnlyMeshes.forEach(function (mesh) {
  22198. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22199. });
  22200. }
  22201. // Animations
  22202. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22203. serializationObject.ranges = this.serializeAnimationRanges();
  22204. return serializationObject;
  22205. };
  22206. /**
  22207. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22208. * This new light is named "name" and added to the passed scene.
  22209. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22210. * @param name The friendly name of the light
  22211. * @param scene The scene the new light will belong to
  22212. * @returns the constructor function
  22213. */
  22214. Light.GetConstructorFromName = function (type, name, scene) {
  22215. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22216. if (constructorFunc) {
  22217. return constructorFunc;
  22218. }
  22219. // Default to no light for none present once.
  22220. return null;
  22221. };
  22222. /**
  22223. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22224. * @param parsedLight The JSON representation of the light
  22225. * @param scene The scene to create the parsed light in
  22226. * @returns the created light after parsing
  22227. */
  22228. Light.Parse = function (parsedLight, scene) {
  22229. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22230. if (!constructor) {
  22231. return null;
  22232. }
  22233. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22234. // Inclusion / exclusions
  22235. if (parsedLight.excludedMeshesIds) {
  22236. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22237. }
  22238. if (parsedLight.includedOnlyMeshesIds) {
  22239. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22240. }
  22241. // Parent
  22242. if (parsedLight.parentId) {
  22243. light._waitingParentId = parsedLight.parentId;
  22244. }
  22245. // Animations
  22246. if (parsedLight.animations) {
  22247. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22248. var parsedAnimation = parsedLight.animations[animationIndex];
  22249. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22250. }
  22251. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22252. }
  22253. if (parsedLight.autoAnimate) {
  22254. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22255. }
  22256. return light;
  22257. };
  22258. Light.prototype._hookArrayForExcluded = function (array) {
  22259. var _this = this;
  22260. var oldPush = array.push;
  22261. array.push = function () {
  22262. var items = [];
  22263. for (var _i = 0; _i < arguments.length; _i++) {
  22264. items[_i] = arguments[_i];
  22265. }
  22266. var result = oldPush.apply(array, items);
  22267. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22268. var item = items_1[_a];
  22269. item._resyncLighSource(_this);
  22270. }
  22271. return result;
  22272. };
  22273. var oldSplice = array.splice;
  22274. array.splice = function (index, deleteCount) {
  22275. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22276. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22277. var item = deleted_1[_i];
  22278. item._resyncLighSource(_this);
  22279. }
  22280. return deleted;
  22281. };
  22282. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22283. var item = array_1[_i];
  22284. item._resyncLighSource(this);
  22285. }
  22286. };
  22287. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22288. var _this = this;
  22289. var oldPush = array.push;
  22290. array.push = function () {
  22291. var items = [];
  22292. for (var _i = 0; _i < arguments.length; _i++) {
  22293. items[_i] = arguments[_i];
  22294. }
  22295. var result = oldPush.apply(array, items);
  22296. _this._resyncMeshes();
  22297. return result;
  22298. };
  22299. var oldSplice = array.splice;
  22300. array.splice = function (index, deleteCount) {
  22301. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22302. _this._resyncMeshes();
  22303. return deleted;
  22304. };
  22305. this._resyncMeshes();
  22306. };
  22307. Light.prototype._resyncMeshes = function () {
  22308. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22309. var mesh = _a[_i];
  22310. mesh._resyncLighSource(this);
  22311. }
  22312. };
  22313. /**
  22314. * Forces the meshes to update their light related information in their rendering used effects
  22315. * @hidden Internal Use Only
  22316. */
  22317. Light.prototype._markMeshesAsLightDirty = function () {
  22318. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22319. var mesh = _a[_i];
  22320. if (mesh._lightSources.indexOf(this) !== -1) {
  22321. mesh._markSubMeshesAsLightDirty();
  22322. }
  22323. }
  22324. };
  22325. /**
  22326. * Recomputes the cached photometric scale if needed.
  22327. */
  22328. Light.prototype._computePhotometricScale = function () {
  22329. this._photometricScale = this._getPhotometricScale();
  22330. this.getScene().resetCachedMaterial();
  22331. };
  22332. /**
  22333. * Returns the Photometric Scale according to the light type and intensity mode.
  22334. */
  22335. Light.prototype._getPhotometricScale = function () {
  22336. var photometricScale = 0.0;
  22337. var lightTypeID = this.getTypeID();
  22338. //get photometric mode
  22339. var photometricMode = this.intensityMode;
  22340. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22341. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22342. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22343. }
  22344. else {
  22345. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22346. }
  22347. }
  22348. //compute photometric scale
  22349. switch (lightTypeID) {
  22350. case Light.LIGHTTYPEID_POINTLIGHT:
  22351. case Light.LIGHTTYPEID_SPOTLIGHT:
  22352. switch (photometricMode) {
  22353. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22354. photometricScale = 1.0 / (4.0 * Math.PI);
  22355. break;
  22356. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22357. photometricScale = 1.0;
  22358. break;
  22359. case Light.INTENSITYMODE_LUMINANCE:
  22360. photometricScale = this.radius * this.radius;
  22361. break;
  22362. }
  22363. break;
  22364. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22365. switch (photometricMode) {
  22366. case Light.INTENSITYMODE_ILLUMINANCE:
  22367. photometricScale = 1.0;
  22368. break;
  22369. case Light.INTENSITYMODE_LUMINANCE:
  22370. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22371. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22372. var apexAngleRadians = this.radius;
  22373. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22374. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22375. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22376. photometricScale = solidAngle;
  22377. break;
  22378. }
  22379. break;
  22380. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22381. // No fall off in hemisperic light.
  22382. photometricScale = 1.0;
  22383. break;
  22384. }
  22385. return photometricScale;
  22386. };
  22387. /**
  22388. * Reorder the light in the scene according to their defined priority.
  22389. * @hidden Internal Use Only
  22390. */
  22391. Light.prototype._reorderLightsInScene = function () {
  22392. var scene = this.getScene();
  22393. if (this._renderPriority != 0) {
  22394. scene.requireLightSorting = true;
  22395. }
  22396. this.getScene().sortLightsByPriority();
  22397. };
  22398. /**
  22399. * Falloff Default: light is falling off following the material specification:
  22400. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22401. */
  22402. Light.FALLOFF_DEFAULT = 0;
  22403. /**
  22404. * Falloff Physical: light is falling off following the inverse squared distance law.
  22405. */
  22406. Light.FALLOFF_PHYSICAL = 1;
  22407. /**
  22408. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22409. * to enhance interoperability with other engines.
  22410. */
  22411. Light.FALLOFF_GLTF = 2;
  22412. /**
  22413. * Falloff Standard: light is falling off like in the standard material
  22414. * to enhance interoperability with other materials.
  22415. */
  22416. Light.FALLOFF_STANDARD = 3;
  22417. //lightmapMode Consts
  22418. /**
  22419. * If every light affecting the material is in this lightmapMode,
  22420. * material.lightmapTexture adds or multiplies
  22421. * (depends on material.useLightmapAsShadowmap)
  22422. * after every other light calculations.
  22423. */
  22424. Light.LIGHTMAP_DEFAULT = 0;
  22425. /**
  22426. * material.lightmapTexture as only diffuse lighting from this light
  22427. * adds only specular lighting from this light
  22428. * adds dynamic shadows
  22429. */
  22430. Light.LIGHTMAP_SPECULAR = 1;
  22431. /**
  22432. * material.lightmapTexture as only lighting
  22433. * no light calculation from this light
  22434. * only adds dynamic shadows from this light
  22435. */
  22436. Light.LIGHTMAP_SHADOWSONLY = 2;
  22437. // Intensity Mode Consts
  22438. /**
  22439. * Each light type uses the default quantity according to its type:
  22440. * point/spot lights use luminous intensity
  22441. * directional lights use illuminance
  22442. */
  22443. Light.INTENSITYMODE_AUTOMATIC = 0;
  22444. /**
  22445. * lumen (lm)
  22446. */
  22447. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22448. /**
  22449. * candela (lm/sr)
  22450. */
  22451. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22452. /**
  22453. * lux (lm/m^2)
  22454. */
  22455. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22456. /**
  22457. * nit (cd/m^2)
  22458. */
  22459. Light.INTENSITYMODE_LUMINANCE = 4;
  22460. // Light types ids const.
  22461. /**
  22462. * Light type const id of the point light.
  22463. */
  22464. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22465. /**
  22466. * Light type const id of the directional light.
  22467. */
  22468. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22469. /**
  22470. * Light type const id of the spot light.
  22471. */
  22472. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22473. /**
  22474. * Light type const id of the hemispheric light.
  22475. */
  22476. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22477. __decorate([
  22478. BABYLON.serializeAsColor3()
  22479. ], Light.prototype, "diffuse", void 0);
  22480. __decorate([
  22481. BABYLON.serializeAsColor3()
  22482. ], Light.prototype, "specular", void 0);
  22483. __decorate([
  22484. BABYLON.serialize()
  22485. ], Light.prototype, "falloffType", void 0);
  22486. __decorate([
  22487. BABYLON.serialize()
  22488. ], Light.prototype, "intensity", void 0);
  22489. __decorate([
  22490. BABYLON.serialize()
  22491. ], Light.prototype, "range", null);
  22492. __decorate([
  22493. BABYLON.serialize()
  22494. ], Light.prototype, "intensityMode", null);
  22495. __decorate([
  22496. BABYLON.serialize()
  22497. ], Light.prototype, "radius", null);
  22498. __decorate([
  22499. BABYLON.serialize()
  22500. ], Light.prototype, "_renderPriority", void 0);
  22501. __decorate([
  22502. BABYLON.expandToProperty("_reorderLightsInScene")
  22503. ], Light.prototype, "renderPriority", void 0);
  22504. __decorate([
  22505. BABYLON.serialize("shadowEnabled")
  22506. ], Light.prototype, "_shadowEnabled", void 0);
  22507. __decorate([
  22508. BABYLON.serialize("excludeWithLayerMask")
  22509. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22510. __decorate([
  22511. BABYLON.serialize("includeOnlyWithLayerMask")
  22512. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22513. __decorate([
  22514. BABYLON.serialize("lightmapMode")
  22515. ], Light.prototype, "_lightmapMode", void 0);
  22516. return Light;
  22517. }(BABYLON.Node));
  22518. BABYLON.Light = Light;
  22519. })(BABYLON || (BABYLON = {}));
  22520. //# sourceMappingURL=babylon.light.js.map
  22521. var BABYLON;
  22522. (function (BABYLON) {
  22523. /**
  22524. * This is the base class of all the camera used in the application.
  22525. * @see http://doc.babylonjs.com/features/cameras
  22526. */
  22527. var Camera = /** @class */ (function (_super) {
  22528. __extends(Camera, _super);
  22529. /**
  22530. * Instantiates a new camera object.
  22531. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22532. * @see http://doc.babylonjs.com/features/cameras
  22533. * @param name Defines the name of the camera in the scene
  22534. * @param position Defines the position of the camera
  22535. * @param scene Defines the scene the camera belongs too
  22536. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22537. */
  22538. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22539. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22540. var _this = _super.call(this, name, scene) || this;
  22541. /**
  22542. * The vector the camera should consider as up.
  22543. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22544. */
  22545. _this.upVector = BABYLON.Vector3.Up();
  22546. /**
  22547. * Define the current limit on the left side for an orthographic camera
  22548. * In scene unit
  22549. */
  22550. _this.orthoLeft = null;
  22551. /**
  22552. * Define the current limit on the right side for an orthographic camera
  22553. * In scene unit
  22554. */
  22555. _this.orthoRight = null;
  22556. /**
  22557. * Define the current limit on the bottom side for an orthographic camera
  22558. * In scene unit
  22559. */
  22560. _this.orthoBottom = null;
  22561. /**
  22562. * Define the current limit on the top side for an orthographic camera
  22563. * In scene unit
  22564. */
  22565. _this.orthoTop = null;
  22566. /**
  22567. * Field Of View is set in Radians. (default is 0.8)
  22568. */
  22569. _this.fov = 0.8;
  22570. /**
  22571. * Define the minimum distance the camera can see from.
  22572. * This is important to note that the depth buffer are not infinite and the closer it starts
  22573. * the more your scene might encounter depth fighting issue.
  22574. */
  22575. _this.minZ = 1;
  22576. /**
  22577. * Define the maximum distance the camera can see to.
  22578. * This is important to note that the depth buffer are not infinite and the further it end
  22579. * the more your scene might encounter depth fighting issue.
  22580. */
  22581. _this.maxZ = 10000.0;
  22582. /**
  22583. * Define the default inertia of the camera.
  22584. * This helps giving a smooth feeling to the camera movement.
  22585. */
  22586. _this.inertia = 0.9;
  22587. /**
  22588. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22589. */
  22590. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22591. /**
  22592. * Define wether the camera is intermediate.
  22593. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22594. */
  22595. _this.isIntermediate = false;
  22596. /**
  22597. * Define the viewport of the camera.
  22598. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22599. */
  22600. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22601. /**
  22602. * Restricts the camera to viewing objects with the same layerMask.
  22603. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22604. */
  22605. _this.layerMask = 0x0FFFFFFF;
  22606. /**
  22607. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22608. */
  22609. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22610. /**
  22611. * Rig mode of the camera.
  22612. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22613. * This is normally controlled byt the camera themselves as internal use.
  22614. */
  22615. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22616. /**
  22617. * Defines the list of custom render target the camera should render to.
  22618. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22619. * else in the scene.
  22620. */
  22621. _this.customRenderTargets = new Array();
  22622. /**
  22623. * Observable triggered when the camera view matrix has changed.
  22624. */
  22625. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22626. /**
  22627. * Observable triggered when the camera Projection matrix has changed.
  22628. */
  22629. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22630. /**
  22631. * Observable triggered when the inputs have been processed.
  22632. */
  22633. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22634. /**
  22635. * Observable triggered when reset has been called and applied to the camera.
  22636. */
  22637. _this.onRestoreStateObservable = new BABYLON.Observable();
  22638. /** @hidden */
  22639. _this._rigCameras = new Array();
  22640. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22641. /** @hidden */
  22642. _this._skipRendering = false;
  22643. /** @hidden */
  22644. _this._projectionMatrix = new BABYLON.Matrix();
  22645. /** @hidden */
  22646. _this._postProcesses = new Array();
  22647. /** @hidden */
  22648. _this._activeMeshes = new BABYLON.SmartArray(256);
  22649. _this._globalPosition = BABYLON.Vector3.Zero();
  22650. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22651. _this._doNotComputeProjectionMatrix = false;
  22652. _this._transformMatrix = BABYLON.Matrix.Zero();
  22653. _this._refreshFrustumPlanes = true;
  22654. _this.getScene().addCamera(_this);
  22655. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22656. _this.getScene().activeCamera = _this;
  22657. }
  22658. _this.position = position;
  22659. return _this;
  22660. }
  22661. /**
  22662. * Store current camera state (fov, position, etc..)
  22663. * @returns the camera
  22664. */
  22665. Camera.prototype.storeState = function () {
  22666. this._stateStored = true;
  22667. this._storedFov = this.fov;
  22668. return this;
  22669. };
  22670. /**
  22671. * Restores the camera state values if it has been stored. You must call storeState() first
  22672. */
  22673. Camera.prototype._restoreStateValues = function () {
  22674. if (!this._stateStored) {
  22675. return false;
  22676. }
  22677. this.fov = this._storedFov;
  22678. return true;
  22679. };
  22680. /**
  22681. * Restored camera state. You must call storeState() first.
  22682. * @returns true if restored and false otherwise
  22683. */
  22684. Camera.prototype.restoreState = function () {
  22685. if (this._restoreStateValues()) {
  22686. this.onRestoreStateObservable.notifyObservers(this);
  22687. return true;
  22688. }
  22689. return false;
  22690. };
  22691. /**
  22692. * Gets the class name of the camera.
  22693. * @returns the class name
  22694. */
  22695. Camera.prototype.getClassName = function () {
  22696. return "Camera";
  22697. };
  22698. /**
  22699. * Gets a string representation of the camera usefull for debug purpose.
  22700. * @param fullDetails Defines that a more verboe level of logging is required
  22701. * @returns the string representation
  22702. */
  22703. Camera.prototype.toString = function (fullDetails) {
  22704. var ret = "Name: " + this.name;
  22705. ret += ", type: " + this.getClassName();
  22706. if (this.animations) {
  22707. for (var i = 0; i < this.animations.length; i++) {
  22708. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22709. }
  22710. }
  22711. if (fullDetails) {
  22712. }
  22713. return ret;
  22714. };
  22715. Object.defineProperty(Camera.prototype, "globalPosition", {
  22716. /**
  22717. * Gets the current world space position of the camera.
  22718. */
  22719. get: function () {
  22720. return this._globalPosition;
  22721. },
  22722. enumerable: true,
  22723. configurable: true
  22724. });
  22725. /**
  22726. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  22727. * @returns the active meshe list
  22728. */
  22729. Camera.prototype.getActiveMeshes = function () {
  22730. return this._activeMeshes;
  22731. };
  22732. /**
  22733. * Check wether a mesh is part of the current active mesh list of the camera
  22734. * @param mesh Defines the mesh to check
  22735. * @returns true if active, false otherwise
  22736. */
  22737. Camera.prototype.isActiveMesh = function (mesh) {
  22738. return (this._activeMeshes.indexOf(mesh) !== -1);
  22739. };
  22740. /**
  22741. * Is this camera ready to be used/rendered
  22742. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22743. * @return true if the camera is ready
  22744. */
  22745. Camera.prototype.isReady = function (completeCheck) {
  22746. if (completeCheck === void 0) { completeCheck = false; }
  22747. if (completeCheck) {
  22748. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22749. var pp = _a[_i];
  22750. if (pp && !pp.isReady()) {
  22751. return false;
  22752. }
  22753. }
  22754. }
  22755. return _super.prototype.isReady.call(this, completeCheck);
  22756. };
  22757. /** @hidden */
  22758. Camera.prototype._initCache = function () {
  22759. _super.prototype._initCache.call(this);
  22760. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22761. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22762. this._cache.mode = undefined;
  22763. this._cache.minZ = undefined;
  22764. this._cache.maxZ = undefined;
  22765. this._cache.fov = undefined;
  22766. this._cache.fovMode = undefined;
  22767. this._cache.aspectRatio = undefined;
  22768. this._cache.orthoLeft = undefined;
  22769. this._cache.orthoRight = undefined;
  22770. this._cache.orthoBottom = undefined;
  22771. this._cache.orthoTop = undefined;
  22772. this._cache.renderWidth = undefined;
  22773. this._cache.renderHeight = undefined;
  22774. };
  22775. /** @hidden */
  22776. Camera.prototype._updateCache = function (ignoreParentClass) {
  22777. if (!ignoreParentClass) {
  22778. _super.prototype._updateCache.call(this);
  22779. }
  22780. this._cache.position.copyFrom(this.position);
  22781. this._cache.upVector.copyFrom(this.upVector);
  22782. };
  22783. /** @hidden */
  22784. Camera.prototype._isSynchronized = function () {
  22785. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22786. };
  22787. /** @hidden */
  22788. Camera.prototype._isSynchronizedViewMatrix = function () {
  22789. if (!_super.prototype._isSynchronized.call(this))
  22790. return false;
  22791. return this._cache.position.equals(this.position)
  22792. && this._cache.upVector.equals(this.upVector)
  22793. && this.isSynchronizedWithParent();
  22794. };
  22795. /** @hidden */
  22796. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22797. var check = this._cache.mode === this.mode
  22798. && this._cache.minZ === this.minZ
  22799. && this._cache.maxZ === this.maxZ;
  22800. if (!check) {
  22801. return false;
  22802. }
  22803. var engine = this.getEngine();
  22804. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22805. check = this._cache.fov === this.fov
  22806. && this._cache.fovMode === this.fovMode
  22807. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22808. }
  22809. else {
  22810. check = this._cache.orthoLeft === this.orthoLeft
  22811. && this._cache.orthoRight === this.orthoRight
  22812. && this._cache.orthoBottom === this.orthoBottom
  22813. && this._cache.orthoTop === this.orthoTop
  22814. && this._cache.renderWidth === engine.getRenderWidth()
  22815. && this._cache.renderHeight === engine.getRenderHeight();
  22816. }
  22817. return check;
  22818. };
  22819. /**
  22820. * Attach the input controls to a specific dom element to get the input from.
  22821. * @param element Defines the element the controls should be listened from
  22822. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  22823. */
  22824. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22825. };
  22826. /**
  22827. * Detach the current controls from the specified dom element.
  22828. * @param element Defines the element to stop listening the inputs from
  22829. */
  22830. Camera.prototype.detachControl = function (element) {
  22831. };
  22832. /**
  22833. * Update the camera state according to the different inputs gathered during the frame.
  22834. */
  22835. Camera.prototype.update = function () {
  22836. this._checkInputs();
  22837. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22838. this._updateRigCameras();
  22839. }
  22840. };
  22841. /** @hidden */
  22842. Camera.prototype._checkInputs = function () {
  22843. this.onAfterCheckInputsObservable.notifyObservers(this);
  22844. };
  22845. Object.defineProperty(Camera.prototype, "rigCameras", {
  22846. /** @hidden */
  22847. get: function () {
  22848. return this._rigCameras;
  22849. },
  22850. enumerable: true,
  22851. configurable: true
  22852. });
  22853. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22854. get: function () {
  22855. return this._rigPostProcess;
  22856. },
  22857. enumerable: true,
  22858. configurable: true
  22859. });
  22860. /**
  22861. * Internal, gets the first post proces.
  22862. * @returns the first post process to be run on this camera.
  22863. */
  22864. Camera.prototype._getFirstPostProcess = function () {
  22865. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22866. if (this._postProcesses[ppIndex] !== null) {
  22867. return this._postProcesses[ppIndex];
  22868. }
  22869. }
  22870. return null;
  22871. };
  22872. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22873. // invalidate framebuffer
  22874. var firstPostProcess = this._getFirstPostProcess();
  22875. if (firstPostProcess) {
  22876. firstPostProcess.markTextureDirty();
  22877. }
  22878. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22879. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22880. var cam = this._rigCameras[i];
  22881. var rigPostProcess = cam._rigPostProcess;
  22882. // for VR rig, there does not have to be a post process
  22883. if (rigPostProcess) {
  22884. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22885. if (isPass) {
  22886. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22887. cam.isIntermediate = this._postProcesses.length === 0;
  22888. }
  22889. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22890. rigPostProcess.markTextureDirty();
  22891. }
  22892. else {
  22893. cam._postProcesses = this._postProcesses.slice(0);
  22894. }
  22895. }
  22896. };
  22897. /**
  22898. * Attach a post process to the camera.
  22899. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22900. * @param postProcess The post process to attach to the camera
  22901. * @param insertAt The position of the post process in case several of them are in use in the scene
  22902. * @returns the position the post process has been inserted at
  22903. */
  22904. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22905. if (insertAt === void 0) { insertAt = null; }
  22906. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22907. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22908. return 0;
  22909. }
  22910. if (insertAt == null || insertAt < 0) {
  22911. this._postProcesses.push(postProcess);
  22912. }
  22913. else if (this._postProcesses[insertAt] === null) {
  22914. this._postProcesses[insertAt] = postProcess;
  22915. }
  22916. else {
  22917. this._postProcesses.splice(insertAt, 0, postProcess);
  22918. }
  22919. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22920. return this._postProcesses.indexOf(postProcess);
  22921. };
  22922. /**
  22923. * Detach a post process to the camera.
  22924. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22925. * @param postProcess The post process to detach from the camera
  22926. */
  22927. Camera.prototype.detachPostProcess = function (postProcess) {
  22928. var idx = this._postProcesses.indexOf(postProcess);
  22929. if (idx !== -1) {
  22930. this._postProcesses[idx] = null;
  22931. }
  22932. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22933. };
  22934. /**
  22935. * Gets the current world matrix of the camera
  22936. */
  22937. Camera.prototype.getWorldMatrix = function () {
  22938. if (this._isSynchronizedViewMatrix()) {
  22939. return this._worldMatrix;
  22940. }
  22941. // Getting the the view matrix will also compute the world matrix.
  22942. this.getViewMatrix();
  22943. return this._worldMatrix;
  22944. };
  22945. /** @hidden */
  22946. Camera.prototype._getViewMatrix = function () {
  22947. return BABYLON.Matrix.Identity();
  22948. };
  22949. /**
  22950. * Gets the current view matrix of the camera.
  22951. * @param force forces the camera to recompute the matrix without looking at the cached state
  22952. * @returns the view matrix
  22953. */
  22954. Camera.prototype.getViewMatrix = function (force) {
  22955. if (!force && this._isSynchronizedViewMatrix()) {
  22956. return this._computedViewMatrix;
  22957. }
  22958. this.updateCache();
  22959. this._computedViewMatrix = this._getViewMatrix();
  22960. this._currentRenderId = this.getScene().getRenderId();
  22961. this._childRenderId = this._currentRenderId;
  22962. this._refreshFrustumPlanes = true;
  22963. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22964. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22965. }
  22966. this.onViewMatrixChangedObservable.notifyObservers(this);
  22967. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22968. return this._computedViewMatrix;
  22969. };
  22970. /**
  22971. * Freeze the projection matrix.
  22972. * It will prevent the cache check of the camera projection compute and can speed up perf
  22973. * if no parameter of the camera are meant to change
  22974. * @param projection Defines manually a projection if necessary
  22975. */
  22976. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22977. this._doNotComputeProjectionMatrix = true;
  22978. if (projection !== undefined) {
  22979. this._projectionMatrix = projection;
  22980. }
  22981. };
  22982. ;
  22983. /**
  22984. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  22985. */
  22986. Camera.prototype.unfreezeProjectionMatrix = function () {
  22987. this._doNotComputeProjectionMatrix = false;
  22988. };
  22989. ;
  22990. /**
  22991. * Gets the current projection matrix of the camera.
  22992. * @param force forces the camera to recompute the matrix without looking at the cached state
  22993. * @returns the projection matrix
  22994. */
  22995. Camera.prototype.getProjectionMatrix = function (force) {
  22996. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22997. return this._projectionMatrix;
  22998. }
  22999. // Cache
  23000. this._cache.mode = this.mode;
  23001. this._cache.minZ = this.minZ;
  23002. this._cache.maxZ = this.maxZ;
  23003. // Matrix
  23004. this._refreshFrustumPlanes = true;
  23005. var engine = this.getEngine();
  23006. var scene = this.getScene();
  23007. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23008. this._cache.fov = this.fov;
  23009. this._cache.fovMode = this.fovMode;
  23010. this._cache.aspectRatio = engine.getAspectRatio(this);
  23011. if (this.minZ <= 0) {
  23012. this.minZ = 0.1;
  23013. }
  23014. if (scene.useRightHandedSystem) {
  23015. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23016. }
  23017. else {
  23018. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23019. }
  23020. }
  23021. else {
  23022. var halfWidth = engine.getRenderWidth() / 2.0;
  23023. var halfHeight = engine.getRenderHeight() / 2.0;
  23024. if (scene.useRightHandedSystem) {
  23025. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23026. }
  23027. else {
  23028. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23029. }
  23030. this._cache.orthoLeft = this.orthoLeft;
  23031. this._cache.orthoRight = this.orthoRight;
  23032. this._cache.orthoBottom = this.orthoBottom;
  23033. this._cache.orthoTop = this.orthoTop;
  23034. this._cache.renderWidth = engine.getRenderWidth();
  23035. this._cache.renderHeight = engine.getRenderHeight();
  23036. }
  23037. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23038. return this._projectionMatrix;
  23039. };
  23040. /**
  23041. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23042. * @returns a Matrix
  23043. */
  23044. Camera.prototype.getTransformationMatrix = function () {
  23045. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23046. return this._transformMatrix;
  23047. };
  23048. Camera.prototype._updateFrustumPlanes = function () {
  23049. if (!this._refreshFrustumPlanes) {
  23050. return;
  23051. }
  23052. this.getTransformationMatrix();
  23053. if (!this._frustumPlanes) {
  23054. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23055. }
  23056. else {
  23057. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23058. }
  23059. this._refreshFrustumPlanes = false;
  23060. };
  23061. /**
  23062. * Checks if a cullable object (mesh...) is in the camera frustum
  23063. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23064. * @param target The object to check
  23065. * @returns true if the object is in frustum otherwise false
  23066. */
  23067. Camera.prototype.isInFrustum = function (target) {
  23068. this._updateFrustumPlanes();
  23069. return target.isInFrustum(this._frustumPlanes);
  23070. };
  23071. /**
  23072. * Checks if a cullable object (mesh...) is in the camera frustum
  23073. * Unlike isInFrustum this cheks the full bounding box
  23074. * @param target The object to check
  23075. * @returns true if the object is in frustum otherwise false
  23076. */
  23077. Camera.prototype.isCompletelyInFrustum = function (target) {
  23078. this._updateFrustumPlanes();
  23079. return target.isCompletelyInFrustum(this._frustumPlanes);
  23080. };
  23081. /**
  23082. * Gets a ray in the forward direction from the camera.
  23083. * @param length Defines the length of the ray to create
  23084. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23085. * @param origin Defines the start point of the ray which defaults to the camera position
  23086. * @returns the forward ray
  23087. */
  23088. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23089. if (length === void 0) { length = 100; }
  23090. if (!transform) {
  23091. transform = this.getWorldMatrix();
  23092. }
  23093. if (!origin) {
  23094. origin = this.position;
  23095. }
  23096. var forward = new BABYLON.Vector3(0, 0, 1);
  23097. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23098. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23099. return new BABYLON.Ray(origin, direction, length);
  23100. };
  23101. /**
  23102. * Releases resources associated with this node.
  23103. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23104. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23105. */
  23106. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23107. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23108. // Observables
  23109. this.onViewMatrixChangedObservable.clear();
  23110. this.onProjectionMatrixChangedObservable.clear();
  23111. this.onAfterCheckInputsObservable.clear();
  23112. this.onRestoreStateObservable.clear();
  23113. // Inputs
  23114. if (this.inputs) {
  23115. this.inputs.clear();
  23116. }
  23117. // Animations
  23118. this.getScene().stopAnimation(this);
  23119. // Remove from scene
  23120. this.getScene().removeCamera(this);
  23121. while (this._rigCameras.length > 0) {
  23122. var camera = this._rigCameras.pop();
  23123. if (camera) {
  23124. camera.dispose();
  23125. }
  23126. }
  23127. // Postprocesses
  23128. if (this._rigPostProcess) {
  23129. this._rigPostProcess.dispose(this);
  23130. this._rigPostProcess = null;
  23131. this._postProcesses = [];
  23132. }
  23133. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23134. this._rigPostProcess = null;
  23135. this._postProcesses = [];
  23136. }
  23137. else {
  23138. var i = this._postProcesses.length;
  23139. while (--i >= 0) {
  23140. var postProcess = this._postProcesses[i];
  23141. if (postProcess) {
  23142. postProcess.dispose(this);
  23143. }
  23144. }
  23145. }
  23146. // Render targets
  23147. var i = this.customRenderTargets.length;
  23148. while (--i >= 0) {
  23149. this.customRenderTargets[i].dispose();
  23150. }
  23151. this.customRenderTargets = [];
  23152. // Active Meshes
  23153. this._activeMeshes.dispose();
  23154. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23155. };
  23156. Object.defineProperty(Camera.prototype, "leftCamera", {
  23157. /**
  23158. * Gets the left camera of a rig setup in case of Rigged Camera
  23159. */
  23160. get: function () {
  23161. if (this._rigCameras.length < 1) {
  23162. return null;
  23163. }
  23164. return this._rigCameras[0];
  23165. },
  23166. enumerable: true,
  23167. configurable: true
  23168. });
  23169. Object.defineProperty(Camera.prototype, "rightCamera", {
  23170. /**
  23171. * Gets the right camera of a rig setup in case of Rigged Camera
  23172. */
  23173. get: function () {
  23174. if (this._rigCameras.length < 2) {
  23175. return null;
  23176. }
  23177. return this._rigCameras[1];
  23178. },
  23179. enumerable: true,
  23180. configurable: true
  23181. });
  23182. /**
  23183. * Gets the left camera target of a rig setup in case of Rigged Camera
  23184. * @returns the target position
  23185. */
  23186. Camera.prototype.getLeftTarget = function () {
  23187. if (this._rigCameras.length < 1) {
  23188. return null;
  23189. }
  23190. return this._rigCameras[0].getTarget();
  23191. };
  23192. /**
  23193. * Gets the right camera target of a rig setup in case of Rigged Camera
  23194. * @returns the target position
  23195. */
  23196. Camera.prototype.getRightTarget = function () {
  23197. if (this._rigCameras.length < 2) {
  23198. return null;
  23199. }
  23200. return this._rigCameras[1].getTarget();
  23201. };
  23202. /**
  23203. * @hidden
  23204. */
  23205. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23206. if (this.cameraRigMode === mode) {
  23207. return;
  23208. }
  23209. while (this._rigCameras.length > 0) {
  23210. var camera = this._rigCameras.pop();
  23211. if (camera) {
  23212. camera.dispose();
  23213. }
  23214. }
  23215. this.cameraRigMode = mode;
  23216. this._cameraRigParams = {};
  23217. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23218. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23219. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23220. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23221. // create the rig cameras, unless none
  23222. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23223. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23224. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23225. if (leftCamera && rightCamera) {
  23226. this._rigCameras.push(leftCamera);
  23227. this._rigCameras.push(rightCamera);
  23228. }
  23229. }
  23230. switch (this.cameraRigMode) {
  23231. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23232. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23233. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23234. break;
  23235. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23236. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23237. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23238. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23239. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23240. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23241. break;
  23242. case Camera.RIG_MODE_VR:
  23243. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23244. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23245. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23246. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23247. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23248. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23249. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23250. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23251. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23252. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23253. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23254. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23255. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23256. if (metrics.compensateDistortion) {
  23257. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23258. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23259. }
  23260. break;
  23261. case Camera.RIG_MODE_WEBVR:
  23262. if (rigParams.vrDisplay) {
  23263. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23264. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23265. //Left eye
  23266. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23267. this._rigCameras[0].setCameraRigParameter("left", true);
  23268. //leaving this for future reference
  23269. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23270. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23271. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23272. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23273. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23274. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23275. this._rigCameras[0].parent = this;
  23276. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23277. //Right eye
  23278. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23279. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23280. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23281. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23282. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23283. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23284. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23285. this._rigCameras[1].parent = this;
  23286. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23287. if (Camera.UseAlternateWebVRRendering) {
  23288. this._rigCameras[1]._skipRendering = true;
  23289. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23290. }
  23291. }
  23292. break;
  23293. }
  23294. this._cascadePostProcessesToRigCams();
  23295. this.update();
  23296. };
  23297. Camera.prototype._getVRProjectionMatrix = function () {
  23298. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23299. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23300. return this._projectionMatrix;
  23301. };
  23302. Camera.prototype._updateCameraRotationMatrix = function () {
  23303. //Here for WebVR
  23304. };
  23305. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23306. //Here for WebVR
  23307. };
  23308. /**
  23309. * This function MUST be overwritten by the different WebVR cameras available.
  23310. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23311. */
  23312. Camera.prototype._getWebVRProjectionMatrix = function () {
  23313. return BABYLON.Matrix.Identity();
  23314. };
  23315. /**
  23316. * This function MUST be overwritten by the different WebVR cameras available.
  23317. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23318. */
  23319. Camera.prototype._getWebVRViewMatrix = function () {
  23320. return BABYLON.Matrix.Identity();
  23321. };
  23322. /** @hidden */
  23323. Camera.prototype.setCameraRigParameter = function (name, value) {
  23324. if (!this._cameraRigParams) {
  23325. this._cameraRigParams = {};
  23326. }
  23327. this._cameraRigParams[name] = value;
  23328. //provisionnally:
  23329. if (name === "interaxialDistance") {
  23330. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23331. }
  23332. };
  23333. /**
  23334. * needs to be overridden by children so sub has required properties to be copied
  23335. * @hidden
  23336. */
  23337. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23338. return null;
  23339. };
  23340. /**
  23341. * May need to be overridden by children
  23342. * @hidden
  23343. */
  23344. Camera.prototype._updateRigCameras = function () {
  23345. for (var i = 0; i < this._rigCameras.length; i++) {
  23346. this._rigCameras[i].minZ = this.minZ;
  23347. this._rigCameras[i].maxZ = this.maxZ;
  23348. this._rigCameras[i].fov = this.fov;
  23349. }
  23350. // only update viewport when ANAGLYPH
  23351. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23352. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23353. }
  23354. };
  23355. /** @hidden */
  23356. Camera.prototype._setupInputs = function () {
  23357. };
  23358. /**
  23359. * Serialiaze the camera setup to a json represention
  23360. * @returns the JSON representation
  23361. */
  23362. Camera.prototype.serialize = function () {
  23363. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23364. // Type
  23365. serializationObject.type = this.getClassName();
  23366. // Parent
  23367. if (this.parent) {
  23368. serializationObject.parentId = this.parent.id;
  23369. }
  23370. if (this.inputs) {
  23371. this.inputs.serialize(serializationObject);
  23372. }
  23373. // Animations
  23374. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23375. serializationObject.ranges = this.serializeAnimationRanges();
  23376. return serializationObject;
  23377. };
  23378. /**
  23379. * Clones the current camera.
  23380. * @param name The cloned camera name
  23381. * @returns the cloned camera
  23382. */
  23383. Camera.prototype.clone = function (name) {
  23384. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23385. };
  23386. /**
  23387. * Gets the direction of the camera relative to a given local axis.
  23388. * @param localAxis Defines the reference axis to provide a relative direction.
  23389. * @return the direction
  23390. */
  23391. Camera.prototype.getDirection = function (localAxis) {
  23392. var result = BABYLON.Vector3.Zero();
  23393. this.getDirectionToRef(localAxis, result);
  23394. return result;
  23395. };
  23396. /**
  23397. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23398. * @param localAxis Defines the reference axis to provide a relative direction.
  23399. * @param result Defines the vector to store the result in
  23400. */
  23401. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23402. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23403. };
  23404. /**
  23405. * Gets a camera constructor for a given camera type
  23406. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23407. * @param name The name of the camera the result will be able to instantiate
  23408. * @param scene The scene the result will construct the camera in
  23409. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23410. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23411. * @returns a factory method to construc the camera
  23412. */
  23413. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23414. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23415. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23416. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23417. interaxial_distance: interaxial_distance,
  23418. isStereoscopicSideBySide: isStereoscopicSideBySide
  23419. });
  23420. if (constructorFunc) {
  23421. return constructorFunc;
  23422. }
  23423. // Default to universal camera
  23424. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23425. };
  23426. /**
  23427. * Compute the world matrix of the camera.
  23428. * @returns the camera workd matrix
  23429. */
  23430. Camera.prototype.computeWorldMatrix = function () {
  23431. return this.getWorldMatrix();
  23432. };
  23433. /**
  23434. * Parse a JSON and creates the camera from the parsed information
  23435. * @param parsedCamera The JSON to parse
  23436. * @param scene The scene to instantiate the camera in
  23437. * @returns the newly constructed camera
  23438. */
  23439. Camera.Parse = function (parsedCamera, scene) {
  23440. var type = parsedCamera.type;
  23441. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23442. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23443. // Parent
  23444. if (parsedCamera.parentId) {
  23445. camera._waitingParentId = parsedCamera.parentId;
  23446. }
  23447. //If camera has an input manager, let it parse inputs settings
  23448. if (camera.inputs) {
  23449. camera.inputs.parse(parsedCamera);
  23450. camera._setupInputs();
  23451. }
  23452. if (camera.setPosition) { // need to force position
  23453. camera.position.copyFromFloats(0, 0, 0);
  23454. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23455. }
  23456. // Target
  23457. if (parsedCamera.target) {
  23458. if (camera.setTarget) {
  23459. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23460. }
  23461. }
  23462. // Apply 3d rig, when found
  23463. if (parsedCamera.cameraRigMode) {
  23464. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23465. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23466. }
  23467. // Animations
  23468. if (parsedCamera.animations) {
  23469. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23470. var parsedAnimation = parsedCamera.animations[animationIndex];
  23471. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23472. }
  23473. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23474. }
  23475. if (parsedCamera.autoAnimate) {
  23476. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23477. }
  23478. return camera;
  23479. };
  23480. /**
  23481. * This is the default projection mode used by the cameras.
  23482. * It helps recreating a feeling of perspective and better appreciate depth.
  23483. * This is the best way to simulate real life cameras.
  23484. */
  23485. Camera.PERSPECTIVE_CAMERA = 0;
  23486. /**
  23487. * This helps creating camera with an orthographic mode.
  23488. * 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.
  23489. */
  23490. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23491. /**
  23492. * This is the default FOV mode for perspective cameras.
  23493. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23494. */
  23495. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23496. /**
  23497. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23498. */
  23499. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23500. /**
  23501. * This specifies ther is no need for a camera rig.
  23502. * Basically only one eye is rendered corresponding to the camera.
  23503. */
  23504. Camera.RIG_MODE_NONE = 0;
  23505. /**
  23506. * Simulates a camera Rig with one blue eye and one red eye.
  23507. * This can be use with 3d blue and red glasses.
  23508. */
  23509. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23510. /**
  23511. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23512. */
  23513. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23514. /**
  23515. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23516. */
  23517. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23518. /**
  23519. * Defines that both eyes of the camera will be rendered over under each other.
  23520. */
  23521. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23522. /**
  23523. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23524. */
  23525. Camera.RIG_MODE_VR = 20;
  23526. /**
  23527. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23528. */
  23529. Camera.RIG_MODE_WEBVR = 21;
  23530. /**
  23531. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23532. */
  23533. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23534. /**
  23535. * @hidden
  23536. * Might be removed once multiview will be a thing
  23537. */
  23538. Camera.UseAlternateWebVRRendering = false;
  23539. __decorate([
  23540. BABYLON.serializeAsVector3()
  23541. ], Camera.prototype, "position", void 0);
  23542. __decorate([
  23543. BABYLON.serializeAsVector3()
  23544. ], Camera.prototype, "upVector", void 0);
  23545. __decorate([
  23546. BABYLON.serialize()
  23547. ], Camera.prototype, "orthoLeft", void 0);
  23548. __decorate([
  23549. BABYLON.serialize()
  23550. ], Camera.prototype, "orthoRight", void 0);
  23551. __decorate([
  23552. BABYLON.serialize()
  23553. ], Camera.prototype, "orthoBottom", void 0);
  23554. __decorate([
  23555. BABYLON.serialize()
  23556. ], Camera.prototype, "orthoTop", void 0);
  23557. __decorate([
  23558. BABYLON.serialize()
  23559. ], Camera.prototype, "fov", void 0);
  23560. __decorate([
  23561. BABYLON.serialize()
  23562. ], Camera.prototype, "minZ", void 0);
  23563. __decorate([
  23564. BABYLON.serialize()
  23565. ], Camera.prototype, "maxZ", void 0);
  23566. __decorate([
  23567. BABYLON.serialize()
  23568. ], Camera.prototype, "inertia", void 0);
  23569. __decorate([
  23570. BABYLON.serialize()
  23571. ], Camera.prototype, "mode", void 0);
  23572. __decorate([
  23573. BABYLON.serialize()
  23574. ], Camera.prototype, "layerMask", void 0);
  23575. __decorate([
  23576. BABYLON.serialize()
  23577. ], Camera.prototype, "fovMode", void 0);
  23578. __decorate([
  23579. BABYLON.serialize()
  23580. ], Camera.prototype, "cameraRigMode", void 0);
  23581. __decorate([
  23582. BABYLON.serialize()
  23583. ], Camera.prototype, "interaxialDistance", void 0);
  23584. __decorate([
  23585. BABYLON.serialize()
  23586. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23587. return Camera;
  23588. }(BABYLON.Node));
  23589. BABYLON.Camera = Camera;
  23590. })(BABYLON || (BABYLON = {}));
  23591. //# sourceMappingURL=babylon.camera.js.map
  23592. var BABYLON;
  23593. (function (BABYLON) {
  23594. /**
  23595. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23596. * It is enable to manage the different groups as well as the different necessary sort functions.
  23597. * This should not be used directly aside of the few static configurations
  23598. */
  23599. var RenderingManager = /** @class */ (function () {
  23600. /**
  23601. * Instantiates a new rendering group for a particular scene
  23602. * @param scene Defines the scene the groups belongs to
  23603. */
  23604. function RenderingManager(scene) {
  23605. /**
  23606. * @hidden
  23607. */
  23608. this._useSceneAutoClearSetup = false;
  23609. this._renderingGroups = new Array();
  23610. this._autoClearDepthStencil = {};
  23611. this._customOpaqueSortCompareFn = {};
  23612. this._customAlphaTestSortCompareFn = {};
  23613. this._customTransparentSortCompareFn = {};
  23614. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23615. this._scene = scene;
  23616. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23617. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23618. }
  23619. }
  23620. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23621. if (depth === void 0) { depth = true; }
  23622. if (stencil === void 0) { stencil = true; }
  23623. if (this._depthStencilBufferAlreadyCleaned) {
  23624. return;
  23625. }
  23626. this._scene.getEngine().clear(null, false, depth, stencil);
  23627. this._depthStencilBufferAlreadyCleaned = true;
  23628. };
  23629. /**
  23630. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  23631. * @hidden
  23632. */
  23633. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23634. // Update the observable context (not null as it only goes away on dispose)
  23635. var info = this._renderingGroupInfo;
  23636. info.scene = this._scene;
  23637. info.camera = this._scene.activeCamera;
  23638. // Dispatch sprites
  23639. if (this._scene.spriteManagers && renderSprites) {
  23640. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23641. var manager = this._scene.spriteManagers[index];
  23642. this.dispatchSprites(manager);
  23643. }
  23644. }
  23645. // Render
  23646. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23647. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23648. var renderingGroup = this._renderingGroups[index];
  23649. if (!renderingGroup)
  23650. continue;
  23651. var renderingGroupMask = Math.pow(2, index);
  23652. info.renderingGroupId = index;
  23653. // Before Observable
  23654. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23655. // Clear depth/stencil if needed
  23656. if (RenderingManager.AUTOCLEAR) {
  23657. var autoClear = this._useSceneAutoClearSetup ?
  23658. this._scene.getAutoClearDepthStencilSetup(index) :
  23659. this._autoClearDepthStencil[index];
  23660. if (autoClear && autoClear.autoClear) {
  23661. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23662. }
  23663. }
  23664. // Render
  23665. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23666. var step = _a[_i];
  23667. step.action(index);
  23668. }
  23669. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23670. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23671. var step = _c[_b];
  23672. step.action(index);
  23673. }
  23674. // After Observable
  23675. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23676. }
  23677. };
  23678. /**
  23679. * Resets the different information of the group to prepare a new frame
  23680. * @hidden
  23681. */
  23682. RenderingManager.prototype.reset = function () {
  23683. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23684. var renderingGroup = this._renderingGroups[index];
  23685. if (renderingGroup) {
  23686. renderingGroup.prepare();
  23687. }
  23688. }
  23689. };
  23690. /**
  23691. * Dispose and release the group and its associated resources.
  23692. * @hidden
  23693. */
  23694. RenderingManager.prototype.dispose = function () {
  23695. this.freeRenderingGroups();
  23696. this._renderingGroups.length = 0;
  23697. this._renderingGroupInfo = null;
  23698. };
  23699. /**
  23700. * Clear the info related to rendering groups preventing retention points during dispose.
  23701. */
  23702. RenderingManager.prototype.freeRenderingGroups = function () {
  23703. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23704. var renderingGroup = this._renderingGroups[index];
  23705. if (renderingGroup) {
  23706. renderingGroup.dispose();
  23707. }
  23708. }
  23709. };
  23710. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23711. if (this._renderingGroups[renderingGroupId] === undefined) {
  23712. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23713. }
  23714. };
  23715. /**
  23716. * Add a sprite manager to the rendering manager in order to render it this frame.
  23717. * @param spriteManager Define the sprite manager to render
  23718. */
  23719. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23720. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23721. this._prepareRenderingGroup(renderingGroupId);
  23722. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23723. };
  23724. /**
  23725. * Add a particle system to the rendering manager in order to render it this frame.
  23726. * @param particleSystem Define the particle system to render
  23727. */
  23728. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23729. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23730. this._prepareRenderingGroup(renderingGroupId);
  23731. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23732. };
  23733. /**
  23734. * Add a submesh to the manager in order to render it this frame
  23735. * @param subMesh The submesh to dispatch
  23736. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23737. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23738. */
  23739. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23740. if (mesh === undefined) {
  23741. mesh = subMesh.getMesh();
  23742. }
  23743. var renderingGroupId = mesh.renderingGroupId || 0;
  23744. this._prepareRenderingGroup(renderingGroupId);
  23745. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23746. };
  23747. /**
  23748. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23749. * This allowed control for front to back rendering or reversly depending of the special needs.
  23750. *
  23751. * @param renderingGroupId The rendering group id corresponding to its index
  23752. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23753. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23754. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23755. */
  23756. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23757. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23758. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23759. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23760. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23761. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23762. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23763. if (this._renderingGroups[renderingGroupId]) {
  23764. var group = this._renderingGroups[renderingGroupId];
  23765. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23766. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23767. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23768. }
  23769. };
  23770. /**
  23771. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23772. *
  23773. * @param renderingGroupId The rendering group id corresponding to its index
  23774. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23775. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23776. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23777. */
  23778. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23779. if (depth === void 0) { depth = true; }
  23780. if (stencil === void 0) { stencil = true; }
  23781. this._autoClearDepthStencil[renderingGroupId] = {
  23782. autoClear: autoClearDepthStencil,
  23783. depth: depth,
  23784. stencil: stencil
  23785. };
  23786. };
  23787. /**
  23788. * Gets the current auto clear configuration for one rendering group of the rendering
  23789. * manager.
  23790. * @param index the rendering group index to get the information for
  23791. * @returns The auto clear setup for the requested rendering group
  23792. */
  23793. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23794. return this._autoClearDepthStencil[index];
  23795. };
  23796. /**
  23797. * The max id used for rendering groups (not included)
  23798. */
  23799. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23800. /**
  23801. * The min id used for rendering groups (included)
  23802. */
  23803. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23804. /**
  23805. * Used to globally prevent autoclearing scenes.
  23806. */
  23807. RenderingManager.AUTOCLEAR = true;
  23808. return RenderingManager;
  23809. }());
  23810. BABYLON.RenderingManager = RenderingManager;
  23811. })(BABYLON || (BABYLON = {}));
  23812. //# sourceMappingURL=babylon.renderingManager.js.map
  23813. var BABYLON;
  23814. (function (BABYLON) {
  23815. /**
  23816. * This represents the object necessary to create a rendering group.
  23817. * This is exclusively used and created by the rendering manager.
  23818. * To modify the behavior, you use the available helpers in your scene or meshes.
  23819. * @hidden
  23820. */
  23821. var RenderingGroup = /** @class */ (function () {
  23822. /**
  23823. * Creates a new rendering group.
  23824. * @param index The rendering group index
  23825. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23826. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23827. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23828. */
  23829. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23830. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23831. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23832. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23833. this.index = index;
  23834. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23835. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23836. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23837. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23838. this._particleSystems = new BABYLON.SmartArray(256);
  23839. this._spriteManagers = new BABYLON.SmartArray(256);
  23840. this._edgesRenderers = new BABYLON.SmartArray(16);
  23841. this._scene = scene;
  23842. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23843. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23844. this.transparentSortCompareFn = transparentSortCompareFn;
  23845. }
  23846. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23847. /**
  23848. * Set the opaque sort comparison function.
  23849. * If null the sub meshes will be render in the order they were created
  23850. */
  23851. set: function (value) {
  23852. this._opaqueSortCompareFn = value;
  23853. if (value) {
  23854. this._renderOpaque = this.renderOpaqueSorted;
  23855. }
  23856. else {
  23857. this._renderOpaque = RenderingGroup.renderUnsorted;
  23858. }
  23859. },
  23860. enumerable: true,
  23861. configurable: true
  23862. });
  23863. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23864. /**
  23865. * Set the alpha test sort comparison function.
  23866. * If null the sub meshes will be render in the order they were created
  23867. */
  23868. set: function (value) {
  23869. this._alphaTestSortCompareFn = value;
  23870. if (value) {
  23871. this._renderAlphaTest = this.renderAlphaTestSorted;
  23872. }
  23873. else {
  23874. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23875. }
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23881. /**
  23882. * Set the transparent sort comparison function.
  23883. * If null the sub meshes will be render in the order they were created
  23884. */
  23885. set: function (value) {
  23886. if (value) {
  23887. this._transparentSortCompareFn = value;
  23888. }
  23889. else {
  23890. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23891. }
  23892. this._renderTransparent = this.renderTransparentSorted;
  23893. },
  23894. enumerable: true,
  23895. configurable: true
  23896. });
  23897. /**
  23898. * Render all the sub meshes contained in the group.
  23899. * @param customRenderFunction Used to override the default render behaviour of the group.
  23900. * @returns true if rendered some submeshes.
  23901. */
  23902. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23903. if (customRenderFunction) {
  23904. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23905. return;
  23906. }
  23907. var engine = this._scene.getEngine();
  23908. // Depth only
  23909. if (this._depthOnlySubMeshes.length !== 0) {
  23910. engine.setColorWrite(false);
  23911. this._renderAlphaTest(this._depthOnlySubMeshes);
  23912. engine.setColorWrite(true);
  23913. }
  23914. // Opaque
  23915. if (this._opaqueSubMeshes.length !== 0) {
  23916. this._renderOpaque(this._opaqueSubMeshes);
  23917. }
  23918. // Alpha test
  23919. if (this._alphaTestSubMeshes.length !== 0) {
  23920. this._renderAlphaTest(this._alphaTestSubMeshes);
  23921. }
  23922. var stencilState = engine.getStencilBuffer();
  23923. engine.setStencilBuffer(false);
  23924. // Sprites
  23925. if (renderSprites) {
  23926. this._renderSprites();
  23927. }
  23928. // Particles
  23929. if (renderParticles) {
  23930. this._renderParticles(activeMeshes);
  23931. }
  23932. if (this.onBeforeTransparentRendering) {
  23933. this.onBeforeTransparentRendering();
  23934. }
  23935. // Transparent
  23936. if (this._transparentSubMeshes.length !== 0) {
  23937. this._renderTransparent(this._transparentSubMeshes);
  23938. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23939. }
  23940. // Set back stencil to false in case it changes before the edge renderer.
  23941. engine.setStencilBuffer(false);
  23942. // Edges
  23943. if (this._edgesRenderers.length) {
  23944. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23945. this._edgesRenderers.data[edgesRendererIndex].render();
  23946. }
  23947. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23948. }
  23949. // Restore Stencil state.
  23950. engine.setStencilBuffer(stencilState);
  23951. };
  23952. /**
  23953. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23954. * @param subMeshes The submeshes to render
  23955. */
  23956. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23957. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23958. };
  23959. /**
  23960. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23961. * @param subMeshes The submeshes to render
  23962. */
  23963. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23964. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23965. };
  23966. /**
  23967. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23968. * @param subMeshes The submeshes to render
  23969. */
  23970. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23971. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23972. };
  23973. /**
  23974. * Renders the submeshes in a specified order.
  23975. * @param subMeshes The submeshes to sort before render
  23976. * @param sortCompareFn The comparison function use to sort
  23977. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23978. * @param transparent Specifies to activate blending if true
  23979. */
  23980. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23981. var subIndex = 0;
  23982. var subMesh;
  23983. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23984. for (; subIndex < subMeshes.length; subIndex++) {
  23985. subMesh = subMeshes.data[subIndex];
  23986. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23987. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23988. }
  23989. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23990. if (sortCompareFn) {
  23991. sortedArray.sort(sortCompareFn);
  23992. }
  23993. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23994. subMesh = sortedArray[subIndex];
  23995. if (transparent) {
  23996. var material = subMesh.getMaterial();
  23997. if (material && material.needDepthPrePass) {
  23998. var engine = material.getScene().getEngine();
  23999. engine.setColorWrite(false);
  24000. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24001. subMesh.render(false);
  24002. engine.setColorWrite(true);
  24003. }
  24004. }
  24005. subMesh.render(transparent);
  24006. }
  24007. };
  24008. /**
  24009. * Renders the submeshes in the order they were dispatched (no sort applied).
  24010. * @param subMeshes The submeshes to render
  24011. */
  24012. RenderingGroup.renderUnsorted = function (subMeshes) {
  24013. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24014. var submesh = subMeshes.data[subIndex];
  24015. submesh.render(false);
  24016. }
  24017. };
  24018. /**
  24019. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24020. * are rendered back to front if in the same alpha index.
  24021. *
  24022. * @param a The first submesh
  24023. * @param b The second submesh
  24024. * @returns The result of the comparison
  24025. */
  24026. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24027. // Alpha index first
  24028. if (a._alphaIndex > b._alphaIndex) {
  24029. return 1;
  24030. }
  24031. if (a._alphaIndex < b._alphaIndex) {
  24032. return -1;
  24033. }
  24034. // Then distance to camera
  24035. return RenderingGroup.backToFrontSortCompare(a, b);
  24036. };
  24037. /**
  24038. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24039. * are rendered back to front.
  24040. *
  24041. * @param a The first submesh
  24042. * @param b The second submesh
  24043. * @returns The result of the comparison
  24044. */
  24045. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24046. // Then distance to camera
  24047. if (a._distanceToCamera < b._distanceToCamera) {
  24048. return 1;
  24049. }
  24050. if (a._distanceToCamera > b._distanceToCamera) {
  24051. return -1;
  24052. }
  24053. return 0;
  24054. };
  24055. /**
  24056. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24057. * are rendered front to back (prevent overdraw).
  24058. *
  24059. * @param a The first submesh
  24060. * @param b The second submesh
  24061. * @returns The result of the comparison
  24062. */
  24063. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24064. // Then distance to camera
  24065. if (a._distanceToCamera < b._distanceToCamera) {
  24066. return -1;
  24067. }
  24068. if (a._distanceToCamera > b._distanceToCamera) {
  24069. return 1;
  24070. }
  24071. return 0;
  24072. };
  24073. /**
  24074. * Resets the different lists of submeshes to prepare a new frame.
  24075. */
  24076. RenderingGroup.prototype.prepare = function () {
  24077. this._opaqueSubMeshes.reset();
  24078. this._transparentSubMeshes.reset();
  24079. this._alphaTestSubMeshes.reset();
  24080. this._depthOnlySubMeshes.reset();
  24081. this._particleSystems.reset();
  24082. this._spriteManagers.reset();
  24083. this._edgesRenderers.reset();
  24084. };
  24085. RenderingGroup.prototype.dispose = function () {
  24086. this._opaqueSubMeshes.dispose();
  24087. this._transparentSubMeshes.dispose();
  24088. this._alphaTestSubMeshes.dispose();
  24089. this._depthOnlySubMeshes.dispose();
  24090. this._particleSystems.dispose();
  24091. this._spriteManagers.dispose();
  24092. this._edgesRenderers.dispose();
  24093. };
  24094. /**
  24095. * Inserts the submesh in its correct queue depending on its material.
  24096. * @param subMesh The submesh to dispatch
  24097. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24098. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24099. */
  24100. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24101. // Get mesh and materials if not provided
  24102. if (mesh === undefined) {
  24103. mesh = subMesh.getMesh();
  24104. }
  24105. if (material === undefined) {
  24106. material = subMesh.getMaterial();
  24107. }
  24108. if (material === null || material === undefined) {
  24109. return;
  24110. }
  24111. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24112. this._transparentSubMeshes.push(subMesh);
  24113. }
  24114. else if (material.needAlphaTesting()) { // Alpha test
  24115. if (material.needDepthPrePass) {
  24116. this._depthOnlySubMeshes.push(subMesh);
  24117. }
  24118. this._alphaTestSubMeshes.push(subMesh);
  24119. }
  24120. else {
  24121. if (material.needDepthPrePass) {
  24122. this._depthOnlySubMeshes.push(subMesh);
  24123. }
  24124. this._opaqueSubMeshes.push(subMesh); // Opaque
  24125. }
  24126. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24127. this._edgesRenderers.push(mesh._edgesRenderer);
  24128. }
  24129. };
  24130. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24131. this._spriteManagers.push(spriteManager);
  24132. };
  24133. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24134. this._particleSystems.push(particleSystem);
  24135. };
  24136. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24137. if (this._particleSystems.length === 0) {
  24138. return;
  24139. }
  24140. // Particles
  24141. var activeCamera = this._scene.activeCamera;
  24142. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24143. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24144. var particleSystem = this._particleSystems.data[particleIndex];
  24145. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24146. continue;
  24147. }
  24148. var emitter = particleSystem.emitter;
  24149. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24150. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24151. }
  24152. }
  24153. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24154. };
  24155. RenderingGroup.prototype._renderSprites = function () {
  24156. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24157. return;
  24158. }
  24159. // Sprites
  24160. var activeCamera = this._scene.activeCamera;
  24161. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24162. for (var id = 0; id < this._spriteManagers.length; id++) {
  24163. var spriteManager = this._spriteManagers.data[id];
  24164. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24165. spriteManager.render();
  24166. }
  24167. }
  24168. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24169. };
  24170. return RenderingGroup;
  24171. }());
  24172. BABYLON.RenderingGroup = RenderingGroup;
  24173. })(BABYLON || (BABYLON = {}));
  24174. //# sourceMappingURL=babylon.renderingGroup.js.map
  24175. var BABYLON;
  24176. (function (BABYLON) {
  24177. /**
  24178. * Groups all the scene component constants in one place to ease maintenance.
  24179. * @hidden
  24180. */
  24181. var SceneComponentConstants = /** @class */ (function () {
  24182. function SceneComponentConstants() {
  24183. }
  24184. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24185. SceneComponentConstants.NAME_LAYER = "Layer";
  24186. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24187. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24188. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24189. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24190. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24191. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24192. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24193. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24194. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24195. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24196. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24197. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24198. SceneComponentConstants.NAME_OCTREE = "Octree";
  24199. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24200. SceneComponentConstants.NAME_AUDIO = "Audio";
  24201. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24202. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24203. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24204. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24205. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24206. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24207. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24208. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24209. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24210. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24211. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24212. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24213. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24214. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24215. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24216. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24217. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24218. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24219. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24220. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24221. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24222. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24223. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24224. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24225. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24226. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24227. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24228. return SceneComponentConstants;
  24229. }());
  24230. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24231. /**
  24232. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24233. * @hidden
  24234. */
  24235. var Stage = /** @class */ (function (_super) {
  24236. __extends(Stage, _super);
  24237. /**
  24238. * Hide ctor from the rest of the world.
  24239. * @param items The items to add.
  24240. */
  24241. function Stage(items) {
  24242. return _super.apply(this, items) || this;
  24243. }
  24244. /**
  24245. * Creates a new Stage.
  24246. * @returns A new instance of a Stage
  24247. */
  24248. Stage.Create = function () {
  24249. return Object.create(Stage.prototype);
  24250. };
  24251. /**
  24252. * Registers a step in an ordered way in the targeted stage.
  24253. * @param index Defines the position to register the step in
  24254. * @param component Defines the component attached to the step
  24255. * @param action Defines the action to launch during the step
  24256. */
  24257. Stage.prototype.registerStep = function (index, component, action) {
  24258. var i = 0;
  24259. var maxIndex = Number.MAX_VALUE;
  24260. for (; i < this.length && i < maxIndex; i++) {
  24261. var step = this[i];
  24262. maxIndex = step.index;
  24263. }
  24264. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24265. };
  24266. /**
  24267. * Clears all the steps from the stage.
  24268. */
  24269. Stage.prototype.clear = function () {
  24270. this.length = 0;
  24271. };
  24272. return Stage;
  24273. }(Array));
  24274. BABYLON.Stage = Stage;
  24275. })(BABYLON || (BABYLON = {}));
  24276. //# sourceMappingURL=babylon.sceneComponent.js.map
  24277. var BABYLON;
  24278. (function (BABYLON) {
  24279. /**
  24280. * Base class of the scene acting as a container for the different elements composing a scene.
  24281. * This class is dynamically extended by the different components of the scene increasing
  24282. * flexibility and reducing coupling
  24283. */
  24284. var AbstractScene = /** @class */ (function () {
  24285. function AbstractScene() {
  24286. /**
  24287. * Gets the list of root nodes (ie. nodes with no parent)
  24288. */
  24289. this.rootNodes = new Array();
  24290. /** All of the cameras added to this scene
  24291. * @see http://doc.babylonjs.com/babylon101/cameras
  24292. */
  24293. this.cameras = new Array();
  24294. /**
  24295. * All of the lights added to this scene
  24296. * @see http://doc.babylonjs.com/babylon101/lights
  24297. */
  24298. this.lights = new Array();
  24299. /**
  24300. * All of the (abstract) meshes added to this scene
  24301. */
  24302. this.meshes = new Array();
  24303. /**
  24304. * The list of skeletons added to the scene
  24305. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24306. */
  24307. this.skeletons = new Array();
  24308. /**
  24309. * All of the particle systems added to this scene
  24310. * @see http://doc.babylonjs.com/babylon101/particles
  24311. */
  24312. this.particleSystems = new Array();
  24313. /**
  24314. * Gets a list of Animations associated with the scene
  24315. */
  24316. this.animations = [];
  24317. /**
  24318. * All of the animation groups added to this scene
  24319. * @see http://doc.babylonjs.com/how_to/group
  24320. */
  24321. this.animationGroups = new Array();
  24322. /**
  24323. * All of the multi-materials added to this scene
  24324. * @see http://doc.babylonjs.com/how_to/multi_materials
  24325. */
  24326. this.multiMaterials = new Array();
  24327. /**
  24328. * All of the materials added to this scene
  24329. * @see http://doc.babylonjs.com/babylon101/materials
  24330. */
  24331. this.materials = new Array();
  24332. /**
  24333. * The list of morph target managers added to the scene
  24334. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24335. */
  24336. this.morphTargetManagers = new Array();
  24337. /**
  24338. * The list of geometries used in the scene.
  24339. */
  24340. this.geometries = new Array();
  24341. /**
  24342. * All of the tranform nodes added to this scene
  24343. * @see http://doc.babylonjs.com/how_to/transformnode
  24344. */
  24345. this.transformNodes = new Array();
  24346. /**
  24347. * ActionManagers available on the scene.
  24348. */
  24349. this.actionManagers = new Array();
  24350. /**
  24351. * Textures to keep.
  24352. */
  24353. this.textures = new Array();
  24354. }
  24355. /**
  24356. * Adds a parser in the list of available ones
  24357. * @param name Defines the name of the parser
  24358. * @param parser Defines the parser to add
  24359. */
  24360. AbstractScene.AddParser = function (name, parser) {
  24361. this._BabylonFileParsers[name] = parser;
  24362. };
  24363. /**
  24364. * Gets a general parser from the list of avaialble ones
  24365. * @param name Defines the name of the parser
  24366. * @returns the requested parser or null
  24367. */
  24368. AbstractScene.GetParser = function (name) {
  24369. if (this._BabylonFileParsers[name]) {
  24370. return this._BabylonFileParsers[name];
  24371. }
  24372. return null;
  24373. };
  24374. /**
  24375. * Adds n individual parser in the list of available ones
  24376. * @param name Defines the name of the parser
  24377. * @param parser Defines the parser to add
  24378. */
  24379. AbstractScene.AddIndividualParser = function (name, parser) {
  24380. this._IndividualBabylonFileParsers[name] = parser;
  24381. };
  24382. /**
  24383. * Gets an individual parser from the list of avaialble ones
  24384. * @param name Defines the name of the parser
  24385. * @returns the requested parser or null
  24386. */
  24387. AbstractScene.GetIndividualParser = function (name) {
  24388. if (this._IndividualBabylonFileParsers[name]) {
  24389. return this._IndividualBabylonFileParsers[name];
  24390. }
  24391. return null;
  24392. };
  24393. /**
  24394. * Parser json data and populate both a scene and its associated container object
  24395. * @param jsonData Defines the data to parse
  24396. * @param scene Defines the scene to parse the data for
  24397. * @param container Defines the container attached to the parsing sequence
  24398. * @param rootUrl Defines the root url of the data
  24399. */
  24400. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24401. for (var parserName in this._BabylonFileParsers) {
  24402. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24403. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24404. }
  24405. }
  24406. };
  24407. /**
  24408. * Stores the list of available parsers in the application.
  24409. */
  24410. AbstractScene._BabylonFileParsers = {};
  24411. /**
  24412. * Stores the list of available individual parsers in the application.
  24413. */
  24414. AbstractScene._IndividualBabylonFileParsers = {};
  24415. return AbstractScene;
  24416. }());
  24417. BABYLON.AbstractScene = AbstractScene;
  24418. })(BABYLON || (BABYLON = {}));
  24419. //# sourceMappingURL=babylon.abstractScene.js.map
  24420. var BABYLON;
  24421. (function (BABYLON) {
  24422. /** @hidden */
  24423. var ClickInfo = /** @class */ (function () {
  24424. function ClickInfo() {
  24425. this._singleClick = false;
  24426. this._doubleClick = false;
  24427. this._hasSwiped = false;
  24428. this._ignore = false;
  24429. }
  24430. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24431. get: function () {
  24432. return this._singleClick;
  24433. },
  24434. set: function (b) {
  24435. this._singleClick = b;
  24436. },
  24437. enumerable: true,
  24438. configurable: true
  24439. });
  24440. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24441. get: function () {
  24442. return this._doubleClick;
  24443. },
  24444. set: function (b) {
  24445. this._doubleClick = b;
  24446. },
  24447. enumerable: true,
  24448. configurable: true
  24449. });
  24450. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24451. get: function () {
  24452. return this._hasSwiped;
  24453. },
  24454. set: function (b) {
  24455. this._hasSwiped = b;
  24456. },
  24457. enumerable: true,
  24458. configurable: true
  24459. });
  24460. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24461. get: function () {
  24462. return this._ignore;
  24463. },
  24464. set: function (b) {
  24465. this._ignore = b;
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. return ClickInfo;
  24471. }());
  24472. /**
  24473. * This class is used by the onRenderingGroupObservable
  24474. */
  24475. var RenderingGroupInfo = /** @class */ (function () {
  24476. function RenderingGroupInfo() {
  24477. }
  24478. return RenderingGroupInfo;
  24479. }());
  24480. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24481. /**
  24482. * Represents a scene to be rendered by the engine.
  24483. * @see http://doc.babylonjs.com/features/scene
  24484. */
  24485. var Scene = /** @class */ (function (_super) {
  24486. __extends(Scene, _super);
  24487. /**
  24488. * Creates a new Scene
  24489. * @param engine defines the engine to use to render this scene
  24490. */
  24491. function Scene(engine) {
  24492. var _this = _super.call(this) || this;
  24493. // Members
  24494. /**
  24495. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24496. */
  24497. _this.autoClear = true;
  24498. /**
  24499. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24500. */
  24501. _this.autoClearDepthAndStencil = true;
  24502. /**
  24503. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24504. */
  24505. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24506. /**
  24507. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24508. */
  24509. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24510. _this._forceWireframe = false;
  24511. _this._forcePointsCloud = false;
  24512. /**
  24513. * Gets or sets a boolean indicating if animations are enabled
  24514. */
  24515. _this.animationsEnabled = true;
  24516. _this._animationPropertiesOverride = null;
  24517. /**
  24518. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24519. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24520. */
  24521. _this.useConstantAnimationDeltaTime = false;
  24522. /**
  24523. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24524. * Please note that it requires to run a ray cast through the scene on every frame
  24525. */
  24526. _this.constantlyUpdateMeshUnderPointer = false;
  24527. /**
  24528. * Defines the HTML cursor to use when hovering over interactive elements
  24529. */
  24530. _this.hoverCursor = "pointer";
  24531. /**
  24532. * Defines the HTML default cursor to use (empty by default)
  24533. */
  24534. _this.defaultCursor = "";
  24535. /**
  24536. * This is used to call preventDefault() on pointer down
  24537. * in order to block unwanted artifacts like system double clicks
  24538. */
  24539. _this.preventDefaultOnPointerDown = true;
  24540. // Metadata
  24541. /**
  24542. * Gets or sets user defined metadata
  24543. */
  24544. _this.metadata = null;
  24545. /**
  24546. * Use this array to add regular expressions used to disable offline support for specific urls
  24547. */
  24548. _this.disableOfflineSupportExceptionRules = new Array();
  24549. /**
  24550. * An event triggered when the scene is disposed.
  24551. */
  24552. _this.onDisposeObservable = new BABYLON.Observable();
  24553. _this._onDisposeObserver = null;
  24554. /**
  24555. * An event triggered before rendering the scene (right after animations and physics)
  24556. */
  24557. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24558. _this._onBeforeRenderObserver = null;
  24559. /**
  24560. * An event triggered after rendering the scene
  24561. */
  24562. _this.onAfterRenderObservable = new BABYLON.Observable();
  24563. _this._onAfterRenderObserver = null;
  24564. /**
  24565. * An event triggered before animating the scene
  24566. */
  24567. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24568. /**
  24569. * An event triggered after animations processing
  24570. */
  24571. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24572. /**
  24573. * An event triggered before draw calls are ready to be sent
  24574. */
  24575. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24576. /**
  24577. * An event triggered after draw calls have been sent
  24578. */
  24579. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24580. /**
  24581. * An event triggered when the scene is ready
  24582. */
  24583. _this.onReadyObservable = new BABYLON.Observable();
  24584. /**
  24585. * An event triggered before rendering a camera
  24586. */
  24587. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24588. _this._onBeforeCameraRenderObserver = null;
  24589. /**
  24590. * An event triggered after rendering a camera
  24591. */
  24592. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24593. _this._onAfterCameraRenderObserver = null;
  24594. /**
  24595. * An event triggered when active meshes evaluation is about to start
  24596. */
  24597. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24598. /**
  24599. * An event triggered when active meshes evaluation is done
  24600. */
  24601. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24602. /**
  24603. * An event triggered when particles rendering is about to start
  24604. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24605. */
  24606. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24607. /**
  24608. * An event triggered when particles rendering is done
  24609. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24610. */
  24611. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24612. /**
  24613. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24614. */
  24615. _this.onDataLoadedObservable = new BABYLON.Observable();
  24616. /**
  24617. * An event triggered when a camera is created
  24618. */
  24619. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24620. /**
  24621. * An event triggered when a camera is removed
  24622. */
  24623. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24624. /**
  24625. * An event triggered when a light is created
  24626. */
  24627. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24628. /**
  24629. * An event triggered when a light is removed
  24630. */
  24631. _this.onLightRemovedObservable = new BABYLON.Observable();
  24632. /**
  24633. * An event triggered when a geometry is created
  24634. */
  24635. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24636. /**
  24637. * An event triggered when a geometry is removed
  24638. */
  24639. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24640. /**
  24641. * An event triggered when a transform node is created
  24642. */
  24643. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24644. /**
  24645. * An event triggered when a transform node is removed
  24646. */
  24647. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24648. /**
  24649. * An event triggered when a mesh is created
  24650. */
  24651. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24652. /**
  24653. * An event triggered when a mesh is removed
  24654. */
  24655. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24656. /**
  24657. * An event triggered when a material is created
  24658. */
  24659. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  24660. /**
  24661. * An event triggered when a material is removed
  24662. */
  24663. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  24664. /**
  24665. * An event triggered when a texture is created
  24666. */
  24667. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  24668. /**
  24669. * An event triggered when a texture is removed
  24670. */
  24671. _this.onTextureRemovedObservable = new BABYLON.Observable();
  24672. /**
  24673. * An event triggered when render targets are about to be rendered
  24674. * Can happen multiple times per frame.
  24675. */
  24676. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24677. /**
  24678. * An event triggered when render targets were rendered.
  24679. * Can happen multiple times per frame.
  24680. */
  24681. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24682. /**
  24683. * An event triggered before calculating deterministic simulation step
  24684. */
  24685. _this.onBeforeStepObservable = new BABYLON.Observable();
  24686. /**
  24687. * An event triggered after calculating deterministic simulation step
  24688. */
  24689. _this.onAfterStepObservable = new BABYLON.Observable();
  24690. /**
  24691. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24692. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24693. * 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)
  24694. */
  24695. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24696. /**
  24697. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24698. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24699. * 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)
  24700. */
  24701. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24702. /**
  24703. * This Observable will when a mesh has been imported into the scene.
  24704. */
  24705. _this.onMeshImportedObservable = new BABYLON.Observable();
  24706. // Animations
  24707. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24708. /**
  24709. * 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).
  24710. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24711. */
  24712. _this.onPrePointerObservable = new BABYLON.Observable();
  24713. /**
  24714. * Observable event triggered each time an input event is received from the rendering canvas
  24715. */
  24716. _this.onPointerObservable = new BABYLON.Observable();
  24717. _this._meshPickProceed = false;
  24718. _this._currentPickResult = null;
  24719. _this._previousPickResult = null;
  24720. _this._totalPointersPressed = 0;
  24721. _this._doubleClickOccured = false;
  24722. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24723. _this.cameraToUseForPointers = null;
  24724. _this._pointerX = 0;
  24725. _this._pointerY = 0;
  24726. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24727. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24728. _this._startingPointerTime = 0;
  24729. _this._previousStartingPointerTime = 0;
  24730. _this._pointerCaptures = {};
  24731. // Deterministic lockstep
  24732. _this._timeAccumulator = 0;
  24733. _this._currentStepId = 0;
  24734. _this._currentInternalStep = 0;
  24735. // Keyboard
  24736. /**
  24737. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24738. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24739. */
  24740. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24741. /**
  24742. * Observable event triggered each time an keyboard event is received from the hosting window
  24743. */
  24744. _this.onKeyboardObservable = new BABYLON.Observable();
  24745. // Coordinates system
  24746. _this._useRightHandedSystem = false;
  24747. // Fog
  24748. _this._fogEnabled = true;
  24749. _this._fogMode = Scene.FOGMODE_NONE;
  24750. /**
  24751. * Gets or sets the fog color to use
  24752. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24753. * (Default is Color3(0.2, 0.2, 0.3))
  24754. */
  24755. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24756. /**
  24757. * Gets or sets the fog density to use
  24758. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24759. * (Default is 0.1)
  24760. */
  24761. _this.fogDensity = 0.1;
  24762. /**
  24763. * Gets or sets the fog start distance to use
  24764. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24765. * (Default is 0)
  24766. */
  24767. _this.fogStart = 0;
  24768. /**
  24769. * Gets or sets the fog end distance to use
  24770. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24771. * (Default is 1000)
  24772. */
  24773. _this.fogEnd = 1000.0;
  24774. // Lights
  24775. _this._shadowsEnabled = true;
  24776. _this._lightsEnabled = true;
  24777. /** All of the active cameras added to this scene. */
  24778. _this.activeCameras = new Array();
  24779. // Textures
  24780. _this._texturesEnabled = true;
  24781. // Particles
  24782. /**
  24783. * Gets or sets a boolean indicating if particles are enabled on this scene
  24784. */
  24785. _this.particlesEnabled = true;
  24786. // Sprites
  24787. /**
  24788. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24789. */
  24790. _this.spritesEnabled = true;
  24791. // Skeletons
  24792. _this._skeletonsEnabled = true;
  24793. // Lens flares
  24794. /**
  24795. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24796. */
  24797. _this.lensFlaresEnabled = true;
  24798. // Collisions
  24799. /**
  24800. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24801. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24802. */
  24803. _this.collisionsEnabled = true;
  24804. /**
  24805. * Defines the gravity applied to this scene (used only for collisions)
  24806. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24807. */
  24808. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24809. // Postprocesses
  24810. /**
  24811. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24812. */
  24813. _this.postProcessesEnabled = true;
  24814. /**
  24815. * The list of postprocesses added to the scene
  24816. */
  24817. _this.postProcesses = new Array();
  24818. // Customs render targets
  24819. /**
  24820. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24821. */
  24822. _this.renderTargetsEnabled = true;
  24823. /**
  24824. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24825. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24826. */
  24827. _this.dumpNextRenderTargets = false;
  24828. /**
  24829. * The list of user defined render targets added to the scene
  24830. */
  24831. _this.customRenderTargets = new Array();
  24832. /**
  24833. * Gets the list of meshes imported to the scene through SceneLoader
  24834. */
  24835. _this.importedMeshesFiles = new Array();
  24836. // Probes
  24837. /**
  24838. * Gets or sets a boolean indicating if probes are enabled on this scene
  24839. */
  24840. _this.probesEnabled = true;
  24841. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24842. // Procedural textures
  24843. /**
  24844. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24845. */
  24846. _this.proceduralTexturesEnabled = true;
  24847. // Performance counters
  24848. _this._totalVertices = new BABYLON.PerfCounter();
  24849. /** @hidden */
  24850. _this._activeIndices = new BABYLON.PerfCounter();
  24851. /** @hidden */
  24852. _this._activeParticles = new BABYLON.PerfCounter();
  24853. /** @hidden */
  24854. _this._activeBones = new BABYLON.PerfCounter();
  24855. _this._animationTime = 0;
  24856. /**
  24857. * Gets or sets a general scale for animation speed
  24858. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24859. */
  24860. _this.animationTimeScale = 1;
  24861. _this._renderId = 0;
  24862. _this._frameId = 0;
  24863. _this._executeWhenReadyTimeoutId = -1;
  24864. _this._intermediateRendering = false;
  24865. _this._viewUpdateFlag = -1;
  24866. _this._projectionUpdateFlag = -1;
  24867. _this._alternateViewUpdateFlag = -1;
  24868. _this._alternateProjectionUpdateFlag = -1;
  24869. /** @hidden */
  24870. _this._toBeDisposed = new Array(256);
  24871. _this._activeRequests = new Array();
  24872. _this._pendingData = new Array();
  24873. _this._isDisposed = false;
  24874. /**
  24875. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24876. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24877. */
  24878. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24879. _this._activeMeshes = new BABYLON.SmartArray(256);
  24880. _this._processedMaterials = new BABYLON.SmartArray(256);
  24881. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24882. /** @hidden */
  24883. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24884. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24885. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24886. /** @hidden */
  24887. _this._activeAnimatables = new Array();
  24888. _this._transformMatrix = BABYLON.Matrix.Zero();
  24889. _this._useAlternateCameraConfiguration = false;
  24890. _this._alternateRendering = false;
  24891. /**
  24892. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24893. * This is useful if there are more lights that the maximum simulteanous authorized
  24894. */
  24895. _this.requireLightSorting = false;
  24896. /**
  24897. * @hidden
  24898. * Backing store of defined scene components.
  24899. */
  24900. _this._components = [];
  24901. /**
  24902. * @hidden
  24903. * Backing store of defined scene components.
  24904. */
  24905. _this._serializableComponents = [];
  24906. /**
  24907. * List of components to register on the next registration step.
  24908. */
  24909. _this._transientComponents = [];
  24910. /**
  24911. * @hidden
  24912. * Defines the actions happening before camera updates.
  24913. */
  24914. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24915. /**
  24916. * @hidden
  24917. * Defines the actions happening before clear the canvas.
  24918. */
  24919. _this._beforeClearStage = BABYLON.Stage.Create();
  24920. /**
  24921. * @hidden
  24922. * Defines the actions when collecting render targets for the frame.
  24923. */
  24924. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24925. /**
  24926. * @hidden
  24927. * Defines the actions happening for one camera in the frame.
  24928. */
  24929. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24930. /**
  24931. * @hidden
  24932. * Defines the actions happening during the per mesh ready checks.
  24933. */
  24934. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24935. /**
  24936. * @hidden
  24937. * Defines the actions happening before evaluate active mesh checks.
  24938. */
  24939. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24940. /**
  24941. * @hidden
  24942. * Defines the actions happening during the evaluate sub mesh checks.
  24943. */
  24944. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24945. /**
  24946. * @hidden
  24947. * Defines the actions happening during the active mesh stage.
  24948. */
  24949. _this._activeMeshStage = BABYLON.Stage.Create();
  24950. /**
  24951. * @hidden
  24952. * Defines the actions happening during the per camera render target step.
  24953. */
  24954. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24955. /**
  24956. * @hidden
  24957. * Defines the actions happening just before the active camera is drawing.
  24958. */
  24959. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24960. /**
  24961. * @hidden
  24962. * Defines the actions happening just before a rendering group is drawing.
  24963. */
  24964. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24965. /**
  24966. * @hidden
  24967. * Defines the actions happening just before a mesh is drawing.
  24968. */
  24969. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24970. /**
  24971. * @hidden
  24972. * Defines the actions happening just after a mesh has been drawn.
  24973. */
  24974. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24975. /**
  24976. * @hidden
  24977. * Defines the actions happening just after a rendering group has been drawn.
  24978. */
  24979. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24980. /**
  24981. * @hidden
  24982. * Defines the actions happening just after the active camera has been drawn.
  24983. */
  24984. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24985. /**
  24986. * @hidden
  24987. * Defines the actions happening just after rendering all cameras and computing intersections.
  24988. */
  24989. _this._afterRenderStage = BABYLON.Stage.Create();
  24990. /**
  24991. * @hidden
  24992. * Defines the actions happening when a pointer move event happens.
  24993. */
  24994. _this._pointerMoveStage = BABYLON.Stage.Create();
  24995. /**
  24996. * @hidden
  24997. * Defines the actions happening when a pointer down event happens.
  24998. */
  24999. _this._pointerDownStage = BABYLON.Stage.Create();
  25000. /**
  25001. * @hidden
  25002. * Defines the actions happening when a pointer up event happens.
  25003. */
  25004. _this._pointerUpStage = BABYLON.Stage.Create();
  25005. _this._defaultMeshCandidates = {
  25006. data: [],
  25007. length: 0
  25008. };
  25009. _this._defaultSubMeshCandidates = {
  25010. data: [],
  25011. length: 0
  25012. };
  25013. _this._activeMeshesFrozen = false;
  25014. /** @hidden */
  25015. _this._allowPostProcessClearColor = true;
  25016. /**
  25017. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25018. */
  25019. _this.getDeterministicFrameTime = function () {
  25020. return 1000.0 / 60.0; // frame time in ms
  25021. };
  25022. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25023. _this._blockMaterialDirtyMechanism = false;
  25024. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25025. _this._engine.scenes.push(_this);
  25026. _this._uid = null;
  25027. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25028. if (BABYLON.PostProcessManager) {
  25029. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25030. }
  25031. if (BABYLON.Tools.IsWindowObjectExist()) {
  25032. _this.attachControl();
  25033. }
  25034. //collision coordinator initialization. For now legacy per default.
  25035. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25036. // Uniform Buffer
  25037. _this._createUbo();
  25038. // Default Image processing definition
  25039. if (BABYLON.ImageProcessingConfiguration) {
  25040. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25041. }
  25042. _this.setDefaultCandidateProviders();
  25043. return _this;
  25044. }
  25045. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25046. /**
  25047. * Texture used in all pbr material as the reflection texture.
  25048. * As in the majority of the scene they are the same (exception for multi room and so on),
  25049. * this is easier to reference from here than from all the materials.
  25050. */
  25051. get: function () {
  25052. return this._environmentTexture;
  25053. },
  25054. /**
  25055. * Texture used in all pbr material as the reflection texture.
  25056. * As in the majority of the scene they are the same (exception for multi room and so on),
  25057. * this is easier to set here than in all the materials.
  25058. */
  25059. set: function (value) {
  25060. if (this._environmentTexture === value) {
  25061. return;
  25062. }
  25063. this._environmentTexture = value;
  25064. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25065. },
  25066. enumerable: true,
  25067. configurable: true
  25068. });
  25069. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25070. /**
  25071. * Default image processing configuration used either in the rendering
  25072. * Forward main pass or through the imageProcessingPostProcess if present.
  25073. * As in the majority of the scene they are the same (exception for multi camera),
  25074. * this is easier to reference from here than from all the materials and post process.
  25075. *
  25076. * No setter as we it is a shared configuration, you can set the values instead.
  25077. */
  25078. get: function () {
  25079. return this._imageProcessingConfiguration;
  25080. },
  25081. enumerable: true,
  25082. configurable: true
  25083. });
  25084. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25085. get: function () {
  25086. return this._forceWireframe;
  25087. },
  25088. /**
  25089. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25090. */
  25091. set: function (value) {
  25092. if (this._forceWireframe === value) {
  25093. return;
  25094. }
  25095. this._forceWireframe = value;
  25096. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25097. },
  25098. enumerable: true,
  25099. configurable: true
  25100. });
  25101. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25102. get: function () {
  25103. return this._forcePointsCloud;
  25104. },
  25105. /**
  25106. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25107. */
  25108. set: function (value) {
  25109. if (this._forcePointsCloud === value) {
  25110. return;
  25111. }
  25112. this._forcePointsCloud = value;
  25113. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25114. },
  25115. enumerable: true,
  25116. configurable: true
  25117. });
  25118. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25119. /**
  25120. * Gets or sets the animation properties override
  25121. */
  25122. get: function () {
  25123. return this._animationPropertiesOverride;
  25124. },
  25125. set: function (value) {
  25126. this._animationPropertiesOverride = value;
  25127. },
  25128. enumerable: true,
  25129. configurable: true
  25130. });
  25131. Object.defineProperty(Scene.prototype, "onDispose", {
  25132. /** Sets a function to be executed when this scene is disposed. */
  25133. set: function (callback) {
  25134. if (this._onDisposeObserver) {
  25135. this.onDisposeObservable.remove(this._onDisposeObserver);
  25136. }
  25137. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25138. },
  25139. enumerable: true,
  25140. configurable: true
  25141. });
  25142. Object.defineProperty(Scene.prototype, "beforeRender", {
  25143. /** Sets a function to be executed before rendering this scene */
  25144. set: function (callback) {
  25145. if (this._onBeforeRenderObserver) {
  25146. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25147. }
  25148. if (callback) {
  25149. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25150. }
  25151. },
  25152. enumerable: true,
  25153. configurable: true
  25154. });
  25155. Object.defineProperty(Scene.prototype, "afterRender", {
  25156. /** Sets a function to be executed after rendering this scene */
  25157. set: function (callback) {
  25158. if (this._onAfterRenderObserver) {
  25159. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25160. }
  25161. if (callback) {
  25162. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25163. }
  25164. },
  25165. enumerable: true,
  25166. configurable: true
  25167. });
  25168. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25169. /** Sets a function to be executed before rendering a camera*/
  25170. set: function (callback) {
  25171. if (this._onBeforeCameraRenderObserver) {
  25172. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25173. }
  25174. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25175. },
  25176. enumerable: true,
  25177. configurable: true
  25178. });
  25179. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25180. /** Sets a function to be executed after rendering a camera*/
  25181. set: function (callback) {
  25182. if (this._onAfterCameraRenderObserver) {
  25183. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25184. }
  25185. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25186. },
  25187. enumerable: true,
  25188. configurable: true
  25189. });
  25190. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25191. /**
  25192. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25193. */
  25194. get: function () {
  25195. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25196. },
  25197. enumerable: true,
  25198. configurable: true
  25199. });
  25200. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25201. get: function () {
  25202. return this._useRightHandedSystem;
  25203. },
  25204. /**
  25205. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25206. */
  25207. set: function (value) {
  25208. if (this._useRightHandedSystem === value) {
  25209. return;
  25210. }
  25211. this._useRightHandedSystem = value;
  25212. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25213. },
  25214. enumerable: true,
  25215. configurable: true
  25216. });
  25217. /**
  25218. * Sets the step Id used by deterministic lock step
  25219. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25220. * @param newStepId defines the step Id
  25221. */
  25222. Scene.prototype.setStepId = function (newStepId) {
  25223. this._currentStepId = newStepId;
  25224. };
  25225. ;
  25226. /**
  25227. * Gets the step Id used by deterministic lock step
  25228. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25229. * @returns the step Id
  25230. */
  25231. Scene.prototype.getStepId = function () {
  25232. return this._currentStepId;
  25233. };
  25234. ;
  25235. /**
  25236. * Gets the internal step used by deterministic lock step
  25237. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25238. * @returns the internal step
  25239. */
  25240. Scene.prototype.getInternalStep = function () {
  25241. return this._currentInternalStep;
  25242. };
  25243. ;
  25244. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25245. get: function () {
  25246. return this._fogEnabled;
  25247. },
  25248. /**
  25249. * Gets or sets a boolean indicating if fog is enabled on this scene
  25250. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25251. * (Default is true)
  25252. */
  25253. set: function (value) {
  25254. if (this._fogEnabled === value) {
  25255. return;
  25256. }
  25257. this._fogEnabled = value;
  25258. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25259. },
  25260. enumerable: true,
  25261. configurable: true
  25262. });
  25263. Object.defineProperty(Scene.prototype, "fogMode", {
  25264. get: function () {
  25265. return this._fogMode;
  25266. },
  25267. /**
  25268. * Gets or sets the fog mode to use
  25269. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25270. * | mode | value |
  25271. * | --- | --- |
  25272. * | FOGMODE_NONE | 0 |
  25273. * | FOGMODE_EXP | 1 |
  25274. * | FOGMODE_EXP2 | 2 |
  25275. * | FOGMODE_LINEAR | 3 |
  25276. */
  25277. set: function (value) {
  25278. if (this._fogMode === value) {
  25279. return;
  25280. }
  25281. this._fogMode = value;
  25282. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25283. },
  25284. enumerable: true,
  25285. configurable: true
  25286. });
  25287. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25288. get: function () {
  25289. return this._shadowsEnabled;
  25290. },
  25291. /**
  25292. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25293. */
  25294. set: function (value) {
  25295. if (this._shadowsEnabled === value) {
  25296. return;
  25297. }
  25298. this._shadowsEnabled = value;
  25299. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25300. },
  25301. enumerable: true,
  25302. configurable: true
  25303. });
  25304. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25305. get: function () {
  25306. return this._lightsEnabled;
  25307. },
  25308. /**
  25309. * Gets or sets a boolean indicating if lights are enabled on this scene
  25310. */
  25311. set: function (value) {
  25312. if (this._lightsEnabled === value) {
  25313. return;
  25314. }
  25315. this._lightsEnabled = value;
  25316. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25317. },
  25318. enumerable: true,
  25319. configurable: true
  25320. });
  25321. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25322. /** The default material used on meshes when no material is affected */
  25323. get: function () {
  25324. if (!this._defaultMaterial) {
  25325. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25326. }
  25327. return this._defaultMaterial;
  25328. },
  25329. /** The default material used on meshes when no material is affected */
  25330. set: function (value) {
  25331. this._defaultMaterial = value;
  25332. },
  25333. enumerable: true,
  25334. configurable: true
  25335. });
  25336. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25337. get: function () {
  25338. return this._texturesEnabled;
  25339. },
  25340. /**
  25341. * Gets or sets a boolean indicating if textures are enabled on this scene
  25342. */
  25343. set: function (value) {
  25344. if (this._texturesEnabled === value) {
  25345. return;
  25346. }
  25347. this._texturesEnabled = value;
  25348. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25349. },
  25350. enumerable: true,
  25351. configurable: true
  25352. });
  25353. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25354. get: function () {
  25355. return this._skeletonsEnabled;
  25356. },
  25357. /**
  25358. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25359. */
  25360. set: function (value) {
  25361. if (this._skeletonsEnabled === value) {
  25362. return;
  25363. }
  25364. this._skeletonsEnabled = value;
  25365. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25366. },
  25367. enumerable: true,
  25368. configurable: true
  25369. });
  25370. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25371. /** @hidden */
  25372. get: function () {
  25373. return this._alternateRendering;
  25374. },
  25375. enumerable: true,
  25376. configurable: true
  25377. });
  25378. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25379. /**
  25380. * Gets the list of frustum planes (built from the active camera)
  25381. */
  25382. get: function () {
  25383. return this._frustumPlanes;
  25384. },
  25385. enumerable: true,
  25386. configurable: true
  25387. });
  25388. /**
  25389. * Registers the transient components if needed.
  25390. */
  25391. Scene.prototype._registerTransientComponents = function () {
  25392. // Register components that have been associated lately to the scene.
  25393. if (this._transientComponents.length > 0) {
  25394. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25395. var component = _a[_i];
  25396. component.register();
  25397. }
  25398. this._transientComponents = [];
  25399. }
  25400. };
  25401. /**
  25402. * @hidden
  25403. * Add a component to the scene.
  25404. * Note that the ccomponent could be registered on th next frame if this is called after
  25405. * the register component stage.
  25406. * @param component Defines the component to add to the scene
  25407. */
  25408. Scene.prototype._addComponent = function (component) {
  25409. this._components.push(component);
  25410. this._transientComponents.push(component);
  25411. var serializableComponent = component;
  25412. if (serializableComponent.addFromContainer) {
  25413. this._serializableComponents.push(serializableComponent);
  25414. }
  25415. };
  25416. /**
  25417. * @hidden
  25418. * Gets a component from the scene.
  25419. * @param name defines the name of the component to retrieve
  25420. * @returns the component or null if not present
  25421. */
  25422. Scene.prototype._getComponent = function (name) {
  25423. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25424. var component = _a[_i];
  25425. if (component.name === name) {
  25426. return component;
  25427. }
  25428. }
  25429. return null;
  25430. };
  25431. /**
  25432. * @hidden
  25433. */
  25434. Scene.prototype._getDefaultMeshCandidates = function () {
  25435. this._defaultMeshCandidates.data = this.meshes;
  25436. this._defaultMeshCandidates.length = this.meshes.length;
  25437. return this._defaultMeshCandidates;
  25438. };
  25439. /**
  25440. * @hidden
  25441. */
  25442. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25443. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25444. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25445. return this._defaultSubMeshCandidates;
  25446. };
  25447. /**
  25448. * Sets the default candidate providers for the scene.
  25449. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25450. * and getCollidingSubMeshCandidates to their default function
  25451. */
  25452. Scene.prototype.setDefaultCandidateProviders = function () {
  25453. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25454. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25455. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25456. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25457. };
  25458. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25459. /**
  25460. * Gets a boolean indicating if collisions are processed on a web worker
  25461. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25462. */
  25463. get: function () {
  25464. return this._workerCollisions;
  25465. },
  25466. set: function (enabled) {
  25467. if (!BABYLON.CollisionCoordinatorLegacy) {
  25468. return;
  25469. }
  25470. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25471. this._workerCollisions = enabled;
  25472. if (this.collisionCoordinator) {
  25473. this.collisionCoordinator.destroy();
  25474. }
  25475. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25476. this.collisionCoordinator.init(this);
  25477. },
  25478. enumerable: true,
  25479. configurable: true
  25480. });
  25481. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25482. /**
  25483. * Gets the mesh that is currently under the pointer
  25484. */
  25485. get: function () {
  25486. return this._pointerOverMesh;
  25487. },
  25488. enumerable: true,
  25489. configurable: true
  25490. });
  25491. Object.defineProperty(Scene.prototype, "pointerX", {
  25492. /**
  25493. * Gets the current on-screen X position of the pointer
  25494. */
  25495. get: function () {
  25496. return this._pointerX;
  25497. },
  25498. enumerable: true,
  25499. configurable: true
  25500. });
  25501. Object.defineProperty(Scene.prototype, "pointerY", {
  25502. /**
  25503. * Gets the current on-screen Y position of the pointer
  25504. */
  25505. get: function () {
  25506. return this._pointerY;
  25507. },
  25508. enumerable: true,
  25509. configurable: true
  25510. });
  25511. /**
  25512. * Gets the cached material (ie. the latest rendered one)
  25513. * @returns the cached material
  25514. */
  25515. Scene.prototype.getCachedMaterial = function () {
  25516. return this._cachedMaterial;
  25517. };
  25518. /**
  25519. * Gets the cached effect (ie. the latest rendered one)
  25520. * @returns the cached effect
  25521. */
  25522. Scene.prototype.getCachedEffect = function () {
  25523. return this._cachedEffect;
  25524. };
  25525. /**
  25526. * Gets the cached visibility state (ie. the latest rendered one)
  25527. * @returns the cached visibility state
  25528. */
  25529. Scene.prototype.getCachedVisibility = function () {
  25530. return this._cachedVisibility;
  25531. };
  25532. /**
  25533. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25534. * @param material defines the current material
  25535. * @param effect defines the current effect
  25536. * @param visibility defines the current visibility state
  25537. * @returns true if one parameter is not cached
  25538. */
  25539. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25540. if (visibility === void 0) { visibility = 1; }
  25541. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25542. };
  25543. /**
  25544. * Gets the engine associated with the scene
  25545. * @returns an Engine
  25546. */
  25547. Scene.prototype.getEngine = function () {
  25548. return this._engine;
  25549. };
  25550. /**
  25551. * Gets the total number of vertices rendered per frame
  25552. * @returns the total number of vertices rendered per frame
  25553. */
  25554. Scene.prototype.getTotalVertices = function () {
  25555. return this._totalVertices.current;
  25556. };
  25557. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25558. /**
  25559. * Gets the performance counter for total vertices
  25560. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25561. */
  25562. get: function () {
  25563. return this._totalVertices;
  25564. },
  25565. enumerable: true,
  25566. configurable: true
  25567. });
  25568. /**
  25569. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25570. * @returns the total number of active indices rendered per frame
  25571. */
  25572. Scene.prototype.getActiveIndices = function () {
  25573. return this._activeIndices.current;
  25574. };
  25575. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25576. /**
  25577. * Gets the performance counter for active indices
  25578. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25579. */
  25580. get: function () {
  25581. return this._activeIndices;
  25582. },
  25583. enumerable: true,
  25584. configurable: true
  25585. });
  25586. /**
  25587. * Gets the total number of active particles rendered per frame
  25588. * @returns the total number of active particles rendered per frame
  25589. */
  25590. Scene.prototype.getActiveParticles = function () {
  25591. return this._activeParticles.current;
  25592. };
  25593. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25594. /**
  25595. * Gets the performance counter for active particles
  25596. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25597. */
  25598. get: function () {
  25599. return this._activeParticles;
  25600. },
  25601. enumerable: true,
  25602. configurable: true
  25603. });
  25604. /**
  25605. * Gets the total number of active bones rendered per frame
  25606. * @returns the total number of active bones rendered per frame
  25607. */
  25608. Scene.prototype.getActiveBones = function () {
  25609. return this._activeBones.current;
  25610. };
  25611. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25612. /**
  25613. * Gets the performance counter for active bones
  25614. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25615. */
  25616. get: function () {
  25617. return this._activeBones;
  25618. },
  25619. enumerable: true,
  25620. configurable: true
  25621. });
  25622. /** @hidden */
  25623. Scene.prototype.getInterFramePerfCounter = function () {
  25624. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25625. return 0;
  25626. };
  25627. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25628. /** @hidden */
  25629. get: function () {
  25630. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25631. return null;
  25632. },
  25633. enumerable: true,
  25634. configurable: true
  25635. });
  25636. /** @hidden */
  25637. Scene.prototype.getLastFrameDuration = function () {
  25638. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25639. return 0;
  25640. };
  25641. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25642. /** @hidden */
  25643. get: function () {
  25644. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25645. return null;
  25646. },
  25647. enumerable: true,
  25648. configurable: true
  25649. });
  25650. /** @hidden */
  25651. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25652. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25653. return 0;
  25654. };
  25655. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25656. /** @hidden */
  25657. get: function () {
  25658. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25659. return null;
  25660. },
  25661. enumerable: true,
  25662. configurable: true
  25663. });
  25664. /**
  25665. * Gets the array of active meshes
  25666. * @returns an array of AbstractMesh
  25667. */
  25668. Scene.prototype.getActiveMeshes = function () {
  25669. return this._activeMeshes;
  25670. };
  25671. /** @hidden */
  25672. Scene.prototype.getRenderTargetsDuration = function () {
  25673. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25674. return 0;
  25675. };
  25676. /** @hidden */
  25677. Scene.prototype.getRenderDuration = function () {
  25678. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25679. return 0;
  25680. };
  25681. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25682. /** @hidden */
  25683. get: function () {
  25684. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25685. return null;
  25686. },
  25687. enumerable: true,
  25688. configurable: true
  25689. });
  25690. /** @hidden */
  25691. Scene.prototype.getParticlesDuration = function () {
  25692. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25693. return 0;
  25694. };
  25695. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25696. /** @hidden */
  25697. get: function () {
  25698. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25699. return null;
  25700. },
  25701. enumerable: true,
  25702. configurable: true
  25703. });
  25704. /** @hidden */
  25705. Scene.prototype.getSpritesDuration = function () {
  25706. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25707. return 0;
  25708. };
  25709. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25710. /** @hidden */
  25711. get: function () {
  25712. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25713. return null;
  25714. },
  25715. enumerable: true,
  25716. configurable: true
  25717. });
  25718. /**
  25719. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25720. * @returns a number
  25721. */
  25722. Scene.prototype.getAnimationRatio = function () {
  25723. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25724. };
  25725. /**
  25726. * Gets an unique Id for the current render phase
  25727. * @returns a number
  25728. */
  25729. Scene.prototype.getRenderId = function () {
  25730. return this._renderId;
  25731. };
  25732. /**
  25733. * Gets an unique Id for the current frame
  25734. * @returns a number
  25735. */
  25736. Scene.prototype.getFrameId = function () {
  25737. return this._frameId;
  25738. };
  25739. /** Call this function if you want to manually increment the render Id*/
  25740. Scene.prototype.incrementRenderId = function () {
  25741. this._renderId++;
  25742. };
  25743. Scene.prototype._updatePointerPosition = function (evt) {
  25744. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25745. if (!canvasRect) {
  25746. return;
  25747. }
  25748. this._pointerX = evt.clientX - canvasRect.left;
  25749. this._pointerY = evt.clientY - canvasRect.top;
  25750. this._unTranslatedPointerX = this._pointerX;
  25751. this._unTranslatedPointerY = this._pointerY;
  25752. };
  25753. Scene.prototype._createUbo = function () {
  25754. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25755. this._sceneUbo.addUniform("viewProjection", 16);
  25756. this._sceneUbo.addUniform("view", 16);
  25757. };
  25758. Scene.prototype._createAlternateUbo = function () {
  25759. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25760. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25761. this._alternateSceneUbo.addUniform("view", 16);
  25762. };
  25763. // Pointers handling
  25764. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25765. if (pointerInfo.pickInfo) {
  25766. if (!pointerInfo.pickInfo.ray) {
  25767. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25768. }
  25769. }
  25770. };
  25771. /**
  25772. * Use this method to simulate a pointer move on a mesh
  25773. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25774. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25775. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25776. * @returns the current scene
  25777. */
  25778. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25779. var evt = new PointerEvent("pointermove", pointerEventInit);
  25780. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25781. return this;
  25782. }
  25783. return this._processPointerMove(pickResult, evt);
  25784. };
  25785. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25786. var canvas = this._engine.getRenderingCanvas();
  25787. if (!canvas) {
  25788. return this;
  25789. }
  25790. // Restore pointer
  25791. canvas.style.cursor = this.defaultCursor;
  25792. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25793. if (isMeshPicked) {
  25794. this.setPointerOverMesh(pickResult.pickedMesh);
  25795. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25796. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25797. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25798. }
  25799. else {
  25800. canvas.style.cursor = this.hoverCursor;
  25801. }
  25802. }
  25803. }
  25804. else {
  25805. this.setPointerOverMesh(null);
  25806. }
  25807. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25808. var step = _a[_i];
  25809. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25810. }
  25811. if (pickResult) {
  25812. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25813. if (this.onPointerMove) {
  25814. this.onPointerMove(evt, pickResult, type);
  25815. }
  25816. if (this.onPointerObservable.hasObservers()) {
  25817. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25818. this._setRayOnPointerInfo(pi);
  25819. this.onPointerObservable.notifyObservers(pi, type);
  25820. }
  25821. }
  25822. return this;
  25823. };
  25824. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25825. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25826. if (pickResult) {
  25827. pi.ray = pickResult.ray;
  25828. }
  25829. this.onPrePointerObservable.notifyObservers(pi, type);
  25830. if (pi.skipOnPointerObservable) {
  25831. return true;
  25832. }
  25833. else {
  25834. return false;
  25835. }
  25836. };
  25837. /**
  25838. * Use this method to simulate a pointer down on a mesh
  25839. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25840. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25841. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25842. * @returns the current scene
  25843. */
  25844. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25845. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25846. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25847. return this;
  25848. }
  25849. return this._processPointerDown(pickResult, evt);
  25850. };
  25851. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25852. var _this = this;
  25853. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25854. this._pickedDownMesh = pickResult.pickedMesh;
  25855. var actionManager = pickResult.pickedMesh.actionManager;
  25856. if (actionManager) {
  25857. if (actionManager.hasPickTriggers) {
  25858. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25859. switch (evt.button) {
  25860. case 0:
  25861. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25862. break;
  25863. case 1:
  25864. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25865. break;
  25866. case 2:
  25867. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25868. break;
  25869. }
  25870. }
  25871. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25872. window.setTimeout(function () {
  25873. 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);
  25874. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25875. if (_this._totalPointersPressed !== 0 &&
  25876. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25877. !_this._isPointerSwiping()) {
  25878. _this._startingPointerTime = 0;
  25879. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25880. }
  25881. }
  25882. }, Scene.LongPressDelay);
  25883. }
  25884. }
  25885. }
  25886. else {
  25887. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25888. var step = _a[_i];
  25889. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25890. }
  25891. }
  25892. if (pickResult) {
  25893. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25894. if (this.onPointerDown) {
  25895. this.onPointerDown(evt, pickResult, type);
  25896. }
  25897. if (this.onPointerObservable.hasObservers()) {
  25898. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25899. this._setRayOnPointerInfo(pi);
  25900. this.onPointerObservable.notifyObservers(pi, type);
  25901. }
  25902. }
  25903. return this;
  25904. };
  25905. /**
  25906. * Use this method to simulate a pointer up on a mesh
  25907. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25908. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25909. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25910. * @returns the current scene
  25911. */
  25912. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25913. var evt = new PointerEvent("pointerup", pointerEventInit);
  25914. var clickInfo = new ClickInfo();
  25915. clickInfo.singleClick = true;
  25916. clickInfo.ignore = true;
  25917. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25918. return this;
  25919. }
  25920. return this._processPointerUp(pickResult, evt, clickInfo);
  25921. };
  25922. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25923. if (pickResult && pickResult && pickResult.pickedMesh) {
  25924. this._pickedUpMesh = pickResult.pickedMesh;
  25925. if (this._pickedDownMesh === this._pickedUpMesh) {
  25926. if (this.onPointerPick) {
  25927. this.onPointerPick(evt, pickResult);
  25928. }
  25929. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25930. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25931. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25932. this._setRayOnPointerInfo(pi);
  25933. this.onPointerObservable.notifyObservers(pi, type_1);
  25934. }
  25935. }
  25936. if (pickResult.pickedMesh.actionManager) {
  25937. if (clickInfo.ignore) {
  25938. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25939. }
  25940. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25941. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25942. }
  25943. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25944. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25945. }
  25946. }
  25947. }
  25948. else {
  25949. if (!clickInfo.ignore) {
  25950. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25951. var step = _a[_i];
  25952. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25953. }
  25954. }
  25955. }
  25956. if (this._pickedDownMesh &&
  25957. this._pickedDownMesh.actionManager &&
  25958. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25959. this._pickedDownMesh !== this._pickedUpMesh) {
  25960. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25961. }
  25962. var type = BABYLON.PointerEventTypes.POINTERUP;
  25963. if (this.onPointerObservable.hasObservers()) {
  25964. if (!clickInfo.ignore) {
  25965. if (!clickInfo.hasSwiped) {
  25966. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25967. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25968. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25969. this._setRayOnPointerInfo(pi);
  25970. this.onPointerObservable.notifyObservers(pi, type_2);
  25971. }
  25972. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25973. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25974. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25975. this._setRayOnPointerInfo(pi);
  25976. this.onPointerObservable.notifyObservers(pi, type_3);
  25977. }
  25978. }
  25979. }
  25980. else {
  25981. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25982. this._setRayOnPointerInfo(pi);
  25983. this.onPointerObservable.notifyObservers(pi, type);
  25984. }
  25985. }
  25986. if (this.onPointerUp) {
  25987. this.onPointerUp(evt, pickResult, type);
  25988. }
  25989. return this;
  25990. };
  25991. /**
  25992. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25993. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25994. * @returns true if the pointer was captured
  25995. */
  25996. Scene.prototype.isPointerCaptured = function (pointerId) {
  25997. if (pointerId === void 0) { pointerId = 0; }
  25998. return this._pointerCaptures[pointerId];
  25999. };
  26000. /** @hidden */
  26001. Scene.prototype._isPointerSwiping = function () {
  26002. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26003. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26004. };
  26005. /**
  26006. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26007. * @param attachUp defines if you want to attach events to pointerup
  26008. * @param attachDown defines if you want to attach events to pointerdown
  26009. * @param attachMove defines if you want to attach events to pointermove
  26010. */
  26011. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26012. var _this = this;
  26013. if (attachUp === void 0) { attachUp = true; }
  26014. if (attachDown === void 0) { attachDown = true; }
  26015. if (attachMove === void 0) { attachMove = true; }
  26016. this._initActionManager = function (act, clickInfo) {
  26017. if (!_this._meshPickProceed) {
  26018. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26019. _this._currentPickResult = pickResult;
  26020. if (pickResult) {
  26021. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26022. }
  26023. _this._meshPickProceed = true;
  26024. }
  26025. return act;
  26026. };
  26027. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26028. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26029. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26030. btn !== _this._previousButtonPressed) {
  26031. _this._doubleClickOccured = false;
  26032. clickInfo.singleClick = true;
  26033. clickInfo.ignore = false;
  26034. cb(clickInfo, _this._currentPickResult);
  26035. }
  26036. };
  26037. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26038. var clickInfo = new ClickInfo();
  26039. _this._currentPickResult = null;
  26040. var act = null;
  26041. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26042. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26043. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26044. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26045. act = _this._initActionManager(act, clickInfo);
  26046. if (act)
  26047. checkPicking = act.hasPickTriggers;
  26048. }
  26049. if (checkPicking) {
  26050. var btn = evt.button;
  26051. clickInfo.hasSwiped = _this._isPointerSwiping();
  26052. if (!clickInfo.hasSwiped) {
  26053. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26054. if (!checkSingleClickImmediately) {
  26055. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26056. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26057. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26058. act = _this._initActionManager(act, clickInfo);
  26059. if (act)
  26060. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26061. }
  26062. }
  26063. if (checkSingleClickImmediately) {
  26064. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26065. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26066. btn !== _this._previousButtonPressed) {
  26067. clickInfo.singleClick = true;
  26068. cb(clickInfo, _this._currentPickResult);
  26069. }
  26070. }
  26071. // at least one double click is required to be check and exclusive double click is enabled
  26072. else {
  26073. // wait that no double click has been raised during the double click delay
  26074. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26075. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26076. }
  26077. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26078. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26079. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26080. act = _this._initActionManager(act, clickInfo);
  26081. if (act)
  26082. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26083. }
  26084. if (checkDoubleClick) {
  26085. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26086. if (btn === _this._previousButtonPressed &&
  26087. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26088. !_this._doubleClickOccured) {
  26089. // pointer has not moved for 2 clicks, it's a double click
  26090. if (!clickInfo.hasSwiped &&
  26091. !_this._isPointerSwiping()) {
  26092. _this._previousStartingPointerTime = 0;
  26093. _this._doubleClickOccured = true;
  26094. clickInfo.doubleClick = true;
  26095. clickInfo.ignore = false;
  26096. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26097. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26098. }
  26099. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26100. cb(clickInfo, _this._currentPickResult);
  26101. }
  26102. // if the two successive clicks are too far, it's just two simple clicks
  26103. else {
  26104. _this._doubleClickOccured = false;
  26105. _this._previousStartingPointerTime = _this._startingPointerTime;
  26106. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26107. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26108. _this._previousButtonPressed = btn;
  26109. if (Scene.ExclusiveDoubleClickMode) {
  26110. if (_this._previousDelayedSimpleClickTimeout) {
  26111. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26112. }
  26113. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26114. cb(clickInfo, _this._previousPickResult);
  26115. }
  26116. else {
  26117. cb(clickInfo, _this._currentPickResult);
  26118. }
  26119. }
  26120. }
  26121. // just the first click of the double has been raised
  26122. else {
  26123. _this._doubleClickOccured = false;
  26124. _this._previousStartingPointerTime = _this._startingPointerTime;
  26125. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26126. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26127. _this._previousButtonPressed = btn;
  26128. }
  26129. }
  26130. }
  26131. }
  26132. clickInfo.ignore = true;
  26133. cb(clickInfo, _this._currentPickResult);
  26134. };
  26135. this._onPointerMove = function (evt) {
  26136. _this._updatePointerPosition(evt);
  26137. // PreObservable support
  26138. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26139. return;
  26140. }
  26141. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26142. return;
  26143. }
  26144. if (!_this.pointerMovePredicate) {
  26145. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26146. }
  26147. // Meshes
  26148. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26149. _this._processPointerMove(pickResult, evt);
  26150. };
  26151. this._onPointerDown = function (evt) {
  26152. _this._totalPointersPressed++;
  26153. _this._pickedDownMesh = null;
  26154. _this._meshPickProceed = false;
  26155. _this._updatePointerPosition(evt);
  26156. if (_this.preventDefaultOnPointerDown && canvas) {
  26157. evt.preventDefault();
  26158. canvas.focus();
  26159. }
  26160. // PreObservable support
  26161. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26162. return;
  26163. }
  26164. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26165. return;
  26166. }
  26167. _this._pointerCaptures[evt.pointerId] = true;
  26168. _this._startingPointerPosition.x = _this._pointerX;
  26169. _this._startingPointerPosition.y = _this._pointerY;
  26170. _this._startingPointerTime = Date.now();
  26171. if (!_this.pointerDownPredicate) {
  26172. _this.pointerDownPredicate = function (mesh) {
  26173. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26174. };
  26175. }
  26176. // Meshes
  26177. _this._pickedDownMesh = null;
  26178. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26179. _this._processPointerDown(pickResult, evt);
  26180. };
  26181. this._onPointerUp = function (evt) {
  26182. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26183. return; // So we need to test it the pointer down was pressed before.
  26184. }
  26185. _this._totalPointersPressed--;
  26186. _this._pickedUpMesh = null;
  26187. _this._meshPickProceed = false;
  26188. _this._updatePointerPosition(evt);
  26189. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26190. // PreObservable support
  26191. if (_this.onPrePointerObservable.hasObservers()) {
  26192. if (!clickInfo.ignore) {
  26193. if (!clickInfo.hasSwiped) {
  26194. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26195. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26196. return;
  26197. }
  26198. }
  26199. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26200. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26201. return;
  26202. }
  26203. }
  26204. }
  26205. }
  26206. else {
  26207. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26208. return;
  26209. }
  26210. }
  26211. }
  26212. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26213. return;
  26214. }
  26215. _this._pointerCaptures[evt.pointerId] = false;
  26216. if (!_this.pointerUpPredicate) {
  26217. _this.pointerUpPredicate = function (mesh) {
  26218. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26219. };
  26220. }
  26221. // Meshes
  26222. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26223. _this._initActionManager(null, clickInfo);
  26224. }
  26225. if (!pickResult) {
  26226. pickResult = _this._currentPickResult;
  26227. }
  26228. _this._processPointerUp(pickResult, evt, clickInfo);
  26229. _this._previousPickResult = _this._currentPickResult;
  26230. });
  26231. };
  26232. this._onKeyDown = function (evt) {
  26233. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26234. if (_this.onPreKeyboardObservable.hasObservers()) {
  26235. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26236. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26237. if (pi.skipOnPointerObservable) {
  26238. return;
  26239. }
  26240. }
  26241. if (_this.onKeyboardObservable.hasObservers()) {
  26242. var pi = new BABYLON.KeyboardInfo(type, evt);
  26243. _this.onKeyboardObservable.notifyObservers(pi, type);
  26244. }
  26245. if (_this.actionManager) {
  26246. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26247. }
  26248. };
  26249. this._onKeyUp = function (evt) {
  26250. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26251. if (_this.onPreKeyboardObservable.hasObservers()) {
  26252. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26253. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26254. if (pi.skipOnPointerObservable) {
  26255. return;
  26256. }
  26257. }
  26258. if (_this.onKeyboardObservable.hasObservers()) {
  26259. var pi = new BABYLON.KeyboardInfo(type, evt);
  26260. _this.onKeyboardObservable.notifyObservers(pi, type);
  26261. }
  26262. if (_this.actionManager) {
  26263. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26264. }
  26265. };
  26266. var engine = this.getEngine();
  26267. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26268. if (!canvas) {
  26269. return;
  26270. }
  26271. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26272. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26273. });
  26274. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26275. if (!canvas) {
  26276. return;
  26277. }
  26278. canvas.removeEventListener("keydown", _this._onKeyDown);
  26279. canvas.removeEventListener("keyup", _this._onKeyUp);
  26280. });
  26281. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26282. var canvas = this._engine.getRenderingCanvas();
  26283. if (!canvas) {
  26284. return;
  26285. }
  26286. if (attachMove) {
  26287. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26288. // Wheel
  26289. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26290. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26291. }
  26292. if (attachDown) {
  26293. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26294. }
  26295. if (attachUp) {
  26296. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26297. }
  26298. canvas.tabIndex = 1;
  26299. };
  26300. /** Detaches all event handlers*/
  26301. Scene.prototype.detachControl = function () {
  26302. var engine = this.getEngine();
  26303. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26304. var canvas = engine.getRenderingCanvas();
  26305. if (!canvas) {
  26306. return;
  26307. }
  26308. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26309. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26310. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26311. if (this._onCanvasBlurObserver) {
  26312. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26313. }
  26314. if (this._onCanvasFocusObserver) {
  26315. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26316. }
  26317. // Wheel
  26318. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26319. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26320. // Keyboard
  26321. canvas.removeEventListener("keydown", this._onKeyDown);
  26322. canvas.removeEventListener("keyup", this._onKeyUp);
  26323. // Observables
  26324. this.onKeyboardObservable.clear();
  26325. this.onPreKeyboardObservable.clear();
  26326. this.onPointerObservable.clear();
  26327. this.onPrePointerObservable.clear();
  26328. };
  26329. /**
  26330. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26331. * Delay loaded resources are not taking in account
  26332. * @return true if all required resources are ready
  26333. */
  26334. Scene.prototype.isReady = function () {
  26335. if (this._isDisposed) {
  26336. return false;
  26337. }
  26338. if (this._pendingData.length > 0) {
  26339. return false;
  26340. }
  26341. var index;
  26342. var engine = this.getEngine();
  26343. // Geometries
  26344. for (index = 0; index < this.geometries.length; index++) {
  26345. var geometry = this.geometries[index];
  26346. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26347. return false;
  26348. }
  26349. }
  26350. // Meshes
  26351. for (index = 0; index < this.meshes.length; index++) {
  26352. var mesh = this.meshes[index];
  26353. if (!mesh.isEnabled()) {
  26354. continue;
  26355. }
  26356. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26357. continue;
  26358. }
  26359. if (!mesh.isReady(true)) {
  26360. return false;
  26361. }
  26362. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26363. // Is Ready For Mesh
  26364. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26365. var step = _a[_i];
  26366. if (!step.action(mesh, hardwareInstancedRendering)) {
  26367. return false;
  26368. }
  26369. }
  26370. }
  26371. // Post-processes
  26372. if (this.activeCameras && this.activeCameras.length > 0) {
  26373. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26374. var camera = _c[_b];
  26375. if (!camera.isReady(true)) {
  26376. return false;
  26377. }
  26378. }
  26379. }
  26380. else if (this.activeCamera) {
  26381. if (!this.activeCamera.isReady(true)) {
  26382. return false;
  26383. }
  26384. }
  26385. // Particles
  26386. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26387. var particleSystem = _e[_d];
  26388. if (!particleSystem.isReady()) {
  26389. return false;
  26390. }
  26391. }
  26392. return true;
  26393. };
  26394. /** Resets all cached information relative to material (including effect and visibility) */
  26395. Scene.prototype.resetCachedMaterial = function () {
  26396. this._cachedMaterial = null;
  26397. this._cachedEffect = null;
  26398. this._cachedVisibility = null;
  26399. };
  26400. /**
  26401. * Registers a function to be called before every frame render
  26402. * @param func defines the function to register
  26403. */
  26404. Scene.prototype.registerBeforeRender = function (func) {
  26405. this.onBeforeRenderObservable.add(func);
  26406. };
  26407. /**
  26408. * Unregisters a function called before every frame render
  26409. * @param func defines the function to unregister
  26410. */
  26411. Scene.prototype.unregisterBeforeRender = function (func) {
  26412. this.onBeforeRenderObservable.removeCallback(func);
  26413. };
  26414. /**
  26415. * Registers a function to be called after every frame render
  26416. * @param func defines the function to register
  26417. */
  26418. Scene.prototype.registerAfterRender = function (func) {
  26419. this.onAfterRenderObservable.add(func);
  26420. };
  26421. /**
  26422. * Unregisters a function called after every frame render
  26423. * @param func defines the function to unregister
  26424. */
  26425. Scene.prototype.unregisterAfterRender = function (func) {
  26426. this.onAfterRenderObservable.removeCallback(func);
  26427. };
  26428. Scene.prototype._executeOnceBeforeRender = function (func) {
  26429. var _this = this;
  26430. var execFunc = function () {
  26431. func();
  26432. setTimeout(function () {
  26433. _this.unregisterBeforeRender(execFunc);
  26434. });
  26435. };
  26436. this.registerBeforeRender(execFunc);
  26437. };
  26438. /**
  26439. * The provided function will run before render once and will be disposed afterwards.
  26440. * A timeout delay can be provided so that the function will be executed in N ms.
  26441. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26442. * @param func The function to be executed.
  26443. * @param timeout optional delay in ms
  26444. */
  26445. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26446. var _this = this;
  26447. if (timeout !== undefined) {
  26448. setTimeout(function () {
  26449. _this._executeOnceBeforeRender(func);
  26450. }, timeout);
  26451. }
  26452. else {
  26453. this._executeOnceBeforeRender(func);
  26454. }
  26455. };
  26456. /** @hidden */
  26457. Scene.prototype._addPendingData = function (data) {
  26458. this._pendingData.push(data);
  26459. };
  26460. /** @hidden */
  26461. Scene.prototype._removePendingData = function (data) {
  26462. var wasLoading = this.isLoading;
  26463. var index = this._pendingData.indexOf(data);
  26464. if (index !== -1) {
  26465. this._pendingData.splice(index, 1);
  26466. }
  26467. if (wasLoading && !this.isLoading) {
  26468. this.onDataLoadedObservable.notifyObservers(this);
  26469. }
  26470. };
  26471. /**
  26472. * Returns the number of items waiting to be loaded
  26473. * @returns the number of items waiting to be loaded
  26474. */
  26475. Scene.prototype.getWaitingItemsCount = function () {
  26476. return this._pendingData.length;
  26477. };
  26478. Object.defineProperty(Scene.prototype, "isLoading", {
  26479. /**
  26480. * Returns a boolean indicating if the scene is still loading data
  26481. */
  26482. get: function () {
  26483. return this._pendingData.length > 0;
  26484. },
  26485. enumerable: true,
  26486. configurable: true
  26487. });
  26488. /**
  26489. * Registers a function to be executed when the scene is ready
  26490. * @param {Function} func - the function to be executed
  26491. */
  26492. Scene.prototype.executeWhenReady = function (func) {
  26493. var _this = this;
  26494. this.onReadyObservable.add(func);
  26495. if (this._executeWhenReadyTimeoutId !== -1) {
  26496. return;
  26497. }
  26498. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26499. _this._checkIsReady();
  26500. }, 150);
  26501. };
  26502. /**
  26503. * Returns a promise that resolves when the scene is ready
  26504. * @returns A promise that resolves when the scene is ready
  26505. */
  26506. Scene.prototype.whenReadyAsync = function () {
  26507. var _this = this;
  26508. return new Promise(function (resolve) {
  26509. _this.executeWhenReady(function () {
  26510. resolve();
  26511. });
  26512. });
  26513. };
  26514. /** @hidden */
  26515. Scene.prototype._checkIsReady = function () {
  26516. var _this = this;
  26517. this._registerTransientComponents();
  26518. if (this.isReady()) {
  26519. this.onReadyObservable.notifyObservers(this);
  26520. this.onReadyObservable.clear();
  26521. this._executeWhenReadyTimeoutId = -1;
  26522. return;
  26523. }
  26524. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26525. _this._checkIsReady();
  26526. }, 150);
  26527. };
  26528. // Animations
  26529. /**
  26530. * Will start the animation sequence of a given target
  26531. * @param target defines the target
  26532. * @param from defines from which frame should animation start
  26533. * @param to defines until which frame should animation run.
  26534. * @param weight defines the weight to apply to the animation (1.0 by default)
  26535. * @param loop defines if the animation loops
  26536. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26537. * @param onAnimationEnd defines the function to be executed when the animation ends
  26538. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26539. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26540. * @returns the animatable object created for this animation
  26541. */
  26542. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26543. if (weight === void 0) { weight = 1.0; }
  26544. if (speedRatio === void 0) { speedRatio = 1.0; }
  26545. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26546. returnedAnimatable.weight = weight;
  26547. return returnedAnimatable;
  26548. };
  26549. /**
  26550. * Will start the animation sequence of a given target
  26551. * @param target defines the target
  26552. * @param from defines from which frame should animation start
  26553. * @param to defines until which frame should animation run.
  26554. * @param loop defines if the animation loops
  26555. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26556. * @param onAnimationEnd defines the function to be executed when the animation ends
  26557. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26558. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26559. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26560. * @returns the animatable object created for this animation
  26561. */
  26562. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26563. if (speedRatio === void 0) { speedRatio = 1.0; }
  26564. if (stopCurrent === void 0) { stopCurrent = true; }
  26565. if (from > to && speedRatio > 0) {
  26566. speedRatio *= -1;
  26567. }
  26568. if (stopCurrent) {
  26569. this.stopAnimation(target, undefined, targetMask);
  26570. }
  26571. if (!animatable) {
  26572. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26573. }
  26574. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26575. // Local animations
  26576. if (target.animations && shouldRunTargetAnimations) {
  26577. animatable.appendAnimations(target, target.animations);
  26578. }
  26579. // Children animations
  26580. if (target.getAnimatables) {
  26581. var animatables = target.getAnimatables();
  26582. for (var index = 0; index < animatables.length; index++) {
  26583. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26584. }
  26585. }
  26586. animatable.reset();
  26587. return animatable;
  26588. };
  26589. /**
  26590. * Begin a new animation on a given node
  26591. * @param target defines the target where the animation will take place
  26592. * @param animations defines the list of animations to start
  26593. * @param from defines the initial value
  26594. * @param to defines the final value
  26595. * @param loop defines if you want animation to loop (off by default)
  26596. * @param speedRatio defines the speed ratio to apply to all animations
  26597. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26598. * @returns the list of created animatables
  26599. */
  26600. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26601. if (speedRatio === undefined) {
  26602. speedRatio = 1.0;
  26603. }
  26604. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26605. return animatable;
  26606. };
  26607. /**
  26608. * Begin a new animation on a given node and its hierarchy
  26609. * @param target defines the root node where the animation will take place
  26610. * @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.
  26611. * @param animations defines the list of animations to start
  26612. * @param from defines the initial value
  26613. * @param to defines the final value
  26614. * @param loop defines if you want animation to loop (off by default)
  26615. * @param speedRatio defines the speed ratio to apply to all animations
  26616. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26617. * @returns the list of animatables created for all nodes
  26618. */
  26619. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26620. var children = target.getDescendants(directDescendantsOnly);
  26621. var result = [];
  26622. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26623. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26624. var child = children_1[_i];
  26625. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26626. }
  26627. return result;
  26628. };
  26629. /**
  26630. * Gets the animatable associated with a specific target
  26631. * @param target defines the target of the animatable
  26632. * @returns the required animatable if found
  26633. */
  26634. Scene.prototype.getAnimatableByTarget = function (target) {
  26635. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26636. if (this._activeAnimatables[index].target === target) {
  26637. return this._activeAnimatables[index];
  26638. }
  26639. }
  26640. return null;
  26641. };
  26642. /**
  26643. * Gets all animatables associated with a given target
  26644. * @param target defines the target to look animatables for
  26645. * @returns an array of Animatables
  26646. */
  26647. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26648. var result = [];
  26649. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26650. if (this._activeAnimatables[index].target === target) {
  26651. result.push(this._activeAnimatables[index]);
  26652. }
  26653. }
  26654. return result;
  26655. };
  26656. Object.defineProperty(Scene.prototype, "animatables", {
  26657. /**
  26658. * Gets all animatable attached to the scene
  26659. */
  26660. get: function () {
  26661. return this._activeAnimatables;
  26662. },
  26663. enumerable: true,
  26664. configurable: true
  26665. });
  26666. /**
  26667. * Will stop the animation of the given target
  26668. * @param target - the target
  26669. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26670. * @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)
  26671. */
  26672. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26673. var animatables = this.getAllAnimatablesByTarget(target);
  26674. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26675. var animatable = animatables_1[_i];
  26676. animatable.stop(animationName, targetMask);
  26677. }
  26678. };
  26679. /**
  26680. * Stops and removes all animations that have been applied to the scene
  26681. */
  26682. Scene.prototype.stopAllAnimations = function () {
  26683. if (this._activeAnimatables) {
  26684. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26685. this._activeAnimatables[i].stop();
  26686. }
  26687. this._activeAnimatables = [];
  26688. }
  26689. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26690. var group = _a[_i];
  26691. group.stop();
  26692. }
  26693. };
  26694. Scene.prototype._animate = function () {
  26695. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26696. return;
  26697. }
  26698. // Getting time
  26699. var now = BABYLON.Tools.Now;
  26700. if (!this._animationTimeLast) {
  26701. if (this._pendingData.length > 0) {
  26702. return;
  26703. }
  26704. this._animationTimeLast = now;
  26705. }
  26706. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26707. this._animationTime += deltaTime;
  26708. this._animationTimeLast = now;
  26709. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26710. this._activeAnimatables[index]._animate(this._animationTime);
  26711. }
  26712. // Late animation bindings
  26713. this._processLateAnimationBindings();
  26714. };
  26715. /** @hidden */
  26716. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26717. var target = runtimeAnimation.target;
  26718. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26719. if (!target._lateAnimationHolders) {
  26720. target._lateAnimationHolders = {};
  26721. }
  26722. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26723. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26724. totalWeight: 0,
  26725. animations: [],
  26726. originalValue: originalValue
  26727. };
  26728. }
  26729. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26730. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26731. };
  26732. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26733. var normalizer = 1.0;
  26734. var finalPosition = BABYLON.Tmp.Vector3[0];
  26735. var finalScaling = BABYLON.Tmp.Vector3[1];
  26736. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26737. var startIndex = 0;
  26738. var originalAnimation = holder.animations[0];
  26739. var originalValue = holder.originalValue;
  26740. var scale = 1;
  26741. if (holder.totalWeight < 1.0) {
  26742. // We need to mix the original value in
  26743. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26744. scale = 1.0 - holder.totalWeight;
  26745. }
  26746. else {
  26747. startIndex = 1;
  26748. // We need to normalize the weights
  26749. normalizer = holder.totalWeight;
  26750. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26751. scale = originalAnimation.weight / normalizer;
  26752. if (scale == 1) {
  26753. return originalAnimation.currentValue;
  26754. }
  26755. }
  26756. finalScaling.scaleInPlace(scale);
  26757. finalPosition.scaleInPlace(scale);
  26758. finalQuaternion.scaleInPlace(scale);
  26759. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26760. var runtimeAnimation = holder.animations[animIndex];
  26761. var scale = runtimeAnimation.weight / normalizer;
  26762. var currentPosition = BABYLON.Tmp.Vector3[2];
  26763. var currentScaling = BABYLON.Tmp.Vector3[3];
  26764. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26765. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26766. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26767. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26768. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26769. }
  26770. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26771. return originalAnimation._workValue;
  26772. };
  26773. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26774. var originalAnimation = holder.animations[0];
  26775. var originalValue = holder.originalValue;
  26776. if (holder.animations.length === 1) {
  26777. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26778. return refQuaternion;
  26779. }
  26780. var normalizer = 1.0;
  26781. var quaternions;
  26782. var weights;
  26783. if (holder.totalWeight < 1.0) {
  26784. var scale = 1.0 - holder.totalWeight;
  26785. quaternions = [];
  26786. weights = [];
  26787. quaternions.push(originalValue);
  26788. weights.push(scale);
  26789. }
  26790. else {
  26791. if (holder.animations.length === 2) { // Slerp as soon as we can
  26792. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26793. return refQuaternion;
  26794. }
  26795. quaternions = [];
  26796. weights = [];
  26797. normalizer = holder.totalWeight;
  26798. }
  26799. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26800. var runtimeAnimation = holder.animations[animIndex];
  26801. quaternions.push(runtimeAnimation.currentValue);
  26802. weights.push(runtimeAnimation.weight / normalizer);
  26803. }
  26804. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26805. var cumulativeAmount = 0;
  26806. var cumulativeQuaternion = null;
  26807. for (var index = 0; index < quaternions.length;) {
  26808. if (!cumulativeQuaternion) {
  26809. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26810. cumulativeQuaternion = refQuaternion;
  26811. cumulativeAmount = weights[index] + weights[index + 1];
  26812. index += 2;
  26813. continue;
  26814. }
  26815. cumulativeAmount += weights[index];
  26816. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26817. index++;
  26818. }
  26819. return cumulativeQuaternion;
  26820. };
  26821. Scene.prototype._processLateAnimationBindings = function () {
  26822. if (!this._registeredForLateAnimationBindings.length) {
  26823. return;
  26824. }
  26825. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26826. var target = this._registeredForLateAnimationBindings.data[index];
  26827. for (var path in target._lateAnimationHolders) {
  26828. var holder = target._lateAnimationHolders[path];
  26829. var originalAnimation = holder.animations[0];
  26830. var originalValue = holder.originalValue;
  26831. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26832. var finalValue = target[path];
  26833. if (matrixDecomposeMode) {
  26834. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26835. }
  26836. else {
  26837. var quaternionMode = originalValue.w !== undefined;
  26838. if (quaternionMode) {
  26839. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26840. }
  26841. else {
  26842. var startIndex = 0;
  26843. var normalizer = 1.0;
  26844. if (holder.totalWeight < 1.0) {
  26845. // We need to mix the original value in
  26846. if (originalValue.scale) {
  26847. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26848. }
  26849. else {
  26850. finalValue = originalValue * (1.0 - holder.totalWeight);
  26851. }
  26852. }
  26853. else {
  26854. // We need to normalize the weights
  26855. normalizer = holder.totalWeight;
  26856. var scale_1 = originalAnimation.weight / normalizer;
  26857. if (scale_1 !== 1) {
  26858. if (originalAnimation.currentValue.scale) {
  26859. finalValue = originalAnimation.currentValue.scale(scale_1);
  26860. }
  26861. else {
  26862. finalValue = originalAnimation.currentValue * scale_1;
  26863. }
  26864. }
  26865. else {
  26866. finalValue = originalAnimation.currentValue;
  26867. }
  26868. startIndex = 1;
  26869. }
  26870. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26871. var runtimeAnimation = holder.animations[animIndex];
  26872. var scale = runtimeAnimation.weight / normalizer;
  26873. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26874. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26875. }
  26876. else {
  26877. finalValue += runtimeAnimation.currentValue * scale;
  26878. }
  26879. }
  26880. }
  26881. }
  26882. target[path] = finalValue;
  26883. }
  26884. target._lateAnimationHolders = {};
  26885. }
  26886. this._registeredForLateAnimationBindings.reset();
  26887. };
  26888. // Matrix
  26889. /** @hidden */
  26890. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26891. this._useAlternateCameraConfiguration = active;
  26892. };
  26893. /**
  26894. * Gets the current view matrix
  26895. * @returns a Matrix
  26896. */
  26897. Scene.prototype.getViewMatrix = function () {
  26898. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26899. };
  26900. /**
  26901. * Gets the current projection matrix
  26902. * @returns a Matrix
  26903. */
  26904. Scene.prototype.getProjectionMatrix = function () {
  26905. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26906. };
  26907. /**
  26908. * Gets the current transform matrix
  26909. * @returns a Matrix made of View * Projection
  26910. */
  26911. Scene.prototype.getTransformMatrix = function () {
  26912. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26913. };
  26914. /**
  26915. * Sets the current transform matrix
  26916. * @param view defines the View matrix to use
  26917. * @param projection defines the Projection matrix to use
  26918. */
  26919. Scene.prototype.setTransformMatrix = function (view, projection) {
  26920. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26921. return;
  26922. }
  26923. this._viewUpdateFlag = view.updateFlag;
  26924. this._projectionUpdateFlag = projection.updateFlag;
  26925. this._viewMatrix = view;
  26926. this._projectionMatrix = projection;
  26927. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26928. // Update frustum
  26929. if (!this._frustumPlanes) {
  26930. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26931. }
  26932. else {
  26933. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26934. }
  26935. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26936. var otherCamera = this.activeCamera._alternateCamera;
  26937. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26938. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26939. }
  26940. if (this._sceneUbo.useUbo) {
  26941. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26942. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26943. this._sceneUbo.update();
  26944. }
  26945. };
  26946. /** @hidden */
  26947. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26948. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26949. return;
  26950. }
  26951. this._alternateViewUpdateFlag = view.updateFlag;
  26952. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26953. this._alternateViewMatrix = view;
  26954. this._alternateProjectionMatrix = projection;
  26955. if (!this._alternateTransformMatrix) {
  26956. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26957. }
  26958. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26959. if (!this._alternateSceneUbo) {
  26960. this._createAlternateUbo();
  26961. }
  26962. if (this._alternateSceneUbo.useUbo) {
  26963. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26964. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26965. this._alternateSceneUbo.update();
  26966. }
  26967. };
  26968. /**
  26969. * Gets the uniform buffer used to store scene data
  26970. * @returns a UniformBuffer
  26971. */
  26972. Scene.prototype.getSceneUniformBuffer = function () {
  26973. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26974. };
  26975. /**
  26976. * Gets an unique (relatively to the current scene) Id
  26977. * @returns an unique number for the scene
  26978. */
  26979. Scene.prototype.getUniqueId = function () {
  26980. var result = Scene._uniqueIdCounter;
  26981. Scene._uniqueIdCounter++;
  26982. return result;
  26983. };
  26984. /**
  26985. * Add a mesh to the list of scene's meshes
  26986. * @param newMesh defines the mesh to add
  26987. * @param recursive if all child meshes should also be added to the scene
  26988. */
  26989. Scene.prototype.addMesh = function (newMesh, recursive) {
  26990. var _this = this;
  26991. if (recursive === void 0) { recursive = false; }
  26992. this.meshes.push(newMesh);
  26993. //notify the collision coordinator
  26994. if (this.collisionCoordinator) {
  26995. this.collisionCoordinator.onMeshAdded(newMesh);
  26996. }
  26997. newMesh._resyncLightSources();
  26998. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26999. if (recursive) {
  27000. newMesh.getChildMeshes().forEach(function (m) {
  27001. _this.addMesh(m);
  27002. });
  27003. }
  27004. };
  27005. /**
  27006. * Remove a mesh for the list of scene's meshes
  27007. * @param toRemove defines the mesh to remove
  27008. * @param recursive if all child meshes should also be removed from the scene
  27009. * @returns the index where the mesh was in the mesh list
  27010. */
  27011. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27012. var _this = this;
  27013. if (recursive === void 0) { recursive = false; }
  27014. var index = this.meshes.indexOf(toRemove);
  27015. if (index !== -1) {
  27016. // Remove from the scene if mesh found
  27017. this.meshes.splice(index, 1);
  27018. }
  27019. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27020. if (recursive) {
  27021. toRemove.getChildMeshes().forEach(function (m) {
  27022. _this.removeMesh(m);
  27023. });
  27024. }
  27025. return index;
  27026. };
  27027. /**
  27028. * Add a transform node to the list of scene's transform nodes
  27029. * @param newTransformNode defines the transform node to add
  27030. */
  27031. Scene.prototype.addTransformNode = function (newTransformNode) {
  27032. this.transformNodes.push(newTransformNode);
  27033. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27034. };
  27035. /**
  27036. * Remove a transform node for the list of scene's transform nodes
  27037. * @param toRemove defines the transform node to remove
  27038. * @returns the index where the transform node was in the transform node list
  27039. */
  27040. Scene.prototype.removeTransformNode = function (toRemove) {
  27041. var index = this.transformNodes.indexOf(toRemove);
  27042. if (index !== -1) {
  27043. // Remove from the scene if found
  27044. this.transformNodes.splice(index, 1);
  27045. }
  27046. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27047. return index;
  27048. };
  27049. /**
  27050. * Remove a skeleton for the list of scene's skeletons
  27051. * @param toRemove defines the skeleton to remove
  27052. * @returns the index where the skeleton was in the skeleton list
  27053. */
  27054. Scene.prototype.removeSkeleton = function (toRemove) {
  27055. var index = this.skeletons.indexOf(toRemove);
  27056. if (index !== -1) {
  27057. // Remove from the scene if found
  27058. this.skeletons.splice(index, 1);
  27059. }
  27060. return index;
  27061. };
  27062. /**
  27063. * Remove a morph target for the list of scene's morph targets
  27064. * @param toRemove defines the morph target to remove
  27065. * @returns the index where the morph target was in the morph target list
  27066. */
  27067. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27068. var index = this.morphTargetManagers.indexOf(toRemove);
  27069. if (index !== -1) {
  27070. // Remove from the scene if found
  27071. this.morphTargetManagers.splice(index, 1);
  27072. }
  27073. return index;
  27074. };
  27075. /**
  27076. * Remove a light for the list of scene's lights
  27077. * @param toRemove defines the light to remove
  27078. * @returns the index where the light was in the light list
  27079. */
  27080. Scene.prototype.removeLight = function (toRemove) {
  27081. var index = this.lights.indexOf(toRemove);
  27082. if (index !== -1) {
  27083. // Remove from meshes
  27084. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27085. var mesh = _a[_i];
  27086. mesh._removeLightSource(toRemove);
  27087. }
  27088. // Remove from the scene if mesh found
  27089. this.lights.splice(index, 1);
  27090. this.sortLightsByPriority();
  27091. }
  27092. this.onLightRemovedObservable.notifyObservers(toRemove);
  27093. return index;
  27094. };
  27095. /**
  27096. * Remove a camera for the list of scene's cameras
  27097. * @param toRemove defines the camera to remove
  27098. * @returns the index where the camera was in the camera list
  27099. */
  27100. Scene.prototype.removeCamera = function (toRemove) {
  27101. var index = this.cameras.indexOf(toRemove);
  27102. if (index !== -1) {
  27103. // Remove from the scene if mesh found
  27104. this.cameras.splice(index, 1);
  27105. }
  27106. // Remove from activeCameras
  27107. var index2 = this.activeCameras.indexOf(toRemove);
  27108. if (index2 !== -1) {
  27109. // Remove from the scene if mesh found
  27110. this.activeCameras.splice(index2, 1);
  27111. }
  27112. // Reset the activeCamera
  27113. if (this.activeCamera === toRemove) {
  27114. if (this.cameras.length > 0) {
  27115. this.activeCamera = this.cameras[0];
  27116. }
  27117. else {
  27118. this.activeCamera = null;
  27119. }
  27120. }
  27121. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27122. return index;
  27123. };
  27124. /**
  27125. * Remove a particle system for the list of scene's particle systems
  27126. * @param toRemove defines the particle system to remove
  27127. * @returns the index where the particle system was in the particle system list
  27128. */
  27129. Scene.prototype.removeParticleSystem = function (toRemove) {
  27130. var index = this.particleSystems.indexOf(toRemove);
  27131. if (index !== -1) {
  27132. this.particleSystems.splice(index, 1);
  27133. }
  27134. return index;
  27135. };
  27136. /**
  27137. * Remove a animation for the list of scene's animations
  27138. * @param toRemove defines the animation to remove
  27139. * @returns the index where the animation was in the animation list
  27140. */
  27141. Scene.prototype.removeAnimation = function (toRemove) {
  27142. var index = this.animations.indexOf(toRemove);
  27143. if (index !== -1) {
  27144. this.animations.splice(index, 1);
  27145. }
  27146. return index;
  27147. };
  27148. /**
  27149. * Removes the given animation group from this scene.
  27150. * @param toRemove The animation group to remove
  27151. * @returns The index of the removed animation group
  27152. */
  27153. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27154. var index = this.animationGroups.indexOf(toRemove);
  27155. if (index !== -1) {
  27156. this.animationGroups.splice(index, 1);
  27157. }
  27158. return index;
  27159. };
  27160. /**
  27161. * Removes the given multi-material from this scene.
  27162. * @param toRemove The multi-material to remove
  27163. * @returns The index of the removed multi-material
  27164. */
  27165. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27166. var index = this.multiMaterials.indexOf(toRemove);
  27167. if (index !== -1) {
  27168. this.multiMaterials.splice(index, 1);
  27169. }
  27170. return index;
  27171. };
  27172. /**
  27173. * Removes the given material from this scene.
  27174. * @param toRemove The material to remove
  27175. * @returns The index of the removed material
  27176. */
  27177. Scene.prototype.removeMaterial = function (toRemove) {
  27178. var index = this.materials.indexOf(toRemove);
  27179. if (index !== -1) {
  27180. this.materials.splice(index, 1);
  27181. }
  27182. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27183. return index;
  27184. };
  27185. /**
  27186. * Removes the given action manager from this scene.
  27187. * @param toRemove The action manager to remove
  27188. * @returns The index of the removed action manager
  27189. */
  27190. Scene.prototype.removeActionManager = function (toRemove) {
  27191. var index = this.actionManagers.indexOf(toRemove);
  27192. if (index !== -1) {
  27193. this.actionManagers.splice(index, 1);
  27194. }
  27195. return index;
  27196. };
  27197. /**
  27198. * Removes the given texture from this scene.
  27199. * @param toRemove The texture to remove
  27200. * @returns The index of the removed texture
  27201. */
  27202. Scene.prototype.removeTexture = function (toRemove) {
  27203. var index = this.textures.indexOf(toRemove);
  27204. if (index !== -1) {
  27205. this.textures.splice(index, 1);
  27206. }
  27207. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27208. return index;
  27209. };
  27210. /**
  27211. * Adds the given light to this scene
  27212. * @param newLight The light to add
  27213. */
  27214. Scene.prototype.addLight = function (newLight) {
  27215. this.lights.push(newLight);
  27216. this.sortLightsByPriority();
  27217. // Add light to all meshes (To support if the light is removed and then readded)
  27218. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27219. var mesh = _a[_i];
  27220. if (mesh._lightSources.indexOf(newLight) === -1) {
  27221. mesh._lightSources.push(newLight);
  27222. mesh._resyncLightSources();
  27223. }
  27224. }
  27225. this.onNewLightAddedObservable.notifyObservers(newLight);
  27226. };
  27227. /**
  27228. * Sorts the list list based on light priorities
  27229. */
  27230. Scene.prototype.sortLightsByPriority = function () {
  27231. if (this.requireLightSorting) {
  27232. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27233. }
  27234. };
  27235. /**
  27236. * Adds the given camera to this scene
  27237. * @param newCamera The camera to add
  27238. */
  27239. Scene.prototype.addCamera = function (newCamera) {
  27240. this.cameras.push(newCamera);
  27241. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27242. };
  27243. /**
  27244. * Adds the given skeleton to this scene
  27245. * @param newSkeleton The skeleton to add
  27246. */
  27247. Scene.prototype.addSkeleton = function (newSkeleton) {
  27248. this.skeletons.push(newSkeleton);
  27249. };
  27250. /**
  27251. * Adds the given particle system to this scene
  27252. * @param newParticleSystem The particle system to add
  27253. */
  27254. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27255. this.particleSystems.push(newParticleSystem);
  27256. };
  27257. /**
  27258. * Adds the given animation to this scene
  27259. * @param newAnimation The animation to add
  27260. */
  27261. Scene.prototype.addAnimation = function (newAnimation) {
  27262. this.animations.push(newAnimation);
  27263. };
  27264. /**
  27265. * Adds the given animation group to this scene.
  27266. * @param newAnimationGroup The animation group to add
  27267. */
  27268. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27269. this.animationGroups.push(newAnimationGroup);
  27270. };
  27271. /**
  27272. * Adds the given multi-material to this scene
  27273. * @param newMultiMaterial The multi-material to add
  27274. */
  27275. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27276. this.multiMaterials.push(newMultiMaterial);
  27277. };
  27278. /**
  27279. * Adds the given material to this scene
  27280. * @param newMaterial The material to add
  27281. */
  27282. Scene.prototype.addMaterial = function (newMaterial) {
  27283. this.materials.push(newMaterial);
  27284. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27285. };
  27286. /**
  27287. * Adds the given morph target to this scene
  27288. * @param newMorphTargetManager The morph target to add
  27289. */
  27290. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27291. this.morphTargetManagers.push(newMorphTargetManager);
  27292. };
  27293. /**
  27294. * Adds the given geometry to this scene
  27295. * @param newGeometry The geometry to add
  27296. */
  27297. Scene.prototype.addGeometry = function (newGeometry) {
  27298. this.geometries.push(newGeometry);
  27299. };
  27300. /**
  27301. * Adds the given action manager to this scene
  27302. * @param newActionManager The action manager to add
  27303. */
  27304. Scene.prototype.addActionManager = function (newActionManager) {
  27305. this.actionManagers.push(newActionManager);
  27306. };
  27307. /**
  27308. * Adds the given texture to this scene.
  27309. * @param newTexture The texture to add
  27310. */
  27311. Scene.prototype.addTexture = function (newTexture) {
  27312. this.textures.push(newTexture);
  27313. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27314. };
  27315. /**
  27316. * Switch active camera
  27317. * @param newCamera defines the new active camera
  27318. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27319. */
  27320. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27321. if (attachControl === void 0) { attachControl = true; }
  27322. var canvas = this._engine.getRenderingCanvas();
  27323. if (!canvas) {
  27324. return;
  27325. }
  27326. if (this.activeCamera) {
  27327. this.activeCamera.detachControl(canvas);
  27328. }
  27329. this.activeCamera = newCamera;
  27330. if (attachControl) {
  27331. newCamera.attachControl(canvas);
  27332. }
  27333. };
  27334. /**
  27335. * sets the active camera of the scene using its ID
  27336. * @param id defines the camera's ID
  27337. * @return the new active camera or null if none found.
  27338. */
  27339. Scene.prototype.setActiveCameraByID = function (id) {
  27340. var camera = this.getCameraByID(id);
  27341. if (camera) {
  27342. this.activeCamera = camera;
  27343. return camera;
  27344. }
  27345. return null;
  27346. };
  27347. /**
  27348. * sets the active camera of the scene using its name
  27349. * @param name defines the camera's name
  27350. * @returns the new active camera or null if none found.
  27351. */
  27352. Scene.prototype.setActiveCameraByName = function (name) {
  27353. var camera = this.getCameraByName(name);
  27354. if (camera) {
  27355. this.activeCamera = camera;
  27356. return camera;
  27357. }
  27358. return null;
  27359. };
  27360. /**
  27361. * get an animation group using its name
  27362. * @param name defines the material's name
  27363. * @return the animation group or null if none found.
  27364. */
  27365. Scene.prototype.getAnimationGroupByName = function (name) {
  27366. for (var index = 0; index < this.animationGroups.length; index++) {
  27367. if (this.animationGroups[index].name === name) {
  27368. return this.animationGroups[index];
  27369. }
  27370. }
  27371. return null;
  27372. };
  27373. /**
  27374. * get a material using its id
  27375. * @param id defines the material's ID
  27376. * @return the material or null if none found.
  27377. */
  27378. Scene.prototype.getMaterialByID = function (id) {
  27379. for (var index = 0; index < this.materials.length; index++) {
  27380. if (this.materials[index].id === id) {
  27381. return this.materials[index];
  27382. }
  27383. }
  27384. return null;
  27385. };
  27386. /**
  27387. * Gets a material using its name
  27388. * @param name defines the material's name
  27389. * @return the material or null if none found.
  27390. */
  27391. Scene.prototype.getMaterialByName = function (name) {
  27392. for (var index = 0; index < this.materials.length; index++) {
  27393. if (this.materials[index].name === name) {
  27394. return this.materials[index];
  27395. }
  27396. }
  27397. return null;
  27398. };
  27399. /**
  27400. * Gets a camera using its id
  27401. * @param id defines the id to look for
  27402. * @returns the camera or null if not found
  27403. */
  27404. Scene.prototype.getCameraByID = function (id) {
  27405. for (var index = 0; index < this.cameras.length; index++) {
  27406. if (this.cameras[index].id === id) {
  27407. return this.cameras[index];
  27408. }
  27409. }
  27410. return null;
  27411. };
  27412. /**
  27413. * Gets a camera using its unique id
  27414. * @param uniqueId defines the unique id to look for
  27415. * @returns the camera or null if not found
  27416. */
  27417. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27418. for (var index = 0; index < this.cameras.length; index++) {
  27419. if (this.cameras[index].uniqueId === uniqueId) {
  27420. return this.cameras[index];
  27421. }
  27422. }
  27423. return null;
  27424. };
  27425. /**
  27426. * Gets a camera using its name
  27427. * @param name defines the camera's name
  27428. * @return the camera or null if none found.
  27429. */
  27430. Scene.prototype.getCameraByName = function (name) {
  27431. for (var index = 0; index < this.cameras.length; index++) {
  27432. if (this.cameras[index].name === name) {
  27433. return this.cameras[index];
  27434. }
  27435. }
  27436. return null;
  27437. };
  27438. /**
  27439. * Gets a bone using its id
  27440. * @param id defines the bone's id
  27441. * @return the bone or null if not found
  27442. */
  27443. Scene.prototype.getBoneByID = function (id) {
  27444. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27445. var skeleton = this.skeletons[skeletonIndex];
  27446. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27447. if (skeleton.bones[boneIndex].id === id) {
  27448. return skeleton.bones[boneIndex];
  27449. }
  27450. }
  27451. }
  27452. return null;
  27453. };
  27454. /**
  27455. * Gets a bone using its id
  27456. * @param name defines the bone's name
  27457. * @return the bone or null if not found
  27458. */
  27459. Scene.prototype.getBoneByName = function (name) {
  27460. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27461. var skeleton = this.skeletons[skeletonIndex];
  27462. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27463. if (skeleton.bones[boneIndex].name === name) {
  27464. return skeleton.bones[boneIndex];
  27465. }
  27466. }
  27467. }
  27468. return null;
  27469. };
  27470. /**
  27471. * Gets a light node using its name
  27472. * @param name defines the the light's name
  27473. * @return the light or null if none found.
  27474. */
  27475. Scene.prototype.getLightByName = function (name) {
  27476. for (var index = 0; index < this.lights.length; index++) {
  27477. if (this.lights[index].name === name) {
  27478. return this.lights[index];
  27479. }
  27480. }
  27481. return null;
  27482. };
  27483. /**
  27484. * Gets a light node using its id
  27485. * @param id defines the light's id
  27486. * @return the light or null if none found.
  27487. */
  27488. Scene.prototype.getLightByID = function (id) {
  27489. for (var index = 0; index < this.lights.length; index++) {
  27490. if (this.lights[index].id === id) {
  27491. return this.lights[index];
  27492. }
  27493. }
  27494. return null;
  27495. };
  27496. /**
  27497. * Gets a light node using its scene-generated unique ID
  27498. * @param uniqueId defines the light's unique id
  27499. * @return the light or null if none found.
  27500. */
  27501. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27502. for (var index = 0; index < this.lights.length; index++) {
  27503. if (this.lights[index].uniqueId === uniqueId) {
  27504. return this.lights[index];
  27505. }
  27506. }
  27507. return null;
  27508. };
  27509. /**
  27510. * Gets a particle system by id
  27511. * @param id defines the particle system id
  27512. * @return the corresponding system or null if none found
  27513. */
  27514. Scene.prototype.getParticleSystemByID = function (id) {
  27515. for (var index = 0; index < this.particleSystems.length; index++) {
  27516. if (this.particleSystems[index].id === id) {
  27517. return this.particleSystems[index];
  27518. }
  27519. }
  27520. return null;
  27521. };
  27522. /**
  27523. * Gets a geometry using its ID
  27524. * @param id defines the geometry's id
  27525. * @return the geometry or null if none found.
  27526. */
  27527. Scene.prototype.getGeometryByID = function (id) {
  27528. for (var index = 0; index < this.geometries.length; index++) {
  27529. if (this.geometries[index].id === id) {
  27530. return this.geometries[index];
  27531. }
  27532. }
  27533. return null;
  27534. };
  27535. /**
  27536. * Add a new geometry to this scene
  27537. * @param geometry defines the geometry to be added to the scene.
  27538. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27539. * @return a boolean defining if the geometry was added or not
  27540. */
  27541. Scene.prototype.pushGeometry = function (geometry, force) {
  27542. if (!force && this.getGeometryByID(geometry.id)) {
  27543. return false;
  27544. }
  27545. this.geometries.push(geometry);
  27546. //notify the collision coordinator
  27547. if (this.collisionCoordinator) {
  27548. this.collisionCoordinator.onGeometryAdded(geometry);
  27549. }
  27550. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27551. return true;
  27552. };
  27553. /**
  27554. * Removes an existing geometry
  27555. * @param geometry defines the geometry to be removed from the scene
  27556. * @return a boolean defining if the geometry was removed or not
  27557. */
  27558. Scene.prototype.removeGeometry = function (geometry) {
  27559. var index = this.geometries.indexOf(geometry);
  27560. if (index > -1) {
  27561. this.geometries.splice(index, 1);
  27562. //notify the collision coordinator
  27563. if (this.collisionCoordinator) {
  27564. this.collisionCoordinator.onGeometryDeleted(geometry);
  27565. }
  27566. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27567. return true;
  27568. }
  27569. return false;
  27570. };
  27571. /**
  27572. * Gets the list of geometries attached to the scene
  27573. * @returns an array of Geometry
  27574. */
  27575. Scene.prototype.getGeometries = function () {
  27576. return this.geometries;
  27577. };
  27578. /**
  27579. * Gets the first added mesh found of a given ID
  27580. * @param id defines the id to search for
  27581. * @return the mesh found or null if not found at all
  27582. */
  27583. Scene.prototype.getMeshByID = function (id) {
  27584. for (var index = 0; index < this.meshes.length; index++) {
  27585. if (this.meshes[index].id === id) {
  27586. return this.meshes[index];
  27587. }
  27588. }
  27589. return null;
  27590. };
  27591. /**
  27592. * Gets a list of meshes using their id
  27593. * @param id defines the id to search for
  27594. * @returns a list of meshes
  27595. */
  27596. Scene.prototype.getMeshesByID = function (id) {
  27597. return this.meshes.filter(function (m) {
  27598. return m.id === id;
  27599. });
  27600. };
  27601. /**
  27602. * Gets the first added transform node found of a given ID
  27603. * @param id defines the id to search for
  27604. * @return the found transform node or null if not found at all.
  27605. */
  27606. Scene.prototype.getTransformNodeByID = function (id) {
  27607. for (var index = 0; index < this.transformNodes.length; index++) {
  27608. if (this.transformNodes[index].id === id) {
  27609. return this.transformNodes[index];
  27610. }
  27611. }
  27612. return null;
  27613. };
  27614. /**
  27615. * Gets a list of transform nodes using their id
  27616. * @param id defines the id to search for
  27617. * @returns a list of transform nodes
  27618. */
  27619. Scene.prototype.getTransformNodesByID = function (id) {
  27620. return this.transformNodes.filter(function (m) {
  27621. return m.id === id;
  27622. });
  27623. };
  27624. /**
  27625. * Gets a mesh with its auto-generated unique id
  27626. * @param uniqueId defines the unique id to search for
  27627. * @return the found mesh or null if not found at all.
  27628. */
  27629. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27630. for (var index = 0; index < this.meshes.length; index++) {
  27631. if (this.meshes[index].uniqueId === uniqueId) {
  27632. return this.meshes[index];
  27633. }
  27634. }
  27635. return null;
  27636. };
  27637. /**
  27638. * Gets a the last added mesh using a given id
  27639. * @param id defines the id to search for
  27640. * @return the found mesh or null if not found at all.
  27641. */
  27642. Scene.prototype.getLastMeshByID = function (id) {
  27643. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27644. if (this.meshes[index].id === id) {
  27645. return this.meshes[index];
  27646. }
  27647. }
  27648. return null;
  27649. };
  27650. /**
  27651. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27652. * @param id defines the id to search for
  27653. * @return the found node or null if not found at all
  27654. */
  27655. Scene.prototype.getLastEntryByID = function (id) {
  27656. var index;
  27657. for (index = this.meshes.length - 1; index >= 0; index--) {
  27658. if (this.meshes[index].id === id) {
  27659. return this.meshes[index];
  27660. }
  27661. }
  27662. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27663. if (this.transformNodes[index].id === id) {
  27664. return this.transformNodes[index];
  27665. }
  27666. }
  27667. for (index = this.cameras.length - 1; index >= 0; index--) {
  27668. if (this.cameras[index].id === id) {
  27669. return this.cameras[index];
  27670. }
  27671. }
  27672. for (index = this.lights.length - 1; index >= 0; index--) {
  27673. if (this.lights[index].id === id) {
  27674. return this.lights[index];
  27675. }
  27676. }
  27677. return null;
  27678. };
  27679. /**
  27680. * Gets a node (Mesh, Camera, Light) using a given id
  27681. * @param id defines the id to search for
  27682. * @return the found node or null if not found at all
  27683. */
  27684. Scene.prototype.getNodeByID = function (id) {
  27685. var mesh = this.getMeshByID(id);
  27686. if (mesh) {
  27687. return mesh;
  27688. }
  27689. var light = this.getLightByID(id);
  27690. if (light) {
  27691. return light;
  27692. }
  27693. var camera = this.getCameraByID(id);
  27694. if (camera) {
  27695. return camera;
  27696. }
  27697. var bone = this.getBoneByID(id);
  27698. return bone;
  27699. };
  27700. /**
  27701. * Gets a node (Mesh, Camera, Light) using a given name
  27702. * @param name defines the name to search for
  27703. * @return the found node or null if not found at all.
  27704. */
  27705. Scene.prototype.getNodeByName = function (name) {
  27706. var mesh = this.getMeshByName(name);
  27707. if (mesh) {
  27708. return mesh;
  27709. }
  27710. var light = this.getLightByName(name);
  27711. if (light) {
  27712. return light;
  27713. }
  27714. var camera = this.getCameraByName(name);
  27715. if (camera) {
  27716. return camera;
  27717. }
  27718. var bone = this.getBoneByName(name);
  27719. return bone;
  27720. };
  27721. /**
  27722. * Gets a mesh using a given name
  27723. * @param name defines the name to search for
  27724. * @return the found mesh or null if not found at all.
  27725. */
  27726. Scene.prototype.getMeshByName = function (name) {
  27727. for (var index = 0; index < this.meshes.length; index++) {
  27728. if (this.meshes[index].name === name) {
  27729. return this.meshes[index];
  27730. }
  27731. }
  27732. return null;
  27733. };
  27734. /**
  27735. * Gets a transform node using a given name
  27736. * @param name defines the name to search for
  27737. * @return the found transform node or null if not found at all.
  27738. */
  27739. Scene.prototype.getTransformNodeByName = function (name) {
  27740. for (var index = 0; index < this.transformNodes.length; index++) {
  27741. if (this.transformNodes[index].name === name) {
  27742. return this.transformNodes[index];
  27743. }
  27744. }
  27745. return null;
  27746. };
  27747. /**
  27748. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27749. * @param id defines the id to search for
  27750. * @return the found skeleton or null if not found at all.
  27751. */
  27752. Scene.prototype.getLastSkeletonByID = function (id) {
  27753. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27754. if (this.skeletons[index].id === id) {
  27755. return this.skeletons[index];
  27756. }
  27757. }
  27758. return null;
  27759. };
  27760. /**
  27761. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27762. * @param id defines the id to search for
  27763. * @return the found skeleton or null if not found at all.
  27764. */
  27765. Scene.prototype.getSkeletonById = function (id) {
  27766. for (var index = 0; index < this.skeletons.length; index++) {
  27767. if (this.skeletons[index].id === id) {
  27768. return this.skeletons[index];
  27769. }
  27770. }
  27771. return null;
  27772. };
  27773. /**
  27774. * Gets a skeleton using a given name
  27775. * @param name defines the name to search for
  27776. * @return the found skeleton or null if not found at all.
  27777. */
  27778. Scene.prototype.getSkeletonByName = function (name) {
  27779. for (var index = 0; index < this.skeletons.length; index++) {
  27780. if (this.skeletons[index].name === name) {
  27781. return this.skeletons[index];
  27782. }
  27783. }
  27784. return null;
  27785. };
  27786. /**
  27787. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27788. * @param id defines the id to search for
  27789. * @return the found morph target manager or null if not found at all.
  27790. */
  27791. Scene.prototype.getMorphTargetManagerById = function (id) {
  27792. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27793. if (this.morphTargetManagers[index].uniqueId === id) {
  27794. return this.morphTargetManagers[index];
  27795. }
  27796. }
  27797. return null;
  27798. };
  27799. /**
  27800. * Gets a boolean indicating if the given mesh is active
  27801. * @param mesh defines the mesh to look for
  27802. * @returns true if the mesh is in the active list
  27803. */
  27804. Scene.prototype.isActiveMesh = function (mesh) {
  27805. return (this._activeMeshes.indexOf(mesh) !== -1);
  27806. };
  27807. Object.defineProperty(Scene.prototype, "uid", {
  27808. /**
  27809. * Return a unique id as a string which can serve as an identifier for the scene
  27810. */
  27811. get: function () {
  27812. if (!this._uid) {
  27813. this._uid = BABYLON.Tools.RandomId();
  27814. }
  27815. return this._uid;
  27816. },
  27817. enumerable: true,
  27818. configurable: true
  27819. });
  27820. /**
  27821. * Add an externaly attached data from its key.
  27822. * This method call will fail and return false, if such key already exists.
  27823. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27824. * @param key the unique key that identifies the data
  27825. * @param data the data object to associate to the key for this Engine instance
  27826. * @return true if no such key were already present and the data was added successfully, false otherwise
  27827. */
  27828. Scene.prototype.addExternalData = function (key, data) {
  27829. if (!this._externalData) {
  27830. this._externalData = new BABYLON.StringDictionary();
  27831. }
  27832. return this._externalData.add(key, data);
  27833. };
  27834. /**
  27835. * Get an externaly attached data from its key
  27836. * @param key the unique key that identifies the data
  27837. * @return the associated data, if present (can be null), or undefined if not present
  27838. */
  27839. Scene.prototype.getExternalData = function (key) {
  27840. if (!this._externalData) {
  27841. return null;
  27842. }
  27843. return this._externalData.get(key);
  27844. };
  27845. /**
  27846. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27847. * @param key the unique key that identifies the data
  27848. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27849. * @return the associated data, can be null if the factory returned null.
  27850. */
  27851. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27852. if (!this._externalData) {
  27853. this._externalData = new BABYLON.StringDictionary();
  27854. }
  27855. return this._externalData.getOrAddWithFactory(key, factory);
  27856. };
  27857. /**
  27858. * Remove an externaly attached data from the Engine instance
  27859. * @param key the unique key that identifies the data
  27860. * @return true if the data was successfully removed, false if it doesn't exist
  27861. */
  27862. Scene.prototype.removeExternalData = function (key) {
  27863. return this._externalData.remove(key);
  27864. };
  27865. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27866. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27867. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27868. var step = _a[_i];
  27869. step.action(mesh, subMesh);
  27870. }
  27871. var material = subMesh.getMaterial();
  27872. if (material !== null && material !== undefined) {
  27873. // Render targets
  27874. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27875. if (this._processedMaterials.indexOf(material) === -1) {
  27876. this._processedMaterials.push(material);
  27877. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27878. }
  27879. }
  27880. // Dispatch
  27881. this._activeIndices.addCount(subMesh.indexCount, false);
  27882. this._renderingManager.dispatch(subMesh, mesh, material);
  27883. }
  27884. }
  27885. };
  27886. /**
  27887. * Clear the processed materials smart array preventing retention point in material dispose.
  27888. */
  27889. Scene.prototype.freeProcessedMaterials = function () {
  27890. this._processedMaterials.dispose();
  27891. };
  27892. /**
  27893. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27894. */
  27895. Scene.prototype.freeActiveMeshes = function () {
  27896. this._activeMeshes.dispose();
  27897. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27898. this.activeCamera._activeMeshes.dispose();
  27899. }
  27900. if (this.activeCameras) {
  27901. for (var i = 0; i < this.activeCameras.length; i++) {
  27902. var activeCamera = this.activeCameras[i];
  27903. if (activeCamera && activeCamera._activeMeshes) {
  27904. activeCamera._activeMeshes.dispose();
  27905. }
  27906. }
  27907. }
  27908. };
  27909. /**
  27910. * Clear the info related to rendering groups preventing retention points during dispose.
  27911. */
  27912. Scene.prototype.freeRenderingGroups = function () {
  27913. if (this._renderingManager) {
  27914. this._renderingManager.freeRenderingGroups();
  27915. }
  27916. if (this.textures) {
  27917. for (var i = 0; i < this.textures.length; i++) {
  27918. var texture = this.textures[i];
  27919. if (texture && texture.renderList) {
  27920. texture.freeRenderingGroups();
  27921. }
  27922. }
  27923. }
  27924. };
  27925. /** @hidden */
  27926. Scene.prototype._isInIntermediateRendering = function () {
  27927. return this._intermediateRendering;
  27928. };
  27929. /**
  27930. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27931. * @returns the current scene
  27932. */
  27933. Scene.prototype.freezeActiveMeshes = function () {
  27934. if (!this.activeCamera) {
  27935. return this;
  27936. }
  27937. if (!this._frustumPlanes) {
  27938. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27939. }
  27940. this._evaluateActiveMeshes();
  27941. this._activeMeshesFrozen = true;
  27942. return this;
  27943. };
  27944. /**
  27945. * Use this function to restart evaluating active meshes on every frame
  27946. * @returns the current scene
  27947. */
  27948. Scene.prototype.unfreezeActiveMeshes = function () {
  27949. this._activeMeshesFrozen = false;
  27950. return this;
  27951. };
  27952. Scene.prototype._evaluateActiveMeshes = function () {
  27953. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27954. return;
  27955. }
  27956. if (!this.activeCamera) {
  27957. return;
  27958. }
  27959. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27960. this.activeCamera._activeMeshes.reset();
  27961. this._activeMeshes.reset();
  27962. this._renderingManager.reset();
  27963. this._processedMaterials.reset();
  27964. this._activeParticleSystems.reset();
  27965. this._activeSkeletons.reset();
  27966. this._softwareSkinnedMeshes.reset();
  27967. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27968. var step = _a[_i];
  27969. step.action();
  27970. }
  27971. // Determine mesh candidates
  27972. var meshes = this.getActiveMeshCandidates();
  27973. // Check each mesh
  27974. var len = meshes.length;
  27975. for (var i = 0; i < len; i++) {
  27976. var mesh = meshes.data[i];
  27977. if (mesh.isBlocked) {
  27978. continue;
  27979. }
  27980. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27981. if (!mesh.isReady() || !mesh.isEnabled()) {
  27982. continue;
  27983. }
  27984. mesh.computeWorldMatrix();
  27985. // Intersections
  27986. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27987. this._meshesForIntersections.pushNoDuplicate(mesh);
  27988. }
  27989. // Switch to current LOD
  27990. var meshLOD = mesh.getLOD(this.activeCamera);
  27991. if (meshLOD === undefined || meshLOD === null) {
  27992. continue;
  27993. }
  27994. mesh._preActivate();
  27995. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27996. this._activeMeshes.push(mesh);
  27997. this.activeCamera._activeMeshes.push(mesh);
  27998. mesh._activate(this._renderId);
  27999. if (meshLOD !== mesh) {
  28000. meshLOD._activate(this._renderId);
  28001. }
  28002. this._activeMesh(mesh, meshLOD);
  28003. }
  28004. }
  28005. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28006. // Particle systems
  28007. if (this.particlesEnabled) {
  28008. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28009. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28010. var particleSystem = this.particleSystems[particleIndex];
  28011. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28012. continue;
  28013. }
  28014. var emitter = particleSystem.emitter;
  28015. if (!emitter.position || emitter.isEnabled()) {
  28016. this._activeParticleSystems.push(particleSystem);
  28017. particleSystem.animate();
  28018. this._renderingManager.dispatchParticles(particleSystem);
  28019. }
  28020. }
  28021. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28022. }
  28023. };
  28024. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28025. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28026. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28027. mesh.skeleton.prepare();
  28028. }
  28029. if (!mesh.computeBonesUsingShaders) {
  28030. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28031. }
  28032. }
  28033. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28034. var step = _a[_i];
  28035. step.action(sourceMesh, mesh);
  28036. }
  28037. if (mesh !== undefined && mesh !== null
  28038. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28039. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28040. var len = subMeshes.length;
  28041. for (var i = 0; i < len; i++) {
  28042. var subMesh = subMeshes.data[i];
  28043. this._evaluateSubMesh(subMesh, mesh);
  28044. }
  28045. }
  28046. };
  28047. /**
  28048. * Update the transform matrix to update from the current active camera
  28049. * @param force defines a boolean used to force the update even if cache is up to date
  28050. */
  28051. Scene.prototype.updateTransformMatrix = function (force) {
  28052. if (!this.activeCamera) {
  28053. return;
  28054. }
  28055. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28056. };
  28057. /**
  28058. * 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)
  28059. * @param alternateCamera defines the camera to use
  28060. */
  28061. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28062. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28063. };
  28064. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28065. if (camera && camera._skipRendering) {
  28066. return;
  28067. }
  28068. var engine = this._engine;
  28069. this.activeCamera = camera;
  28070. if (!this.activeCamera)
  28071. throw new Error("Active camera not set");
  28072. // Viewport
  28073. engine.setViewport(this.activeCamera.viewport);
  28074. // Camera
  28075. this.resetCachedMaterial();
  28076. this._renderId++;
  28077. this.updateTransformMatrix();
  28078. if (camera._alternateCamera) {
  28079. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28080. this._alternateRendering = true;
  28081. }
  28082. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28083. // Meshes
  28084. this._evaluateActiveMeshes();
  28085. // Software skinning
  28086. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28087. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28088. mesh.applySkeleton(mesh.skeleton);
  28089. }
  28090. // Render targets
  28091. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28092. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28093. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28094. }
  28095. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28096. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28097. }
  28098. // Collects render targets from external components.
  28099. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28100. var step = _a[_i];
  28101. step.action(this._renderTargets);
  28102. }
  28103. if (this.renderTargetsEnabled) {
  28104. this._intermediateRendering = true;
  28105. if (this._renderTargets.length > 0) {
  28106. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28107. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28108. var renderTarget = this._renderTargets.data[renderIndex];
  28109. if (renderTarget._shouldRender()) {
  28110. this._renderId++;
  28111. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28112. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28113. }
  28114. }
  28115. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28116. this._renderId++;
  28117. }
  28118. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28119. var step = _c[_b];
  28120. step.action(this.activeCamera);
  28121. }
  28122. this._intermediateRendering = false;
  28123. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28124. }
  28125. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28126. // Prepare Frame
  28127. if (this.postProcessManager) {
  28128. this.postProcessManager._prepareFrame();
  28129. }
  28130. // Before Camera Draw
  28131. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28132. var step = _e[_d];
  28133. step.action(this.activeCamera);
  28134. }
  28135. // Render
  28136. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28137. this._renderingManager.render(null, null, true, true);
  28138. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28139. // After Camera Draw
  28140. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28141. var step = _g[_f];
  28142. step.action(this.activeCamera);
  28143. }
  28144. // Finalize frame
  28145. if (this.postProcessManager) {
  28146. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28147. }
  28148. // Reset some special arrays
  28149. this._renderTargets.reset();
  28150. this._alternateRendering = false;
  28151. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28152. };
  28153. Scene.prototype._processSubCameras = function (camera) {
  28154. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28155. this._renderForCamera(camera);
  28156. return;
  28157. }
  28158. // rig cameras
  28159. for (var index = 0; index < camera._rigCameras.length; index++) {
  28160. this._renderForCamera(camera._rigCameras[index], camera);
  28161. }
  28162. this.activeCamera = camera;
  28163. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28164. };
  28165. Scene.prototype._checkIntersections = function () {
  28166. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28167. var sourceMesh = this._meshesForIntersections.data[index];
  28168. if (!sourceMesh.actionManager) {
  28169. continue;
  28170. }
  28171. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28172. var action = sourceMesh.actionManager.actions[actionIndex];
  28173. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28174. var parameters = action.getTriggerParameter();
  28175. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28176. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28177. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28178. if (areIntersecting && currentIntersectionInProgress === -1) {
  28179. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28180. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28181. sourceMesh._intersectionsInProgress.push(otherMesh);
  28182. }
  28183. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28184. sourceMesh._intersectionsInProgress.push(otherMesh);
  28185. }
  28186. }
  28187. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28188. //They intersected, and now they don't.
  28189. //is this trigger an exit trigger? execute an event.
  28190. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28191. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28192. }
  28193. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28194. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28195. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28196. return otherMesh === parameterMesh;
  28197. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28198. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28199. }
  28200. }
  28201. }
  28202. }
  28203. }
  28204. };
  28205. /** @hidden */
  28206. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28207. // Do nothing. Code will be replaced if physics engine component is referenced
  28208. };
  28209. /**
  28210. * Render the scene
  28211. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28212. */
  28213. Scene.prototype.render = function (updateCameras) {
  28214. if (updateCameras === void 0) { updateCameras = true; }
  28215. if (this.isDisposed) {
  28216. return;
  28217. }
  28218. this._frameId++;
  28219. // Register components that have been associated lately to the scene.
  28220. this._registerTransientComponents();
  28221. this._activeParticles.fetchNewFrame();
  28222. this._totalVertices.fetchNewFrame();
  28223. this._activeIndices.fetchNewFrame();
  28224. this._activeBones.fetchNewFrame();
  28225. this._meshesForIntersections.reset();
  28226. this.resetCachedMaterial();
  28227. this.onBeforeAnimationsObservable.notifyObservers(this);
  28228. // Actions
  28229. if (this.actionManager) {
  28230. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28231. }
  28232. if (this._engine.isDeterministicLockStep()) {
  28233. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28234. var defaultFPS = (60.0 / 1000.0);
  28235. var defaultFrameTime = this.getDeterministicFrameTime();
  28236. var stepsTaken = 0;
  28237. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28238. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28239. internalSteps = Math.min(internalSteps, maxSubSteps);
  28240. do {
  28241. this.onBeforeStepObservable.notifyObservers(this);
  28242. // Animations
  28243. this._animationRatio = defaultFrameTime * defaultFPS;
  28244. this._animate();
  28245. this.onAfterAnimationsObservable.notifyObservers(this);
  28246. // Physics
  28247. this._advancePhysicsEngineStep(defaultFrameTime);
  28248. this.onAfterStepObservable.notifyObservers(this);
  28249. this._currentStepId++;
  28250. stepsTaken++;
  28251. deltaTime -= defaultFrameTime;
  28252. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28253. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28254. }
  28255. else {
  28256. // Animations
  28257. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28258. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28259. this._animate();
  28260. this.onAfterAnimationsObservable.notifyObservers(this);
  28261. // Physics
  28262. this._advancePhysicsEngineStep(deltaTime);
  28263. }
  28264. // Before camera update steps
  28265. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28266. var step = _a[_i];
  28267. step.action();
  28268. }
  28269. // Update Cameras
  28270. if (updateCameras) {
  28271. if (this.activeCameras.length > 0) {
  28272. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28273. var camera = this.activeCameras[cameraIndex];
  28274. camera.update();
  28275. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28276. // rig cameras
  28277. for (var index = 0; index < camera._rigCameras.length; index++) {
  28278. camera._rigCameras[index].update();
  28279. }
  28280. }
  28281. }
  28282. }
  28283. else if (this.activeCamera) {
  28284. this.activeCamera.update();
  28285. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28286. // rig cameras
  28287. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28288. this.activeCamera._rigCameras[index].update();
  28289. }
  28290. }
  28291. }
  28292. }
  28293. // Before render
  28294. this.onBeforeRenderObservable.notifyObservers(this);
  28295. // Customs render targets
  28296. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28297. var engine = this.getEngine();
  28298. var currentActiveCamera = this.activeCamera;
  28299. if (this.renderTargetsEnabled) {
  28300. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28301. this._intermediateRendering = true;
  28302. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28303. var renderTarget = this.customRenderTargets[customIndex];
  28304. if (renderTarget._shouldRender()) {
  28305. this._renderId++;
  28306. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28307. if (!this.activeCamera)
  28308. throw new Error("Active camera not set");
  28309. // Viewport
  28310. engine.setViewport(this.activeCamera.viewport);
  28311. // Camera
  28312. this.updateTransformMatrix();
  28313. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28314. }
  28315. }
  28316. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28317. this._intermediateRendering = false;
  28318. this._renderId++;
  28319. }
  28320. // Restore back buffer
  28321. if (this.customRenderTargets.length > 0) {
  28322. engine.restoreDefaultFramebuffer();
  28323. }
  28324. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28325. this.activeCamera = currentActiveCamera;
  28326. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28327. var step = _c[_b];
  28328. step.action();
  28329. }
  28330. // Clear
  28331. if (this.autoClearDepthAndStencil || this.autoClear) {
  28332. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28333. }
  28334. // Collects render targets from external components.
  28335. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28336. var step = _e[_d];
  28337. step.action(this._renderTargets);
  28338. }
  28339. // Multi-cameras?
  28340. if (this.activeCameras.length > 0) {
  28341. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28342. if (cameraIndex > 0) {
  28343. this._engine.clear(null, false, true, true);
  28344. }
  28345. this._processSubCameras(this.activeCameras[cameraIndex]);
  28346. }
  28347. }
  28348. else {
  28349. if (!this.activeCamera) {
  28350. throw new Error("No camera defined");
  28351. }
  28352. this._processSubCameras(this.activeCamera);
  28353. }
  28354. // Intersection checks
  28355. this._checkIntersections();
  28356. // Executes the after render stage actions.
  28357. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28358. var step = _g[_f];
  28359. step.action();
  28360. }
  28361. // After render
  28362. if (this.afterRender) {
  28363. this.afterRender();
  28364. }
  28365. this.onAfterRenderObservable.notifyObservers(this);
  28366. // Cleaning
  28367. if (this._toBeDisposed.length) {
  28368. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28369. var data = this._toBeDisposed[index];
  28370. if (data) {
  28371. data.dispose();
  28372. }
  28373. }
  28374. this._toBeDisposed = [];
  28375. }
  28376. if (this.dumpNextRenderTargets) {
  28377. this.dumpNextRenderTargets = false;
  28378. }
  28379. this._activeBones.addCount(0, true);
  28380. this._activeIndices.addCount(0, true);
  28381. this._activeParticles.addCount(0, true);
  28382. };
  28383. /**
  28384. * Freeze all materials
  28385. * A frozen material will not be updatable but should be faster to render
  28386. */
  28387. Scene.prototype.freezeMaterials = function () {
  28388. for (var i = 0; i < this.materials.length; i++) {
  28389. this.materials[i].freeze();
  28390. }
  28391. };
  28392. /**
  28393. * Unfreeze all materials
  28394. * A frozen material will not be updatable but should be faster to render
  28395. */
  28396. Scene.prototype.unfreezeMaterials = function () {
  28397. for (var i = 0; i < this.materials.length; i++) {
  28398. this.materials[i].unfreeze();
  28399. }
  28400. };
  28401. /**
  28402. * Releases all held ressources
  28403. */
  28404. Scene.prototype.dispose = function () {
  28405. this.beforeRender = null;
  28406. this.afterRender = null;
  28407. this.skeletons = [];
  28408. this.morphTargetManagers = [];
  28409. this._transientComponents = [];
  28410. this._isReadyForMeshStage.clear();
  28411. this._beforeEvaluateActiveMeshStage.clear();
  28412. this._evaluateSubMeshStage.clear();
  28413. this._activeMeshStage.clear();
  28414. this._cameraDrawRenderTargetStage.clear();
  28415. this._beforeCameraDrawStage.clear();
  28416. this._beforeRenderingGroupDrawStage.clear();
  28417. this._beforeRenderingMeshStage.clear();
  28418. this._afterRenderingMeshStage.clear();
  28419. this._afterRenderingGroupDrawStage.clear();
  28420. this._afterCameraDrawStage.clear();
  28421. this._afterRenderStage.clear();
  28422. this._beforeCameraUpdateStage.clear();
  28423. this._beforeClearStage.clear();
  28424. this._gatherRenderTargetsStage.clear();
  28425. this._gatherActiveCameraRenderTargetsStage.clear();
  28426. this._pointerMoveStage.clear();
  28427. this._pointerDownStage.clear();
  28428. this._pointerUpStage.clear();
  28429. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28430. var component = _a[_i];
  28431. component.dispose();
  28432. }
  28433. this.importedMeshesFiles = new Array();
  28434. this.stopAllAnimations();
  28435. this.resetCachedMaterial();
  28436. // Smart arrays
  28437. if (this.activeCamera) {
  28438. this.activeCamera._activeMeshes.dispose();
  28439. this.activeCamera = null;
  28440. }
  28441. this._activeMeshes.dispose();
  28442. this._renderingManager.dispose();
  28443. this._processedMaterials.dispose();
  28444. this._activeParticleSystems.dispose();
  28445. this._activeSkeletons.dispose();
  28446. this._softwareSkinnedMeshes.dispose();
  28447. this._renderTargets.dispose();
  28448. this._registeredForLateAnimationBindings.dispose();
  28449. this._meshesForIntersections.dispose();
  28450. this._toBeDisposed = [];
  28451. // Abort active requests
  28452. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28453. var request = _c[_b];
  28454. request.abort();
  28455. }
  28456. // Events
  28457. this.onDisposeObservable.notifyObservers(this);
  28458. this.onDisposeObservable.clear();
  28459. this.onBeforeRenderObservable.clear();
  28460. this.onAfterRenderObservable.clear();
  28461. this.onBeforeRenderTargetsRenderObservable.clear();
  28462. this.onAfterRenderTargetsRenderObservable.clear();
  28463. this.onAfterStepObservable.clear();
  28464. this.onBeforeStepObservable.clear();
  28465. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28466. this.onAfterActiveMeshesEvaluationObservable.clear();
  28467. this.onBeforeParticlesRenderingObservable.clear();
  28468. this.onAfterParticlesRenderingObservable.clear();
  28469. this.onBeforeDrawPhaseObservable.clear();
  28470. this.onAfterDrawPhaseObservable.clear();
  28471. this.onBeforeAnimationsObservable.clear();
  28472. this.onAfterAnimationsObservable.clear();
  28473. this.onDataLoadedObservable.clear();
  28474. this.onBeforeRenderingGroupObservable.clear();
  28475. this.onAfterRenderingGroupObservable.clear();
  28476. this.onMeshImportedObservable.clear();
  28477. this.onBeforeCameraRenderObservable.clear();
  28478. this.onAfterCameraRenderObservable.clear();
  28479. this.onReadyObservable.clear();
  28480. this.onNewCameraAddedObservable.clear();
  28481. this.onCameraRemovedObservable.clear();
  28482. this.onNewLightAddedObservable.clear();
  28483. this.onLightRemovedObservable.clear();
  28484. this.onNewGeometryAddedObservable.clear();
  28485. this.onGeometryRemovedObservable.clear();
  28486. this.onNewTransformNodeAddedObservable.clear();
  28487. this.onTransformNodeRemovedObservable.clear();
  28488. this.onNewMeshAddedObservable.clear();
  28489. this.onMeshRemovedObservable.clear();
  28490. this.onNewMaterialAddedObservable.clear();
  28491. this.onMaterialRemovedObservable.clear();
  28492. this.onNewTextureAddedObservable.clear();
  28493. this.onTextureRemovedObservable.clear();
  28494. this.onPrePointerObservable.clear();
  28495. this.onPointerObservable.clear();
  28496. this.onPreKeyboardObservable.clear();
  28497. this.onKeyboardObservable.clear();
  28498. this.detachControl();
  28499. // Detach cameras
  28500. var canvas = this._engine.getRenderingCanvas();
  28501. if (canvas) {
  28502. var index;
  28503. for (index = 0; index < this.cameras.length; index++) {
  28504. this.cameras[index].detachControl(canvas);
  28505. }
  28506. }
  28507. // Release animation groups
  28508. while (this.animationGroups.length) {
  28509. this.animationGroups[0].dispose();
  28510. }
  28511. // Release lights
  28512. while (this.lights.length) {
  28513. this.lights[0].dispose();
  28514. }
  28515. // Release meshes
  28516. while (this.meshes.length) {
  28517. this.meshes[0].dispose(true);
  28518. }
  28519. while (this.transformNodes.length) {
  28520. this.removeTransformNode(this.transformNodes[0]);
  28521. }
  28522. // Release cameras
  28523. while (this.cameras.length) {
  28524. this.cameras[0].dispose();
  28525. }
  28526. // Release materials
  28527. if (this.defaultMaterial) {
  28528. this.defaultMaterial.dispose();
  28529. }
  28530. while (this.multiMaterials.length) {
  28531. this.multiMaterials[0].dispose();
  28532. }
  28533. while (this.materials.length) {
  28534. this.materials[0].dispose();
  28535. }
  28536. // Release particles
  28537. while (this.particleSystems.length) {
  28538. this.particleSystems[0].dispose();
  28539. }
  28540. // Release postProcesses
  28541. while (this.postProcesses.length) {
  28542. this.postProcesses[0].dispose();
  28543. }
  28544. // Release textures
  28545. while (this.textures.length) {
  28546. this.textures[0].dispose();
  28547. }
  28548. // Release UBO
  28549. this._sceneUbo.dispose();
  28550. if (this._alternateSceneUbo) {
  28551. this._alternateSceneUbo.dispose();
  28552. }
  28553. // Post-processes
  28554. this.postProcessManager.dispose();
  28555. // Remove from engine
  28556. index = this._engine.scenes.indexOf(this);
  28557. if (index > -1) {
  28558. this._engine.scenes.splice(index, 1);
  28559. }
  28560. this._engine.wipeCaches(true);
  28561. this._isDisposed = true;
  28562. };
  28563. Object.defineProperty(Scene.prototype, "isDisposed", {
  28564. /**
  28565. * Gets if the scene is already disposed
  28566. */
  28567. get: function () {
  28568. return this._isDisposed;
  28569. },
  28570. enumerable: true,
  28571. configurable: true
  28572. });
  28573. /**
  28574. * Call this function to reduce memory footprint of the scene.
  28575. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28576. */
  28577. Scene.prototype.clearCachedVertexData = function () {
  28578. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28579. var mesh = this.meshes[meshIndex];
  28580. var geometry = mesh.geometry;
  28581. if (geometry) {
  28582. geometry._indices = [];
  28583. for (var vbName in geometry._vertexBuffers) {
  28584. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28585. continue;
  28586. }
  28587. geometry._vertexBuffers[vbName]._buffer._data = null;
  28588. }
  28589. }
  28590. }
  28591. };
  28592. /**
  28593. * This function will remove the local cached buffer data from texture.
  28594. * It will save memory but will prevent the texture from being rebuilt
  28595. */
  28596. Scene.prototype.cleanCachedTextureBuffer = function () {
  28597. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28598. var baseTexture = _a[_i];
  28599. var buffer = baseTexture._buffer;
  28600. if (buffer) {
  28601. baseTexture._buffer = null;
  28602. }
  28603. }
  28604. };
  28605. /**
  28606. * Get the world extend vectors with an optional filter
  28607. *
  28608. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28609. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28610. */
  28611. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28612. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28613. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28614. filterPredicate = filterPredicate || (function () { return true; });
  28615. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28616. mesh.computeWorldMatrix(true);
  28617. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28618. return;
  28619. }
  28620. var boundingInfo = mesh.getBoundingInfo();
  28621. var minBox = boundingInfo.boundingBox.minimumWorld;
  28622. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28623. BABYLON.Tools.CheckExtends(minBox, min, max);
  28624. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28625. });
  28626. return {
  28627. min: min,
  28628. max: max
  28629. };
  28630. };
  28631. // Picking
  28632. /**
  28633. * Creates a ray that can be used to pick in the scene
  28634. * @param x defines the x coordinate of the origin (on-screen)
  28635. * @param y defines the y coordinate of the origin (on-screen)
  28636. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28637. * @param camera defines the camera to use for the picking
  28638. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28639. * @returns a Ray
  28640. */
  28641. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28642. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28643. var result = BABYLON.Ray.Zero();
  28644. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28645. return result;
  28646. };
  28647. /**
  28648. * Creates a ray that can be used to pick in the scene
  28649. * @param x defines the x coordinate of the origin (on-screen)
  28650. * @param y defines the y coordinate of the origin (on-screen)
  28651. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28652. * @param result defines the ray where to store the picking ray
  28653. * @param camera defines the camera to use for the picking
  28654. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28655. * @returns the current scene
  28656. */
  28657. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28658. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28659. var engine = this._engine;
  28660. if (!camera) {
  28661. if (!this.activeCamera)
  28662. throw new Error("Active camera not set");
  28663. camera = this.activeCamera;
  28664. }
  28665. var cameraViewport = camera.viewport;
  28666. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28667. // Moving coordinates to local viewport world
  28668. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28669. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28670. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28671. return this;
  28672. };
  28673. /**
  28674. * Creates a ray that can be used to pick in the scene
  28675. * @param x defines the x coordinate of the origin (on-screen)
  28676. * @param y defines the y coordinate of the origin (on-screen)
  28677. * @param camera defines the camera to use for the picking
  28678. * @returns a Ray
  28679. */
  28680. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28681. var result = BABYLON.Ray.Zero();
  28682. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28683. return result;
  28684. };
  28685. /**
  28686. * Creates a ray that can be used to pick in the scene
  28687. * @param x defines the x coordinate of the origin (on-screen)
  28688. * @param y defines the y coordinate of the origin (on-screen)
  28689. * @param result defines the ray where to store the picking ray
  28690. * @param camera defines the camera to use for the picking
  28691. * @returns the current scene
  28692. */
  28693. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28694. if (!BABYLON.PickingInfo) {
  28695. return this;
  28696. }
  28697. var engine = this._engine;
  28698. if (!camera) {
  28699. if (!this.activeCamera)
  28700. throw new Error("Active camera not set");
  28701. camera = this.activeCamera;
  28702. }
  28703. var cameraViewport = camera.viewport;
  28704. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28705. var identity = BABYLON.Matrix.Identity();
  28706. // Moving coordinates to local viewport world
  28707. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28708. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28709. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28710. return this;
  28711. };
  28712. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28713. if (!BABYLON.PickingInfo) {
  28714. return null;
  28715. }
  28716. var pickingInfo = null;
  28717. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28718. var mesh = this.meshes[meshIndex];
  28719. if (predicate) {
  28720. if (!predicate(mesh)) {
  28721. continue;
  28722. }
  28723. }
  28724. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28725. continue;
  28726. }
  28727. var world = mesh.getWorldMatrix();
  28728. var ray = rayFunction(world);
  28729. var result = mesh.intersects(ray, fastCheck);
  28730. if (!result || !result.hit)
  28731. continue;
  28732. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28733. continue;
  28734. pickingInfo = result;
  28735. if (fastCheck) {
  28736. break;
  28737. }
  28738. }
  28739. return pickingInfo || new BABYLON.PickingInfo();
  28740. };
  28741. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28742. if (!BABYLON.PickingInfo) {
  28743. return null;
  28744. }
  28745. var pickingInfos = new Array();
  28746. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28747. var mesh = this.meshes[meshIndex];
  28748. if (predicate) {
  28749. if (!predicate(mesh)) {
  28750. continue;
  28751. }
  28752. }
  28753. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28754. continue;
  28755. }
  28756. var world = mesh.getWorldMatrix();
  28757. var ray = rayFunction(world);
  28758. var result = mesh.intersects(ray, false);
  28759. if (!result || !result.hit)
  28760. continue;
  28761. pickingInfos.push(result);
  28762. }
  28763. return pickingInfos;
  28764. };
  28765. /** Launch a ray to try to pick a mesh in the scene
  28766. * @param x position on screen
  28767. * @param y position on screen
  28768. * @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
  28769. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28770. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28771. * @returns a PickingInfo
  28772. */
  28773. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28774. var _this = this;
  28775. if (!BABYLON.PickingInfo) {
  28776. return null;
  28777. }
  28778. var result = this._internalPick(function (world) {
  28779. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28780. return _this._tempPickingRay;
  28781. }, predicate, fastCheck);
  28782. if (result) {
  28783. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28784. }
  28785. return result;
  28786. };
  28787. /** Use the given ray to pick a mesh in the scene
  28788. * @param ray The ray to use to pick meshes
  28789. * @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
  28790. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28791. * @returns a PickingInfo
  28792. */
  28793. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28794. var _this = this;
  28795. var result = this._internalPick(function (world) {
  28796. if (!_this._pickWithRayInverseMatrix) {
  28797. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28798. }
  28799. world.invertToRef(_this._pickWithRayInverseMatrix);
  28800. if (!_this._cachedRayForTransform) {
  28801. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28802. }
  28803. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28804. return _this._cachedRayForTransform;
  28805. }, predicate, fastCheck);
  28806. if (result) {
  28807. result.ray = ray;
  28808. }
  28809. return result;
  28810. };
  28811. /**
  28812. * Launch a ray to try to pick a mesh in the scene
  28813. * @param x X position on screen
  28814. * @param y Y position on screen
  28815. * @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
  28816. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28817. * @returns an array of PickingInfo
  28818. */
  28819. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28820. var _this = this;
  28821. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28822. };
  28823. /**
  28824. * Launch a ray to try to pick a mesh in the scene
  28825. * @param ray Ray to use
  28826. * @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
  28827. * @returns an array of PickingInfo
  28828. */
  28829. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28830. var _this = this;
  28831. return this._internalMultiPick(function (world) {
  28832. if (!_this._pickWithRayInverseMatrix) {
  28833. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28834. }
  28835. world.invertToRef(_this._pickWithRayInverseMatrix);
  28836. if (!_this._cachedRayForTransform) {
  28837. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28838. }
  28839. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28840. return _this._cachedRayForTransform;
  28841. }, predicate);
  28842. };
  28843. /**
  28844. * Force the value of meshUnderPointer
  28845. * @param mesh defines the mesh to use
  28846. */
  28847. Scene.prototype.setPointerOverMesh = function (mesh) {
  28848. if (this._pointerOverMesh === mesh) {
  28849. return;
  28850. }
  28851. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28852. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28853. }
  28854. this._pointerOverMesh = mesh;
  28855. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28856. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28857. }
  28858. };
  28859. /**
  28860. * Gets the mesh under the pointer
  28861. * @returns a Mesh or null if no mesh is under the pointer
  28862. */
  28863. Scene.prototype.getPointerOverMesh = function () {
  28864. return this._pointerOverMesh;
  28865. };
  28866. // Misc.
  28867. /** @hidden */
  28868. Scene.prototype._rebuildGeometries = function () {
  28869. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28870. var geometry = _a[_i];
  28871. geometry._rebuild();
  28872. }
  28873. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28874. var mesh = _c[_b];
  28875. mesh._rebuild();
  28876. }
  28877. if (this.postProcessManager) {
  28878. this.postProcessManager._rebuild();
  28879. }
  28880. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28881. var component = _e[_d];
  28882. component.rebuild();
  28883. }
  28884. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28885. var system = _g[_f];
  28886. system.rebuild();
  28887. }
  28888. };
  28889. /** @hidden */
  28890. Scene.prototype._rebuildTextures = function () {
  28891. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28892. var texture = _a[_i];
  28893. texture._rebuild();
  28894. }
  28895. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28896. };
  28897. // Tags
  28898. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28899. if (tagsQuery === undefined) {
  28900. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28901. return list;
  28902. }
  28903. var listByTags = [];
  28904. forEach = forEach || (function (item) { return; });
  28905. for (var i in list) {
  28906. var item = list[i];
  28907. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28908. listByTags.push(item);
  28909. forEach(item);
  28910. }
  28911. }
  28912. return listByTags;
  28913. };
  28914. /**
  28915. * Get a list of meshes by tags
  28916. * @param tagsQuery defines the tags query to use
  28917. * @param forEach defines a predicate used to filter results
  28918. * @returns an array of Mesh
  28919. */
  28920. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28921. return this._getByTags(this.meshes, tagsQuery, forEach);
  28922. };
  28923. /**
  28924. * Get a list of cameras by tags
  28925. * @param tagsQuery defines the tags query to use
  28926. * @param forEach defines a predicate used to filter results
  28927. * @returns an array of Camera
  28928. */
  28929. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28930. return this._getByTags(this.cameras, tagsQuery, forEach);
  28931. };
  28932. /**
  28933. * Get a list of lights by tags
  28934. * @param tagsQuery defines the tags query to use
  28935. * @param forEach defines a predicate used to filter results
  28936. * @returns an array of Light
  28937. */
  28938. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28939. return this._getByTags(this.lights, tagsQuery, forEach);
  28940. };
  28941. /**
  28942. * Get a list of materials by tags
  28943. * @param tagsQuery defines the tags query to use
  28944. * @param forEach defines a predicate used to filter results
  28945. * @returns an array of Material
  28946. */
  28947. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28948. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28949. };
  28950. /**
  28951. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28952. * This allowed control for front to back rendering or reversly depending of the special needs.
  28953. *
  28954. * @param renderingGroupId The rendering group id corresponding to its index
  28955. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28956. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28957. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28958. */
  28959. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28960. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28961. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28962. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28963. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28964. };
  28965. /**
  28966. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28967. *
  28968. * @param renderingGroupId The rendering group id corresponding to its index
  28969. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28970. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28971. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28972. */
  28973. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28974. if (depth === void 0) { depth = true; }
  28975. if (stencil === void 0) { stencil = true; }
  28976. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28977. };
  28978. /**
  28979. * Gets the current auto clear configuration for one rendering group of the rendering
  28980. * manager.
  28981. * @param index the rendering group index to get the information for
  28982. * @returns The auto clear setup for the requested rendering group
  28983. */
  28984. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28985. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28986. };
  28987. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  28988. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  28989. get: function () {
  28990. return this._blockMaterialDirtyMechanism;
  28991. },
  28992. set: function (value) {
  28993. if (this._blockMaterialDirtyMechanism === value) {
  28994. return;
  28995. }
  28996. this._blockMaterialDirtyMechanism = value;
  28997. if (!value) { // Do a complete update
  28998. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  28999. }
  29000. },
  29001. enumerable: true,
  29002. configurable: true
  29003. });
  29004. /**
  29005. * Will flag all materials as dirty to trigger new shader compilation
  29006. * @param flag defines the flag used to specify which material part must be marked as dirty
  29007. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29008. */
  29009. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29010. if (this._blockMaterialDirtyMechanism) {
  29011. return;
  29012. }
  29013. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29014. var material = _a[_i];
  29015. if (predicate && !predicate(material)) {
  29016. continue;
  29017. }
  29018. material.markAsDirty(flag);
  29019. }
  29020. };
  29021. /** @hidden */
  29022. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29023. var _this = this;
  29024. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29025. this._activeRequests.push(request);
  29026. request.onCompleteObservable.add(function (request) {
  29027. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29028. });
  29029. return request;
  29030. };
  29031. /** @hidden */
  29032. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29033. var _this = this;
  29034. return new Promise(function (resolve, reject) {
  29035. _this._loadFile(url, function (data) {
  29036. resolve(data);
  29037. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29038. reject(exception);
  29039. });
  29040. });
  29041. };
  29042. // Statics
  29043. Scene._uniqueIdCounter = 0;
  29044. /** The fog is deactivated */
  29045. Scene.FOGMODE_NONE = 0;
  29046. /** The fog density is following an exponential function */
  29047. Scene.FOGMODE_EXP = 1;
  29048. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29049. Scene.FOGMODE_EXP2 = 2;
  29050. /** The fog density is following a linear function. */
  29051. Scene.FOGMODE_LINEAR = 3;
  29052. /**
  29053. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29054. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29055. */
  29056. Scene.MinDeltaTime = 1.0;
  29057. /**
  29058. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29059. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29060. */
  29061. Scene.MaxDeltaTime = 1000.0;
  29062. /** The distance in pixel that you have to move to prevent some events */
  29063. Scene.DragMovementThreshold = 10; // in pixels
  29064. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29065. Scene.LongPressDelay = 500; // in milliseconds
  29066. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29067. Scene.DoubleClickDelay = 300; // in milliseconds
  29068. /** If you need to check double click without raising a single click at first click, enable this flag */
  29069. Scene.ExclusiveDoubleClickMode = false;
  29070. return Scene;
  29071. }(BABYLON.AbstractScene));
  29072. BABYLON.Scene = Scene;
  29073. })(BABYLON || (BABYLON = {}));
  29074. //# sourceMappingURL=babylon.scene.js.map
  29075. var BABYLON;
  29076. (function (BABYLON) {
  29077. /**
  29078. * Set of assets to keep when moving a scene into an asset container.
  29079. */
  29080. var KeepAssets = /** @class */ (function (_super) {
  29081. __extends(KeepAssets, _super);
  29082. function KeepAssets() {
  29083. return _super !== null && _super.apply(this, arguments) || this;
  29084. }
  29085. return KeepAssets;
  29086. }(BABYLON.AbstractScene));
  29087. BABYLON.KeepAssets = KeepAssets;
  29088. /**
  29089. * Container with a set of assets that can be added or removed from a scene.
  29090. */
  29091. var AssetContainer = /** @class */ (function (_super) {
  29092. __extends(AssetContainer, _super);
  29093. /**
  29094. * Instantiates an AssetContainer.
  29095. * @param scene The scene the AssetContainer belongs to.
  29096. */
  29097. function AssetContainer(scene) {
  29098. var _this = _super.call(this) || this;
  29099. _this.scene = scene;
  29100. return _this;
  29101. }
  29102. /**
  29103. * Adds all the assets from the container to the scene.
  29104. */
  29105. AssetContainer.prototype.addAllToScene = function () {
  29106. var _this = this;
  29107. this.cameras.forEach(function (o) {
  29108. _this.scene.addCamera(o);
  29109. });
  29110. this.lights.forEach(function (o) {
  29111. _this.scene.addLight(o);
  29112. });
  29113. this.meshes.forEach(function (o) {
  29114. _this.scene.addMesh(o);
  29115. });
  29116. this.skeletons.forEach(function (o) {
  29117. _this.scene.addSkeleton(o);
  29118. });
  29119. this.animations.forEach(function (o) {
  29120. _this.scene.addAnimation(o);
  29121. });
  29122. this.animationGroups.forEach(function (o) {
  29123. _this.scene.addAnimationGroup(o);
  29124. });
  29125. this.multiMaterials.forEach(function (o) {
  29126. _this.scene.addMultiMaterial(o);
  29127. });
  29128. this.materials.forEach(function (o) {
  29129. _this.scene.addMaterial(o);
  29130. });
  29131. this.morphTargetManagers.forEach(function (o) {
  29132. _this.scene.addMorphTargetManager(o);
  29133. });
  29134. this.geometries.forEach(function (o) {
  29135. _this.scene.addGeometry(o);
  29136. });
  29137. this.transformNodes.forEach(function (o) {
  29138. _this.scene.addTransformNode(o);
  29139. });
  29140. this.actionManagers.forEach(function (o) {
  29141. _this.scene.addActionManager(o);
  29142. });
  29143. this.textures.forEach(function (o) {
  29144. _this.scene.addTexture(o);
  29145. });
  29146. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29147. var component = _a[_i];
  29148. component.addFromContainer(this.scene);
  29149. }
  29150. };
  29151. /**
  29152. * Removes all the assets in the container from the scene
  29153. */
  29154. AssetContainer.prototype.removeAllFromScene = function () {
  29155. var _this = this;
  29156. this.cameras.forEach(function (o) {
  29157. _this.scene.removeCamera(o);
  29158. });
  29159. this.lights.forEach(function (o) {
  29160. _this.scene.removeLight(o);
  29161. });
  29162. this.meshes.forEach(function (o) {
  29163. _this.scene.removeMesh(o);
  29164. });
  29165. this.skeletons.forEach(function (o) {
  29166. _this.scene.removeSkeleton(o);
  29167. });
  29168. this.animations.forEach(function (o) {
  29169. _this.scene.removeAnimation(o);
  29170. });
  29171. this.animationGroups.forEach(function (o) {
  29172. _this.scene.removeAnimationGroup(o);
  29173. });
  29174. this.multiMaterials.forEach(function (o) {
  29175. _this.scene.removeMultiMaterial(o);
  29176. });
  29177. this.materials.forEach(function (o) {
  29178. _this.scene.removeMaterial(o);
  29179. });
  29180. this.morphTargetManagers.forEach(function (o) {
  29181. _this.scene.removeMorphTargetManager(o);
  29182. });
  29183. this.geometries.forEach(function (o) {
  29184. _this.scene.removeGeometry(o);
  29185. });
  29186. this.transformNodes.forEach(function (o) {
  29187. _this.scene.removeTransformNode(o);
  29188. });
  29189. this.actionManagers.forEach(function (o) {
  29190. _this.scene.removeActionManager(o);
  29191. });
  29192. this.textures.forEach(function (o) {
  29193. _this.scene.removeTexture(o);
  29194. });
  29195. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29196. var component = _a[_i];
  29197. component.removeFromContainer(this.scene);
  29198. }
  29199. };
  29200. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29201. if (!sourceAssets) {
  29202. return;
  29203. }
  29204. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29205. var asset = sourceAssets_1[_i];
  29206. var move = true;
  29207. if (keepAssets) {
  29208. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29209. var keepAsset = keepAssets_1[_a];
  29210. if (asset === keepAsset) {
  29211. move = false;
  29212. break;
  29213. }
  29214. }
  29215. }
  29216. if (move) {
  29217. targetAssets.push(asset);
  29218. }
  29219. }
  29220. };
  29221. /**
  29222. * Removes all the assets contained in the scene and adds them to the container.
  29223. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29224. */
  29225. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29226. if (keepAssets === undefined) {
  29227. keepAssets = new KeepAssets();
  29228. }
  29229. for (var key in this) {
  29230. if (this.hasOwnProperty(key)) {
  29231. this[key] = this[key] || [];
  29232. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29233. }
  29234. }
  29235. this.removeAllFromScene();
  29236. };
  29237. /**
  29238. * 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.
  29239. * @returns the root mesh
  29240. */
  29241. AssetContainer.prototype.createRootMesh = function () {
  29242. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29243. this.meshes.forEach(function (m) {
  29244. if (!m.parent) {
  29245. rootMesh.addChild(m);
  29246. }
  29247. });
  29248. this.meshes.unshift(rootMesh);
  29249. return rootMesh;
  29250. };
  29251. return AssetContainer;
  29252. }(BABYLON.AbstractScene));
  29253. BABYLON.AssetContainer = AssetContainer;
  29254. })(BABYLON || (BABYLON = {}));
  29255. //# sourceMappingURL=babylon.assetContainer.js.map
  29256. var BABYLON;
  29257. (function (BABYLON) {
  29258. var Buffer = /** @class */ (function () {
  29259. /**
  29260. * Constructor
  29261. * @param engine the engine
  29262. * @param data the data to use for this buffer
  29263. * @param updatable whether the data is updatable
  29264. * @param stride the stride (optional)
  29265. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29266. * @param instanced whether the buffer is instanced (optional)
  29267. * @param useBytes set to true if the stride in in bytes (optional)
  29268. */
  29269. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29270. if (stride === void 0) { stride = 0; }
  29271. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29272. if (instanced === void 0) { instanced = false; }
  29273. if (useBytes === void 0) { useBytes = false; }
  29274. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29275. this._engine = engine.getScene().getEngine();
  29276. }
  29277. else {
  29278. this._engine = engine;
  29279. }
  29280. this._updatable = updatable;
  29281. this._instanced = instanced;
  29282. this._data = data;
  29283. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29284. if (!postponeInternalCreation) { // by default
  29285. this.create();
  29286. }
  29287. }
  29288. /**
  29289. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29290. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29291. * @param offset defines offset in the buffer (0 by default)
  29292. * @param size defines the size in floats of attributes (position is 3 for instance)
  29293. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29294. * @param instanced defines if the vertex buffer contains indexed data
  29295. * @param useBytes defines if the offset and stride are in bytes
  29296. * @returns the new vertex buffer
  29297. */
  29298. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29299. if (useBytes === void 0) { useBytes = false; }
  29300. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29301. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29302. // a lot of these parameters are ignored as they are overriden by the buffer
  29303. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29304. };
  29305. // Properties
  29306. Buffer.prototype.isUpdatable = function () {
  29307. return this._updatable;
  29308. };
  29309. Buffer.prototype.getData = function () {
  29310. return this._data;
  29311. };
  29312. Buffer.prototype.getBuffer = function () {
  29313. return this._buffer;
  29314. };
  29315. /**
  29316. * Gets the stride in float32 units (i.e. byte stride / 4).
  29317. * May not be an integer if the byte stride is not divisible by 4.
  29318. * DEPRECATED. Use byteStride instead.
  29319. * @returns the stride in float32 units
  29320. */
  29321. Buffer.prototype.getStrideSize = function () {
  29322. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29323. };
  29324. // Methods
  29325. Buffer.prototype.create = function (data) {
  29326. if (data === void 0) { data = null; }
  29327. if (!data && this._buffer) {
  29328. return; // nothing to do
  29329. }
  29330. data = data || this._data;
  29331. if (!data) {
  29332. return;
  29333. }
  29334. if (!this._buffer) { // create buffer
  29335. if (this._updatable) {
  29336. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29337. this._data = data;
  29338. }
  29339. else {
  29340. this._buffer = this._engine.createVertexBuffer(data);
  29341. }
  29342. }
  29343. else if (this._updatable) { // update buffer
  29344. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29345. this._data = data;
  29346. }
  29347. };
  29348. /** @hidden */
  29349. Buffer.prototype._rebuild = function () {
  29350. this._buffer = null;
  29351. this.create(this._data);
  29352. };
  29353. Buffer.prototype.update = function (data) {
  29354. this.create(data);
  29355. };
  29356. /**
  29357. * Updates the data directly.
  29358. * @param data the new data
  29359. * @param offset the new offset
  29360. * @param vertexCount the vertex count (optional)
  29361. * @param useBytes set to true if the offset is in bytes
  29362. */
  29363. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29364. if (useBytes === void 0) { useBytes = false; }
  29365. if (!this._buffer) {
  29366. return;
  29367. }
  29368. if (this._updatable) { // update buffer
  29369. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29370. this._data = null;
  29371. }
  29372. };
  29373. Buffer.prototype.dispose = function () {
  29374. if (!this._buffer) {
  29375. return;
  29376. }
  29377. if (this._engine._releaseBuffer(this._buffer)) {
  29378. this._buffer = null;
  29379. }
  29380. };
  29381. return Buffer;
  29382. }());
  29383. BABYLON.Buffer = Buffer;
  29384. })(BABYLON || (BABYLON = {}));
  29385. //# sourceMappingURL=babylon.buffer.js.map
  29386. var BABYLON;
  29387. (function (BABYLON) {
  29388. var VertexBuffer = /** @class */ (function () {
  29389. /**
  29390. * Constructor
  29391. * @param engine the engine
  29392. * @param data the data to use for this vertex buffer
  29393. * @param kind the vertex buffer kind
  29394. * @param updatable whether the data is updatable
  29395. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29396. * @param stride the stride (optional)
  29397. * @param instanced whether the buffer is instanced (optional)
  29398. * @param offset the offset of the data (optional)
  29399. * @param size the number of components (optional)
  29400. * @param type the type of the component (optional)
  29401. * @param normalized whether the data contains normalized data (optional)
  29402. * @param useBytes set to true if stride and offset are in bytes (optional)
  29403. */
  29404. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29405. if (normalized === void 0) { normalized = false; }
  29406. if (useBytes === void 0) { useBytes = false; }
  29407. if (data instanceof BABYLON.Buffer) {
  29408. this._buffer = data;
  29409. this._ownsBuffer = false;
  29410. }
  29411. else {
  29412. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29413. this._ownsBuffer = true;
  29414. }
  29415. this._kind = kind;
  29416. if (type == undefined) {
  29417. var data_1 = this.getData();
  29418. this.type = VertexBuffer.FLOAT;
  29419. if (data_1 instanceof Int8Array)
  29420. this.type = VertexBuffer.BYTE;
  29421. else if (data_1 instanceof Uint8Array)
  29422. this.type = VertexBuffer.UNSIGNED_BYTE;
  29423. else if (data_1 instanceof Int16Array)
  29424. this.type = VertexBuffer.SHORT;
  29425. else if (data_1 instanceof Uint16Array)
  29426. this.type = VertexBuffer.UNSIGNED_SHORT;
  29427. else if (data_1 instanceof Int32Array)
  29428. this.type = VertexBuffer.INT;
  29429. else if (data_1 instanceof Uint32Array)
  29430. this.type = VertexBuffer.UNSIGNED_INT;
  29431. }
  29432. else {
  29433. this.type = type;
  29434. }
  29435. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29436. if (useBytes) {
  29437. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29438. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29439. this.byteOffset = offset || 0;
  29440. }
  29441. else {
  29442. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29443. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29444. this.byteOffset = (offset || 0) * typeByteLength;
  29445. }
  29446. this.normalized = normalized;
  29447. this._instanced = instanced !== undefined ? instanced : false;
  29448. this._instanceDivisor = instanced ? 1 : 0;
  29449. }
  29450. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29451. /**
  29452. * Gets or sets the instance divisor when in instanced mode
  29453. */
  29454. get: function () {
  29455. return this._instanceDivisor;
  29456. },
  29457. set: function (value) {
  29458. this._instanceDivisor = value;
  29459. if (value == 0) {
  29460. this._instanced = false;
  29461. }
  29462. else {
  29463. this._instanced = true;
  29464. }
  29465. },
  29466. enumerable: true,
  29467. configurable: true
  29468. });
  29469. /** @hidden */
  29470. VertexBuffer.prototype._rebuild = function () {
  29471. if (!this._buffer) {
  29472. return;
  29473. }
  29474. this._buffer._rebuild();
  29475. };
  29476. /**
  29477. * Returns the kind of the VertexBuffer (string).
  29478. */
  29479. VertexBuffer.prototype.getKind = function () {
  29480. return this._kind;
  29481. };
  29482. // Properties
  29483. /**
  29484. * Boolean : is the VertexBuffer updatable ?
  29485. */
  29486. VertexBuffer.prototype.isUpdatable = function () {
  29487. return this._buffer.isUpdatable();
  29488. };
  29489. /**
  29490. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29491. */
  29492. VertexBuffer.prototype.getData = function () {
  29493. return this._buffer.getData();
  29494. };
  29495. /**
  29496. * Returns the WebGLBuffer associated to the VertexBuffer.
  29497. */
  29498. VertexBuffer.prototype.getBuffer = function () {
  29499. return this._buffer.getBuffer();
  29500. };
  29501. /**
  29502. * Returns the stride as a multiple of the type byte length.
  29503. * DEPRECATED. Use byteStride instead.
  29504. */
  29505. VertexBuffer.prototype.getStrideSize = function () {
  29506. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29507. };
  29508. /**
  29509. * Returns the offset as a multiple of the type byte length.
  29510. * DEPRECATED. Use byteOffset instead.
  29511. */
  29512. VertexBuffer.prototype.getOffset = function () {
  29513. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29514. };
  29515. /**
  29516. * Returns the number of components per vertex attribute (integer).
  29517. */
  29518. VertexBuffer.prototype.getSize = function () {
  29519. return this._size;
  29520. };
  29521. /**
  29522. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29523. */
  29524. VertexBuffer.prototype.getIsInstanced = function () {
  29525. return this._instanced;
  29526. };
  29527. /**
  29528. * Returns the instancing divisor, zero for non-instanced (integer).
  29529. */
  29530. VertexBuffer.prototype.getInstanceDivisor = function () {
  29531. return this._instanceDivisor;
  29532. };
  29533. // Methods
  29534. /**
  29535. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29536. * Returns the created WebGLBuffer.
  29537. */
  29538. VertexBuffer.prototype.create = function (data) {
  29539. return this._buffer.create(data);
  29540. };
  29541. /**
  29542. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29543. * This function will create a new buffer if the current one is not updatable
  29544. * Returns the updated WebGLBuffer.
  29545. */
  29546. VertexBuffer.prototype.update = function (data) {
  29547. return this._buffer.update(data);
  29548. };
  29549. /**
  29550. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29551. * Returns the directly updated WebGLBuffer.
  29552. * @param data the new data
  29553. * @param offset the new offset
  29554. * @param useBytes set to true if the offset is in bytes
  29555. */
  29556. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29557. if (useBytes === void 0) { useBytes = false; }
  29558. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29559. };
  29560. /**
  29561. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29562. */
  29563. VertexBuffer.prototype.dispose = function () {
  29564. if (this._ownsBuffer) {
  29565. this._buffer.dispose();
  29566. }
  29567. };
  29568. /**
  29569. * Enumerates each value of this vertex buffer as numbers.
  29570. * @param count the number of values to enumerate
  29571. * @param callback the callback function called for each value
  29572. */
  29573. VertexBuffer.prototype.forEach = function (count, callback) {
  29574. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29575. };
  29576. Object.defineProperty(VertexBuffer, "PositionKind", {
  29577. get: function () {
  29578. return VertexBuffer._PositionKind;
  29579. },
  29580. enumerable: true,
  29581. configurable: true
  29582. });
  29583. Object.defineProperty(VertexBuffer, "NormalKind", {
  29584. get: function () {
  29585. return VertexBuffer._NormalKind;
  29586. },
  29587. enumerable: true,
  29588. configurable: true
  29589. });
  29590. Object.defineProperty(VertexBuffer, "TangentKind", {
  29591. get: function () {
  29592. return VertexBuffer._TangentKind;
  29593. },
  29594. enumerable: true,
  29595. configurable: true
  29596. });
  29597. Object.defineProperty(VertexBuffer, "UVKind", {
  29598. get: function () {
  29599. return VertexBuffer._UVKind;
  29600. },
  29601. enumerable: true,
  29602. configurable: true
  29603. });
  29604. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29605. get: function () {
  29606. return VertexBuffer._UV2Kind;
  29607. },
  29608. enumerable: true,
  29609. configurable: true
  29610. });
  29611. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29612. get: function () {
  29613. return VertexBuffer._UV3Kind;
  29614. },
  29615. enumerable: true,
  29616. configurable: true
  29617. });
  29618. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29619. get: function () {
  29620. return VertexBuffer._UV4Kind;
  29621. },
  29622. enumerable: true,
  29623. configurable: true
  29624. });
  29625. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29626. get: function () {
  29627. return VertexBuffer._UV5Kind;
  29628. },
  29629. enumerable: true,
  29630. configurable: true
  29631. });
  29632. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29633. get: function () {
  29634. return VertexBuffer._UV6Kind;
  29635. },
  29636. enumerable: true,
  29637. configurable: true
  29638. });
  29639. Object.defineProperty(VertexBuffer, "ColorKind", {
  29640. get: function () {
  29641. return VertexBuffer._ColorKind;
  29642. },
  29643. enumerable: true,
  29644. configurable: true
  29645. });
  29646. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29647. get: function () {
  29648. return VertexBuffer._MatricesIndicesKind;
  29649. },
  29650. enumerable: true,
  29651. configurable: true
  29652. });
  29653. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29654. get: function () {
  29655. return VertexBuffer._MatricesWeightsKind;
  29656. },
  29657. enumerable: true,
  29658. configurable: true
  29659. });
  29660. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29661. get: function () {
  29662. return VertexBuffer._MatricesIndicesExtraKind;
  29663. },
  29664. enumerable: true,
  29665. configurable: true
  29666. });
  29667. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29668. get: function () {
  29669. return VertexBuffer._MatricesWeightsExtraKind;
  29670. },
  29671. enumerable: true,
  29672. configurable: true
  29673. });
  29674. /**
  29675. * Deduces the stride given a kind.
  29676. * @param kind The kind string to deduce
  29677. * @returns The deduced stride
  29678. */
  29679. VertexBuffer.DeduceStride = function (kind) {
  29680. switch (kind) {
  29681. case VertexBuffer.UVKind:
  29682. case VertexBuffer.UV2Kind:
  29683. case VertexBuffer.UV3Kind:
  29684. case VertexBuffer.UV4Kind:
  29685. case VertexBuffer.UV5Kind:
  29686. case VertexBuffer.UV6Kind:
  29687. return 2;
  29688. case VertexBuffer.NormalKind:
  29689. case VertexBuffer.PositionKind:
  29690. return 3;
  29691. case VertexBuffer.ColorKind:
  29692. case VertexBuffer.MatricesIndicesKind:
  29693. case VertexBuffer.MatricesIndicesExtraKind:
  29694. case VertexBuffer.MatricesWeightsKind:
  29695. case VertexBuffer.MatricesWeightsExtraKind:
  29696. case VertexBuffer.TangentKind:
  29697. return 4;
  29698. default:
  29699. throw new Error("Invalid kind '" + kind + "'");
  29700. }
  29701. };
  29702. /**
  29703. * Gets the byte length of the given type.
  29704. * @param type the type
  29705. * @returns the number of bytes
  29706. */
  29707. VertexBuffer.GetTypeByteLength = function (type) {
  29708. switch (type) {
  29709. case VertexBuffer.BYTE:
  29710. case VertexBuffer.UNSIGNED_BYTE:
  29711. return 1;
  29712. case VertexBuffer.SHORT:
  29713. case VertexBuffer.UNSIGNED_SHORT:
  29714. return 2;
  29715. case VertexBuffer.INT:
  29716. case VertexBuffer.FLOAT:
  29717. return 4;
  29718. default:
  29719. throw new Error("Invalid type '" + type + "'");
  29720. }
  29721. };
  29722. /**
  29723. * Enumerates each value of the given parameters as numbers.
  29724. * @param data the data to enumerate
  29725. * @param byteOffset the byte offset of the data
  29726. * @param byteStride the byte stride of the data
  29727. * @param componentCount the number of components per element
  29728. * @param componentType the type of the component
  29729. * @param count the total number of components
  29730. * @param normalized whether the data is normalized
  29731. * @param callback the callback function called for each value
  29732. */
  29733. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29734. if (data instanceof Array) {
  29735. var offset = byteOffset / 4;
  29736. var stride = byteStride / 4;
  29737. for (var index = 0; index < count; index += componentCount) {
  29738. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29739. callback(data[offset + componentIndex], index + componentIndex);
  29740. }
  29741. offset += stride;
  29742. }
  29743. }
  29744. else {
  29745. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29746. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29747. for (var index = 0; index < count; index += componentCount) {
  29748. var componentByteOffset = byteOffset;
  29749. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29750. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29751. callback(value, index + componentIndex);
  29752. componentByteOffset += componentByteLength;
  29753. }
  29754. byteOffset += byteStride;
  29755. }
  29756. }
  29757. };
  29758. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29759. switch (type) {
  29760. case VertexBuffer.BYTE: {
  29761. var value = dataView.getInt8(byteOffset);
  29762. if (normalized) {
  29763. value = Math.max(value / 127, -1);
  29764. }
  29765. return value;
  29766. }
  29767. case VertexBuffer.UNSIGNED_BYTE: {
  29768. var value = dataView.getUint8(byteOffset);
  29769. if (normalized) {
  29770. value = value / 255;
  29771. }
  29772. return value;
  29773. }
  29774. case VertexBuffer.SHORT: {
  29775. var value = dataView.getInt16(byteOffset, true);
  29776. if (normalized) {
  29777. value = Math.max(value / 16383, -1);
  29778. }
  29779. return value;
  29780. }
  29781. case VertexBuffer.UNSIGNED_SHORT: {
  29782. var value = dataView.getUint16(byteOffset, true);
  29783. if (normalized) {
  29784. value = value / 65535;
  29785. }
  29786. return value;
  29787. }
  29788. case VertexBuffer.FLOAT: {
  29789. return dataView.getFloat32(byteOffset, true);
  29790. }
  29791. default: {
  29792. throw new Error("Invalid component type " + type);
  29793. }
  29794. }
  29795. };
  29796. /**
  29797. * The byte type.
  29798. */
  29799. VertexBuffer.BYTE = 5120;
  29800. /**
  29801. * The unsigned byte type.
  29802. */
  29803. VertexBuffer.UNSIGNED_BYTE = 5121;
  29804. /**
  29805. * The short type.
  29806. */
  29807. VertexBuffer.SHORT = 5122;
  29808. /**
  29809. * The unsigned short type.
  29810. */
  29811. VertexBuffer.UNSIGNED_SHORT = 5123;
  29812. /**
  29813. * The integer type.
  29814. */
  29815. VertexBuffer.INT = 5124;
  29816. /**
  29817. * The unsigned integer type.
  29818. */
  29819. VertexBuffer.UNSIGNED_INT = 5125;
  29820. /**
  29821. * The float type.
  29822. */
  29823. VertexBuffer.FLOAT = 5126;
  29824. // Enums
  29825. VertexBuffer._PositionKind = "position";
  29826. VertexBuffer._NormalKind = "normal";
  29827. VertexBuffer._TangentKind = "tangent";
  29828. VertexBuffer._UVKind = "uv";
  29829. VertexBuffer._UV2Kind = "uv2";
  29830. VertexBuffer._UV3Kind = "uv3";
  29831. VertexBuffer._UV4Kind = "uv4";
  29832. VertexBuffer._UV5Kind = "uv5";
  29833. VertexBuffer._UV6Kind = "uv6";
  29834. VertexBuffer._ColorKind = "color";
  29835. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29836. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29837. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29838. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29839. return VertexBuffer;
  29840. }());
  29841. BABYLON.VertexBuffer = VertexBuffer;
  29842. })(BABYLON || (BABYLON = {}));
  29843. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29844. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29845. var BABYLON;
  29846. (function (BABYLON) {
  29847. /**
  29848. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29849. */
  29850. var DummyInternalTextureTracker = /** @class */ (function () {
  29851. function DummyInternalTextureTracker() {
  29852. /**
  29853. * Gets or set the previous tracker in the list
  29854. */
  29855. this.previous = null;
  29856. /**
  29857. * Gets or set the next tracker in the list
  29858. */
  29859. this.next = null;
  29860. }
  29861. return DummyInternalTextureTracker;
  29862. }());
  29863. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29864. })(BABYLON || (BABYLON = {}));
  29865. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29866. var BABYLON;
  29867. (function (BABYLON) {
  29868. /**
  29869. * Class used to store data associated with WebGL texture data for the engine
  29870. * This class should not be used directly
  29871. */
  29872. var InternalTexture = /** @class */ (function () {
  29873. /**
  29874. * Creates a new InternalTexture
  29875. * @param engine defines the engine to use
  29876. * @param dataSource defines the type of data that will be used
  29877. */
  29878. function InternalTexture(engine, dataSource) {
  29879. /**
  29880. * Observable called when the texture is loaded
  29881. */
  29882. this.onLoadedObservable = new BABYLON.Observable();
  29883. /**
  29884. * Gets or set the previous tracker in the list
  29885. */
  29886. this.previous = null;
  29887. /**
  29888. * Gets or set the next tracker in the list
  29889. */
  29890. this.next = null;
  29891. // Private
  29892. /** @hidden */
  29893. this._initialSlot = -1;
  29894. /** @hidden */
  29895. this._designatedSlot = -1;
  29896. /** @hidden */
  29897. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29898. /** @hidden */
  29899. this._comparisonFunction = 0;
  29900. /** @hidden */
  29901. this._sphericalPolynomial = null;
  29902. /** @hidden */
  29903. this._lodGenerationScale = 0;
  29904. /** @hidden */
  29905. this._lodGenerationOffset = 0;
  29906. /** @hidden */
  29907. this._isRGBD = false;
  29908. /** @hidden */
  29909. this._references = 1;
  29910. this._engine = engine;
  29911. this._dataSource = dataSource;
  29912. this._webGLTexture = engine._createTexture();
  29913. }
  29914. /**
  29915. * Gets the Engine the texture belongs to.
  29916. * @returns The babylon engine
  29917. */
  29918. InternalTexture.prototype.getEngine = function () {
  29919. return this._engine;
  29920. };
  29921. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29922. /**
  29923. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29924. */
  29925. get: function () {
  29926. return this._dataSource;
  29927. },
  29928. enumerable: true,
  29929. configurable: true
  29930. });
  29931. /**
  29932. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29933. */
  29934. InternalTexture.prototype.incrementReferences = function () {
  29935. this._references++;
  29936. };
  29937. /**
  29938. * Change the size of the texture (not the size of the content)
  29939. * @param width defines the new width
  29940. * @param height defines the new height
  29941. * @param depth defines the new depth (1 by default)
  29942. */
  29943. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29944. if (depth === void 0) { depth = 1; }
  29945. this.width = width;
  29946. this.height = height;
  29947. this.depth = depth;
  29948. this.baseWidth = width;
  29949. this.baseHeight = height;
  29950. this.baseDepth = depth;
  29951. this._size = width * height * depth;
  29952. };
  29953. /** @hidden */
  29954. InternalTexture.prototype._rebuild = function () {
  29955. var _this = this;
  29956. var proxy;
  29957. this.isReady = false;
  29958. this._cachedCoordinatesMode = null;
  29959. this._cachedWrapU = null;
  29960. this._cachedWrapV = null;
  29961. this._cachedAnisotropicFilteringLevel = null;
  29962. switch (this._dataSource) {
  29963. case InternalTexture.DATASOURCE_TEMP:
  29964. return;
  29965. case InternalTexture.DATASOURCE_URL:
  29966. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29967. _this.isReady = true;
  29968. }, null, this._buffer, undefined, this.format);
  29969. proxy._swapAndDie(this);
  29970. return;
  29971. case InternalTexture.DATASOURCE_RAW:
  29972. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29973. proxy._swapAndDie(this);
  29974. this.isReady = true;
  29975. return;
  29976. case InternalTexture.DATASOURCE_RAW3D:
  29977. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29978. proxy._swapAndDie(this);
  29979. this.isReady = true;
  29980. return;
  29981. case InternalTexture.DATASOURCE_DYNAMIC:
  29982. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29983. proxy._swapAndDie(this);
  29984. // The engine will make sure to update content so no need to flag it as isReady = true
  29985. return;
  29986. case InternalTexture.DATASOURCE_RENDERTARGET:
  29987. var options = new BABYLON.RenderTargetCreationOptions();
  29988. options.generateDepthBuffer = this._generateDepthBuffer;
  29989. options.generateMipMaps = this.generateMipMaps;
  29990. options.generateStencilBuffer = this._generateStencilBuffer;
  29991. options.samplingMode = this.samplingMode;
  29992. options.type = this.type;
  29993. if (this.isCube) {
  29994. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29995. }
  29996. else {
  29997. var size = {
  29998. width: this.width,
  29999. height: this.height
  30000. };
  30001. proxy = this._engine.createRenderTargetTexture(size, options);
  30002. }
  30003. proxy._swapAndDie(this);
  30004. this.isReady = true;
  30005. return;
  30006. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30007. var depthTextureOptions = {
  30008. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30009. comparisonFunction: this._comparisonFunction,
  30010. generateStencil: this._generateStencilBuffer,
  30011. isCube: this.isCube
  30012. };
  30013. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30014. proxy._swapAndDie(this);
  30015. this.isReady = true;
  30016. return;
  30017. case InternalTexture.DATASOURCE_CUBE:
  30018. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30019. _this.isReady = true;
  30020. }, null, this.format, this._extension);
  30021. proxy._swapAndDie(this);
  30022. return;
  30023. case InternalTexture.DATASOURCE_CUBERAW:
  30024. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30025. proxy._swapAndDie(this);
  30026. this.isReady = true;
  30027. return;
  30028. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30029. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30030. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30031. _this.isReady = true;
  30032. });
  30033. proxy._swapAndDie(this);
  30034. return;
  30035. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30036. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30037. if (proxy) {
  30038. proxy._swapAndDie(_this);
  30039. }
  30040. _this.isReady = true;
  30041. }, null, this.format, this._extension);
  30042. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30043. return;
  30044. }
  30045. };
  30046. /** @hidden */
  30047. InternalTexture.prototype._swapAndDie = function (target) {
  30048. target._webGLTexture = this._webGLTexture;
  30049. if (this._framebuffer) {
  30050. target._framebuffer = this._framebuffer;
  30051. }
  30052. if (this._depthStencilBuffer) {
  30053. target._depthStencilBuffer = this._depthStencilBuffer;
  30054. }
  30055. if (this._lodTextureHigh) {
  30056. if (target._lodTextureHigh) {
  30057. target._lodTextureHigh.dispose();
  30058. }
  30059. target._lodTextureHigh = this._lodTextureHigh;
  30060. }
  30061. if (this._lodTextureMid) {
  30062. if (target._lodTextureMid) {
  30063. target._lodTextureMid.dispose();
  30064. }
  30065. target._lodTextureMid = this._lodTextureMid;
  30066. }
  30067. if (this._lodTextureLow) {
  30068. if (target._lodTextureLow) {
  30069. target._lodTextureLow.dispose();
  30070. }
  30071. target._lodTextureLow = this._lodTextureLow;
  30072. }
  30073. var cache = this._engine.getLoadedTexturesCache();
  30074. var index = cache.indexOf(this);
  30075. if (index !== -1) {
  30076. cache.splice(index, 1);
  30077. }
  30078. };
  30079. /**
  30080. * Dispose the current allocated resources
  30081. */
  30082. InternalTexture.prototype.dispose = function () {
  30083. if (!this._webGLTexture) {
  30084. return;
  30085. }
  30086. this._references--;
  30087. if (this._references === 0) {
  30088. this._engine._releaseTexture(this);
  30089. this._webGLTexture = null;
  30090. this.previous = null;
  30091. this.next = null;
  30092. }
  30093. };
  30094. /**
  30095. * The source of the texture data is unknown
  30096. */
  30097. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30098. /**
  30099. * Texture data comes from an URL
  30100. */
  30101. InternalTexture.DATASOURCE_URL = 1;
  30102. /**
  30103. * Texture data is only used for temporary storage
  30104. */
  30105. InternalTexture.DATASOURCE_TEMP = 2;
  30106. /**
  30107. * Texture data comes from raw data (ArrayBuffer)
  30108. */
  30109. InternalTexture.DATASOURCE_RAW = 3;
  30110. /**
  30111. * Texture content is dynamic (video or dynamic texture)
  30112. */
  30113. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30114. /**
  30115. * Texture content is generated by rendering to it
  30116. */
  30117. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30118. /**
  30119. * Texture content is part of a multi render target process
  30120. */
  30121. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30122. /**
  30123. * Texture data comes from a cube data file
  30124. */
  30125. InternalTexture.DATASOURCE_CUBE = 7;
  30126. /**
  30127. * Texture data comes from a raw cube data
  30128. */
  30129. InternalTexture.DATASOURCE_CUBERAW = 8;
  30130. /**
  30131. * Texture data come from a prefiltered cube data file
  30132. */
  30133. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30134. /**
  30135. * Texture content is raw 3D data
  30136. */
  30137. InternalTexture.DATASOURCE_RAW3D = 10;
  30138. /**
  30139. * Texture content is a depth texture
  30140. */
  30141. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30142. /**
  30143. * Texture data comes from a raw cube data encoded with RGBD
  30144. */
  30145. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30146. return InternalTexture;
  30147. }());
  30148. BABYLON.InternalTexture = InternalTexture;
  30149. })(BABYLON || (BABYLON = {}));
  30150. //# sourceMappingURL=babylon.internalTexture.js.map
  30151. var BABYLON;
  30152. (function (BABYLON) {
  30153. var BaseTexture = /** @class */ (function () {
  30154. function BaseTexture(scene) {
  30155. this._hasAlpha = false;
  30156. this.getAlphaFromRGB = false;
  30157. this.level = 1;
  30158. this.coordinatesIndex = 0;
  30159. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30160. /**
  30161. * | Value | Type | Description |
  30162. * | ----- | ------------------ | ----------- |
  30163. * | 0 | CLAMP_ADDRESSMODE | |
  30164. * | 1 | WRAP_ADDRESSMODE | |
  30165. * | 2 | MIRROR_ADDRESSMODE | |
  30166. */
  30167. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30168. /**
  30169. * | Value | Type | Description |
  30170. * | ----- | ------------------ | ----------- |
  30171. * | 0 | CLAMP_ADDRESSMODE | |
  30172. * | 1 | WRAP_ADDRESSMODE | |
  30173. * | 2 | MIRROR_ADDRESSMODE | |
  30174. */
  30175. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30176. /**
  30177. * | Value | Type | Description |
  30178. * | ----- | ------------------ | ----------- |
  30179. * | 0 | CLAMP_ADDRESSMODE | |
  30180. * | 1 | WRAP_ADDRESSMODE | |
  30181. * | 2 | MIRROR_ADDRESSMODE | |
  30182. */
  30183. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30184. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30185. this.isCube = false;
  30186. this.is3D = false;
  30187. this.gammaSpace = true;
  30188. this.invertZ = false;
  30189. this.lodLevelInAlpha = false;
  30190. this.isRenderTarget = false;
  30191. this.animations = new Array();
  30192. /**
  30193. * An event triggered when the texture is disposed.
  30194. */
  30195. this.onDisposeObservable = new BABYLON.Observable();
  30196. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30197. this._cachedSize = BABYLON.Size.Zero();
  30198. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30199. if (this._scene) {
  30200. this._scene.textures.push(this);
  30201. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30202. }
  30203. this._uid = null;
  30204. }
  30205. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30206. get: function () {
  30207. return this._hasAlpha;
  30208. },
  30209. set: function (value) {
  30210. if (this._hasAlpha === value) {
  30211. return;
  30212. }
  30213. this._hasAlpha = value;
  30214. if (this._scene) {
  30215. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30216. }
  30217. },
  30218. enumerable: true,
  30219. configurable: true
  30220. });
  30221. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30222. get: function () {
  30223. return this._coordinatesMode;
  30224. },
  30225. /**
  30226. * How a texture is mapped.
  30227. *
  30228. * | Value | Type | Description |
  30229. * | ----- | ----------------------------------- | ----------- |
  30230. * | 0 | EXPLICIT_MODE | |
  30231. * | 1 | SPHERICAL_MODE | |
  30232. * | 2 | PLANAR_MODE | |
  30233. * | 3 | CUBIC_MODE | |
  30234. * | 4 | PROJECTION_MODE | |
  30235. * | 5 | SKYBOX_MODE | |
  30236. * | 6 | INVCUBIC_MODE | |
  30237. * | 7 | EQUIRECTANGULAR_MODE | |
  30238. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30239. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30240. */
  30241. set: function (value) {
  30242. if (this._coordinatesMode === value) {
  30243. return;
  30244. }
  30245. this._coordinatesMode = value;
  30246. if (this._scene) {
  30247. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30248. }
  30249. },
  30250. enumerable: true,
  30251. configurable: true
  30252. });
  30253. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30254. /**
  30255. * Gets whether or not the texture contains RGBD data.
  30256. */
  30257. get: function () {
  30258. return this._texture != null && this._texture._isRGBD;
  30259. },
  30260. enumerable: true,
  30261. configurable: true
  30262. });
  30263. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30264. get: function () {
  30265. if (this._texture)
  30266. return this._texture._lodGenerationOffset;
  30267. return 0.0;
  30268. },
  30269. set: function (value) {
  30270. if (this._texture)
  30271. this._texture._lodGenerationOffset = value;
  30272. },
  30273. enumerable: true,
  30274. configurable: true
  30275. });
  30276. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30277. get: function () {
  30278. if (this._texture)
  30279. return this._texture._lodGenerationScale;
  30280. return 0.0;
  30281. },
  30282. set: function (value) {
  30283. if (this._texture)
  30284. this._texture._lodGenerationScale = value;
  30285. },
  30286. enumerable: true,
  30287. configurable: true
  30288. });
  30289. Object.defineProperty(BaseTexture.prototype, "uid", {
  30290. get: function () {
  30291. if (!this._uid) {
  30292. this._uid = BABYLON.Tools.RandomId();
  30293. }
  30294. return this._uid;
  30295. },
  30296. enumerable: true,
  30297. configurable: true
  30298. });
  30299. BaseTexture.prototype.toString = function () {
  30300. return this.name;
  30301. };
  30302. BaseTexture.prototype.getClassName = function () {
  30303. return "BaseTexture";
  30304. };
  30305. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30306. set: function (callback) {
  30307. if (this._onDisposeObserver) {
  30308. this.onDisposeObservable.remove(this._onDisposeObserver);
  30309. }
  30310. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30311. },
  30312. enumerable: true,
  30313. configurable: true
  30314. });
  30315. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30316. get: function () {
  30317. return true;
  30318. },
  30319. enumerable: true,
  30320. configurable: true
  30321. });
  30322. BaseTexture.prototype.getScene = function () {
  30323. return this._scene;
  30324. };
  30325. BaseTexture.prototype.getTextureMatrix = function () {
  30326. return BABYLON.Matrix.IdentityReadOnly;
  30327. };
  30328. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30329. return BABYLON.Matrix.IdentityReadOnly;
  30330. };
  30331. BaseTexture.prototype.getInternalTexture = function () {
  30332. return this._texture;
  30333. };
  30334. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30335. return !this.isBlocking || this.isReady();
  30336. };
  30337. BaseTexture.prototype.isReady = function () {
  30338. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30339. this.delayLoad();
  30340. return false;
  30341. }
  30342. if (this._texture) {
  30343. return this._texture.isReady;
  30344. }
  30345. return false;
  30346. };
  30347. BaseTexture.prototype.getSize = function () {
  30348. if (this._texture) {
  30349. if (this._texture.width) {
  30350. this._cachedSize.width = this._texture.width;
  30351. this._cachedSize.height = this._texture.height;
  30352. return this._cachedSize;
  30353. }
  30354. if (this._texture._size) {
  30355. this._cachedSize.width = this._texture._size;
  30356. this._cachedSize.height = this._texture._size;
  30357. return this._cachedSize;
  30358. }
  30359. }
  30360. return this._cachedSize;
  30361. };
  30362. BaseTexture.prototype.getBaseSize = function () {
  30363. if (!this.isReady() || !this._texture)
  30364. return BABYLON.Size.Zero();
  30365. if (this._texture._size) {
  30366. return new BABYLON.Size(this._texture._size, this._texture._size);
  30367. }
  30368. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30369. };
  30370. BaseTexture.prototype.scale = function (ratio) {
  30371. };
  30372. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30373. get: function () {
  30374. return false;
  30375. },
  30376. enumerable: true,
  30377. configurable: true
  30378. });
  30379. /** @hidden */
  30380. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30381. if (!this._scene) {
  30382. return null;
  30383. }
  30384. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30385. for (var index = 0; index < texturesCache.length; index++) {
  30386. var texturesCacheEntry = texturesCache[index];
  30387. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30388. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30389. texturesCacheEntry.incrementReferences();
  30390. return texturesCacheEntry;
  30391. }
  30392. }
  30393. }
  30394. return null;
  30395. };
  30396. /** @hidden */
  30397. BaseTexture.prototype._rebuild = function () {
  30398. };
  30399. BaseTexture.prototype.delayLoad = function () {
  30400. };
  30401. BaseTexture.prototype.clone = function () {
  30402. return null;
  30403. };
  30404. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30405. get: function () {
  30406. if (!this._texture) {
  30407. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30408. }
  30409. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30410. },
  30411. enumerable: true,
  30412. configurable: true
  30413. });
  30414. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30415. get: function () {
  30416. if (!this._texture) {
  30417. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30418. }
  30419. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30420. },
  30421. enumerable: true,
  30422. configurable: true
  30423. });
  30424. /**
  30425. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30426. * This will returns an RGBA array buffer containing either in values (0-255) or
  30427. * float values (0-1) depending of the underlying buffer type.
  30428. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30429. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30430. * @param buffer defines a user defined buffer to fill with data (can be null)
  30431. * @returns The Array buffer containing the pixels data.
  30432. */
  30433. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30434. if (faceIndex === void 0) { faceIndex = 0; }
  30435. if (level === void 0) { level = 0; }
  30436. if (buffer === void 0) { buffer = null; }
  30437. if (!this._texture) {
  30438. return null;
  30439. }
  30440. var size = this.getSize();
  30441. var width = size.width;
  30442. var height = size.height;
  30443. var scene = this.getScene();
  30444. if (!scene) {
  30445. return null;
  30446. }
  30447. var engine = scene.getEngine();
  30448. if (level != 0) {
  30449. width = width / Math.pow(2, level);
  30450. height = height / Math.pow(2, level);
  30451. width = Math.round(width);
  30452. height = Math.round(height);
  30453. }
  30454. if (this._texture.isCube) {
  30455. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30456. }
  30457. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30458. };
  30459. BaseTexture.prototype.releaseInternalTexture = function () {
  30460. if (this._texture) {
  30461. this._texture.dispose();
  30462. this._texture = null;
  30463. }
  30464. };
  30465. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30466. get: function () {
  30467. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30468. return null;
  30469. }
  30470. if (!this._texture._sphericalPolynomial) {
  30471. this._texture._sphericalPolynomial =
  30472. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30473. }
  30474. return this._texture._sphericalPolynomial;
  30475. },
  30476. set: function (value) {
  30477. if (this._texture) {
  30478. this._texture._sphericalPolynomial = value;
  30479. }
  30480. },
  30481. enumerable: true,
  30482. configurable: true
  30483. });
  30484. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30485. get: function () {
  30486. if (this._texture) {
  30487. return this._texture._lodTextureHigh;
  30488. }
  30489. return null;
  30490. },
  30491. enumerable: true,
  30492. configurable: true
  30493. });
  30494. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30495. get: function () {
  30496. if (this._texture) {
  30497. return this._texture._lodTextureMid;
  30498. }
  30499. return null;
  30500. },
  30501. enumerable: true,
  30502. configurable: true
  30503. });
  30504. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30505. get: function () {
  30506. if (this._texture) {
  30507. return this._texture._lodTextureLow;
  30508. }
  30509. return null;
  30510. },
  30511. enumerable: true,
  30512. configurable: true
  30513. });
  30514. BaseTexture.prototype.dispose = function () {
  30515. if (!this._scene) {
  30516. return;
  30517. }
  30518. // Animations
  30519. this._scene.stopAnimation(this);
  30520. // Remove from scene
  30521. this._scene._removePendingData(this);
  30522. var index = this._scene.textures.indexOf(this);
  30523. if (index >= 0) {
  30524. this._scene.textures.splice(index, 1);
  30525. }
  30526. this._scene.onTextureRemovedObservable.notifyObservers(this);
  30527. if (this._texture === undefined) {
  30528. return;
  30529. }
  30530. // Release
  30531. this.releaseInternalTexture();
  30532. // Callback
  30533. this.onDisposeObservable.notifyObservers(this);
  30534. this.onDisposeObservable.clear();
  30535. };
  30536. BaseTexture.prototype.serialize = function () {
  30537. if (!this.name) {
  30538. return null;
  30539. }
  30540. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30541. // Animations
  30542. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30543. return serializationObject;
  30544. };
  30545. BaseTexture.WhenAllReady = function (textures, callback) {
  30546. var numRemaining = textures.length;
  30547. if (numRemaining === 0) {
  30548. callback();
  30549. return;
  30550. }
  30551. var _loop_1 = function () {
  30552. texture = textures[i];
  30553. if (texture.isReady()) {
  30554. if (--numRemaining === 0) {
  30555. callback();
  30556. }
  30557. }
  30558. else {
  30559. onLoadObservable = texture.onLoadObservable;
  30560. var onLoadCallback_1 = function () {
  30561. onLoadObservable.removeCallback(onLoadCallback_1);
  30562. if (--numRemaining === 0) {
  30563. callback();
  30564. }
  30565. };
  30566. onLoadObservable.add(onLoadCallback_1);
  30567. }
  30568. };
  30569. var texture, onLoadObservable;
  30570. for (var i = 0; i < textures.length; i++) {
  30571. _loop_1();
  30572. }
  30573. };
  30574. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30575. __decorate([
  30576. BABYLON.serialize()
  30577. ], BaseTexture.prototype, "name", void 0);
  30578. __decorate([
  30579. BABYLON.serialize("hasAlpha")
  30580. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30581. __decorate([
  30582. BABYLON.serialize()
  30583. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30584. __decorate([
  30585. BABYLON.serialize()
  30586. ], BaseTexture.prototype, "level", void 0);
  30587. __decorate([
  30588. BABYLON.serialize()
  30589. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30590. __decorate([
  30591. BABYLON.serialize("coordinatesMode")
  30592. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30593. __decorate([
  30594. BABYLON.serialize()
  30595. ], BaseTexture.prototype, "wrapU", void 0);
  30596. __decorate([
  30597. BABYLON.serialize()
  30598. ], BaseTexture.prototype, "wrapV", void 0);
  30599. __decorate([
  30600. BABYLON.serialize()
  30601. ], BaseTexture.prototype, "wrapR", void 0);
  30602. __decorate([
  30603. BABYLON.serialize()
  30604. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30605. __decorate([
  30606. BABYLON.serialize()
  30607. ], BaseTexture.prototype, "isCube", void 0);
  30608. __decorate([
  30609. BABYLON.serialize()
  30610. ], BaseTexture.prototype, "is3D", void 0);
  30611. __decorate([
  30612. BABYLON.serialize()
  30613. ], BaseTexture.prototype, "gammaSpace", void 0);
  30614. __decorate([
  30615. BABYLON.serialize()
  30616. ], BaseTexture.prototype, "invertZ", void 0);
  30617. __decorate([
  30618. BABYLON.serialize()
  30619. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30620. __decorate([
  30621. BABYLON.serialize()
  30622. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30623. __decorate([
  30624. BABYLON.serialize()
  30625. ], BaseTexture.prototype, "lodGenerationScale", null);
  30626. __decorate([
  30627. BABYLON.serialize()
  30628. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30629. return BaseTexture;
  30630. }());
  30631. BABYLON.BaseTexture = BaseTexture;
  30632. })(BABYLON || (BABYLON = {}));
  30633. //# sourceMappingURL=babylon.baseTexture.js.map
  30634. var BABYLON;
  30635. (function (BABYLON) {
  30636. var Texture = /** @class */ (function (_super) {
  30637. __extends(Texture, _super);
  30638. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30639. if (noMipmap === void 0) { noMipmap = false; }
  30640. if (invertY === void 0) { invertY = true; }
  30641. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30642. if (onLoad === void 0) { onLoad = null; }
  30643. if (onError === void 0) { onError = null; }
  30644. if (buffer === void 0) { buffer = null; }
  30645. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30646. var _this = _super.call(this, scene) || this;
  30647. _this.uOffset = 0;
  30648. _this.vOffset = 0;
  30649. _this.uScale = 1.0;
  30650. _this.vScale = 1.0;
  30651. _this.uAng = 0;
  30652. _this.vAng = 0;
  30653. _this.wAng = 0;
  30654. /**
  30655. * Defines the center of rotation (U)
  30656. */
  30657. _this.uRotationCenter = 0.5;
  30658. /**
  30659. * Defines the center of rotation (V)
  30660. */
  30661. _this.vRotationCenter = 0.5;
  30662. /**
  30663. * Defines the center of rotation (W)
  30664. */
  30665. _this.wRotationCenter = 0.5;
  30666. _this._isBlocking = true;
  30667. _this.name = url || "";
  30668. _this.url = url;
  30669. _this._noMipmap = noMipmap;
  30670. _this._invertY = invertY;
  30671. _this._samplingMode = samplingMode;
  30672. _this._buffer = buffer;
  30673. _this._deleteBuffer = deleteBuffer;
  30674. if (format) {
  30675. _this._format = format;
  30676. }
  30677. scene = _this.getScene();
  30678. if (!scene) {
  30679. return _this;
  30680. }
  30681. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30682. var load = function () {
  30683. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30684. _this.onLoadObservable.notifyObservers(_this);
  30685. }
  30686. if (onLoad) {
  30687. onLoad();
  30688. }
  30689. if (!_this.isBlocking && scene) {
  30690. scene.resetCachedMaterial();
  30691. }
  30692. };
  30693. if (!_this.url) {
  30694. _this._delayedOnLoad = load;
  30695. _this._delayedOnError = onError;
  30696. return _this;
  30697. }
  30698. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30699. if (!_this._texture) {
  30700. if (!scene.useDelayedTextureLoading) {
  30701. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30702. if (deleteBuffer) {
  30703. delete _this._buffer;
  30704. }
  30705. }
  30706. else {
  30707. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30708. _this._delayedOnLoad = load;
  30709. _this._delayedOnError = onError;
  30710. }
  30711. }
  30712. else {
  30713. if (_this._texture.isReady) {
  30714. BABYLON.Tools.SetImmediate(function () { return load(); });
  30715. }
  30716. else {
  30717. _this._texture.onLoadedObservable.add(load);
  30718. }
  30719. }
  30720. return _this;
  30721. }
  30722. Object.defineProperty(Texture.prototype, "noMipmap", {
  30723. get: function () {
  30724. return this._noMipmap;
  30725. },
  30726. enumerable: true,
  30727. configurable: true
  30728. });
  30729. Object.defineProperty(Texture.prototype, "isBlocking", {
  30730. get: function () {
  30731. return this._isBlocking;
  30732. },
  30733. set: function (value) {
  30734. this._isBlocking = value;
  30735. },
  30736. enumerable: true,
  30737. configurable: true
  30738. });
  30739. Object.defineProperty(Texture.prototype, "samplingMode", {
  30740. get: function () {
  30741. return this._samplingMode;
  30742. },
  30743. enumerable: true,
  30744. configurable: true
  30745. });
  30746. /**
  30747. * Update the url (and optional buffer) of this texture if url was null during construction.
  30748. * @param url the url of the texture
  30749. * @param buffer the buffer of the texture (defaults to null)
  30750. */
  30751. Texture.prototype.updateURL = function (url, buffer) {
  30752. if (buffer === void 0) { buffer = null; }
  30753. if (this.url) {
  30754. throw new Error("URL is already set");
  30755. }
  30756. this.url = url;
  30757. this._buffer = buffer;
  30758. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30759. this.delayLoad();
  30760. };
  30761. Texture.prototype.delayLoad = function () {
  30762. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30763. return;
  30764. }
  30765. var scene = this.getScene();
  30766. if (!scene) {
  30767. return;
  30768. }
  30769. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30770. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30771. if (!this._texture) {
  30772. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30773. if (this._deleteBuffer) {
  30774. delete this._buffer;
  30775. }
  30776. }
  30777. else {
  30778. if (this._delayedOnLoad) {
  30779. if (this._texture.isReady) {
  30780. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30781. }
  30782. else {
  30783. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30784. }
  30785. }
  30786. }
  30787. this._delayedOnLoad = null;
  30788. this._delayedOnError = null;
  30789. };
  30790. /**
  30791. * Default is Trilinear mode.
  30792. *
  30793. * | Value | Type | Description |
  30794. * | ----- | ------------------ | ----------- |
  30795. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30796. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30797. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30798. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30799. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30800. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30801. * | 7 | NEAREST_LINEAR | |
  30802. * | 8 | NEAREST_NEAREST | |
  30803. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30804. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30805. * | 11 | LINEAR_LINEAR | |
  30806. * | 12 | LINEAR_NEAREST | |
  30807. *
  30808. * > _mag_: magnification filter (close to the viewer)
  30809. * > _min_: minification filter (far from the viewer)
  30810. * > _mip_: filter used between mip map levels
  30811. *
  30812. */
  30813. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30814. if (!this._texture) {
  30815. return;
  30816. }
  30817. var scene = this.getScene();
  30818. if (!scene) {
  30819. return;
  30820. }
  30821. this._samplingMode = samplingMode;
  30822. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30823. };
  30824. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30825. x *= this.uScale;
  30826. y *= this.vScale;
  30827. x -= this.uRotationCenter * this.uScale;
  30828. y -= this.vRotationCenter * this.vScale;
  30829. z -= this.wRotationCenter;
  30830. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30831. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30832. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30833. t.z += this.wRotationCenter;
  30834. };
  30835. Texture.prototype.getTextureMatrix = function () {
  30836. var _this = this;
  30837. if (this.uOffset === this._cachedUOffset &&
  30838. this.vOffset === this._cachedVOffset &&
  30839. this.uScale === this._cachedUScale &&
  30840. this.vScale === this._cachedVScale &&
  30841. this.uAng === this._cachedUAng &&
  30842. this.vAng === this._cachedVAng &&
  30843. this.wAng === this._cachedWAng) {
  30844. return this._cachedTextureMatrix;
  30845. }
  30846. this._cachedUOffset = this.uOffset;
  30847. this._cachedVOffset = this.vOffset;
  30848. this._cachedUScale = this.uScale;
  30849. this._cachedVScale = this.vScale;
  30850. this._cachedUAng = this.uAng;
  30851. this._cachedVAng = this.vAng;
  30852. this._cachedWAng = this.wAng;
  30853. if (!this._cachedTextureMatrix) {
  30854. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30855. this._rowGenerationMatrix = new BABYLON.Matrix();
  30856. this._t0 = BABYLON.Vector3.Zero();
  30857. this._t1 = BABYLON.Vector3.Zero();
  30858. this._t2 = BABYLON.Vector3.Zero();
  30859. }
  30860. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30861. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30862. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30863. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30864. this._t1.subtractInPlace(this._t0);
  30865. this._t2.subtractInPlace(this._t0);
  30866. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30867. this._cachedTextureMatrix.m[0] = this._t1.x;
  30868. this._cachedTextureMatrix.m[1] = this._t1.y;
  30869. this._cachedTextureMatrix.m[2] = this._t1.z;
  30870. this._cachedTextureMatrix.m[4] = this._t2.x;
  30871. this._cachedTextureMatrix.m[5] = this._t2.y;
  30872. this._cachedTextureMatrix.m[6] = this._t2.z;
  30873. this._cachedTextureMatrix.m[8] = this._t0.x;
  30874. this._cachedTextureMatrix.m[9] = this._t0.y;
  30875. this._cachedTextureMatrix.m[10] = this._t0.z;
  30876. var scene = this.getScene();
  30877. if (!scene) {
  30878. return this._cachedTextureMatrix;
  30879. }
  30880. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30881. return mat.hasTexture(_this);
  30882. });
  30883. return this._cachedTextureMatrix;
  30884. };
  30885. Texture.prototype.getReflectionTextureMatrix = function () {
  30886. var _this = this;
  30887. var scene = this.getScene();
  30888. if (!scene) {
  30889. return this._cachedTextureMatrix;
  30890. }
  30891. if (this.uOffset === this._cachedUOffset &&
  30892. this.vOffset === this._cachedVOffset &&
  30893. this.uScale === this._cachedUScale &&
  30894. this.vScale === this._cachedVScale &&
  30895. this.coordinatesMode === this._cachedCoordinatesMode) {
  30896. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30897. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30898. return this._cachedTextureMatrix;
  30899. }
  30900. }
  30901. else {
  30902. return this._cachedTextureMatrix;
  30903. }
  30904. }
  30905. if (!this._cachedTextureMatrix) {
  30906. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30907. }
  30908. if (!this._projectionModeMatrix) {
  30909. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30910. }
  30911. this._cachedUOffset = this.uOffset;
  30912. this._cachedVOffset = this.vOffset;
  30913. this._cachedUScale = this.uScale;
  30914. this._cachedVScale = this.vScale;
  30915. this._cachedCoordinatesMode = this.coordinatesMode;
  30916. switch (this.coordinatesMode) {
  30917. case Texture.PLANAR_MODE:
  30918. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30919. this._cachedTextureMatrix[0] = this.uScale;
  30920. this._cachedTextureMatrix[5] = this.vScale;
  30921. this._cachedTextureMatrix[12] = this.uOffset;
  30922. this._cachedTextureMatrix[13] = this.vOffset;
  30923. break;
  30924. case Texture.PROJECTION_MODE:
  30925. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30926. this._projectionModeMatrix.m[0] = 0.5;
  30927. this._projectionModeMatrix.m[5] = -0.5;
  30928. this._projectionModeMatrix.m[10] = 0.0;
  30929. this._projectionModeMatrix.m[12] = 0.5;
  30930. this._projectionModeMatrix.m[13] = 0.5;
  30931. this._projectionModeMatrix.m[14] = 1.0;
  30932. this._projectionModeMatrix.m[15] = 1.0;
  30933. var projectionMatrix = scene.getProjectionMatrix();
  30934. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30935. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30936. break;
  30937. default:
  30938. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30939. break;
  30940. }
  30941. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30942. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30943. });
  30944. return this._cachedTextureMatrix;
  30945. };
  30946. Texture.prototype.clone = function () {
  30947. var _this = this;
  30948. return BABYLON.SerializationHelper.Clone(function () {
  30949. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30950. }, this);
  30951. };
  30952. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30953. get: function () {
  30954. if (!this._onLoadObservable) {
  30955. this._onLoadObservable = new BABYLON.Observable();
  30956. }
  30957. return this._onLoadObservable;
  30958. },
  30959. enumerable: true,
  30960. configurable: true
  30961. });
  30962. Texture.prototype.serialize = function () {
  30963. var serializationObject = _super.prototype.serialize.call(this);
  30964. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30965. serializationObject.base64String = this._buffer;
  30966. serializationObject.name = serializationObject.name.replace("data:", "");
  30967. }
  30968. serializationObject.invertY = this._invertY;
  30969. serializationObject.samplingMode = this.samplingMode;
  30970. return serializationObject;
  30971. };
  30972. Texture.prototype.getClassName = function () {
  30973. return "Texture";
  30974. };
  30975. Texture.prototype.dispose = function () {
  30976. _super.prototype.dispose.call(this);
  30977. if (this._onLoadObservable) {
  30978. this._onLoadObservable.clear();
  30979. this._onLoadObservable = null;
  30980. }
  30981. this._delayedOnLoad = null;
  30982. this._delayedOnError = null;
  30983. };
  30984. // Statics
  30985. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30986. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30987. if (onLoad === void 0) { onLoad = null; }
  30988. if (onError === void 0) { onError = null; }
  30989. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30990. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30991. };
  30992. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30993. if (parsedTexture.customType) {
  30994. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30995. // Update Sampling Mode
  30996. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30997. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30998. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30999. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31000. }
  31001. }
  31002. return parsedCustomTexture;
  31003. }
  31004. if (parsedTexture.isCube) {
  31005. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31006. }
  31007. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31008. return null;
  31009. }
  31010. var texture = BABYLON.SerializationHelper.Parse(function () {
  31011. var generateMipMaps = true;
  31012. if (parsedTexture.noMipmap) {
  31013. generateMipMaps = false;
  31014. }
  31015. if (parsedTexture.mirrorPlane) {
  31016. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31017. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31018. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31019. return mirrorTexture;
  31020. }
  31021. else if (parsedTexture.isRenderTarget) {
  31022. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31023. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31024. return renderTargetTexture;
  31025. }
  31026. else {
  31027. var texture;
  31028. if (parsedTexture.base64String) {
  31029. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31030. }
  31031. else {
  31032. var url = rootUrl + parsedTexture.name;
  31033. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31034. url = parsedTexture.url;
  31035. }
  31036. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31037. }
  31038. return texture;
  31039. }
  31040. }, parsedTexture, scene);
  31041. // Update Sampling Mode
  31042. if (parsedTexture.samplingMode) {
  31043. var sampling = parsedTexture.samplingMode;
  31044. if (texture._samplingMode !== sampling) {
  31045. texture.updateSamplingMode(sampling);
  31046. }
  31047. }
  31048. // Animations
  31049. if (parsedTexture.animations) {
  31050. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31051. var parsedAnimation = parsedTexture.animations[animationIndex];
  31052. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31053. }
  31054. }
  31055. return texture;
  31056. };
  31057. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31058. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31059. if (noMipmap === void 0) { noMipmap = false; }
  31060. if (invertY === void 0) { invertY = true; }
  31061. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31062. if (onLoad === void 0) { onLoad = null; }
  31063. if (onError === void 0) { onError = null; }
  31064. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31065. if (name.substr(0, 5) !== "data:") {
  31066. name = "data:" + name;
  31067. }
  31068. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31069. };
  31070. // Constants
  31071. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31072. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31073. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31074. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31075. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31076. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31077. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31078. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31079. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31080. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31081. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31082. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31083. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31084. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31085. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31086. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31087. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31088. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31089. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31090. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31091. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31092. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31093. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31094. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31095. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31096. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31097. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31098. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31099. /**
  31100. * 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
  31101. */
  31102. Texture.UseSerializedUrlIfAny = false;
  31103. __decorate([
  31104. BABYLON.serialize()
  31105. ], Texture.prototype, "url", void 0);
  31106. __decorate([
  31107. BABYLON.serialize()
  31108. ], Texture.prototype, "uOffset", void 0);
  31109. __decorate([
  31110. BABYLON.serialize()
  31111. ], Texture.prototype, "vOffset", void 0);
  31112. __decorate([
  31113. BABYLON.serialize()
  31114. ], Texture.prototype, "uScale", void 0);
  31115. __decorate([
  31116. BABYLON.serialize()
  31117. ], Texture.prototype, "vScale", void 0);
  31118. __decorate([
  31119. BABYLON.serialize()
  31120. ], Texture.prototype, "uAng", void 0);
  31121. __decorate([
  31122. BABYLON.serialize()
  31123. ], Texture.prototype, "vAng", void 0);
  31124. __decorate([
  31125. BABYLON.serialize()
  31126. ], Texture.prototype, "wAng", void 0);
  31127. __decorate([
  31128. BABYLON.serialize()
  31129. ], Texture.prototype, "uRotationCenter", void 0);
  31130. __decorate([
  31131. BABYLON.serialize()
  31132. ], Texture.prototype, "vRotationCenter", void 0);
  31133. __decorate([
  31134. BABYLON.serialize()
  31135. ], Texture.prototype, "wRotationCenter", void 0);
  31136. __decorate([
  31137. BABYLON.serialize()
  31138. ], Texture.prototype, "isBlocking", null);
  31139. return Texture;
  31140. }(BABYLON.BaseTexture));
  31141. BABYLON.Texture = Texture;
  31142. })(BABYLON || (BABYLON = {}));
  31143. //# sourceMappingURL=babylon.texture.js.map
  31144. var BABYLON;
  31145. (function (BABYLON) {
  31146. /**
  31147. * @hidden
  31148. **/
  31149. var _InstancesBatch = /** @class */ (function () {
  31150. function _InstancesBatch() {
  31151. this.mustReturn = false;
  31152. this.visibleInstances = new Array();
  31153. this.renderSelf = new Array();
  31154. }
  31155. return _InstancesBatch;
  31156. }());
  31157. BABYLON._InstancesBatch = _InstancesBatch;
  31158. /**
  31159. * Class used to represent renderable models
  31160. */
  31161. var Mesh = /** @class */ (function (_super) {
  31162. __extends(Mesh, _super);
  31163. /**
  31164. * @constructor
  31165. * @param name The value used by scene.getMeshByName() to do a lookup.
  31166. * @param scene The scene to add this mesh to.
  31167. * @param parent The parent of this mesh, if it has one
  31168. * @param source An optional Mesh from which geometry is shared, cloned.
  31169. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31170. * When false, achieved by calling a clone(), also passing False.
  31171. * This will make creation of children, recursive.
  31172. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31173. */
  31174. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31175. if (scene === void 0) { scene = null; }
  31176. if (parent === void 0) { parent = null; }
  31177. if (source === void 0) { source = null; }
  31178. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31179. var _this = _super.call(this, name, scene) || this;
  31180. // Members
  31181. /**
  31182. * Gets the delay loading state of the mesh (when delay loading is turned on)
  31183. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  31184. */
  31185. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31186. /**
  31187. * Gets the list of instances created from this mesh
  31188. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  31189. */
  31190. _this.instances = new Array();
  31191. _this._LODLevels = new Array();
  31192. /** @hidden */
  31193. _this._visibleInstances = {};
  31194. _this._renderIdForInstances = new Array();
  31195. _this._batchCache = new _InstancesBatch();
  31196. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31197. // Use by builder only to know what orientation were the mesh build in.
  31198. /** @hidden */
  31199. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  31200. /**
  31201. * Use this property to change the original side orientation defined at construction time
  31202. */
  31203. _this.overrideMaterialSideOrientation = null;
  31204. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31205. // Will be used to save a source mesh reference, If any
  31206. _this._source = null;
  31207. scene = _this.getScene();
  31208. if (source) {
  31209. // Geometry
  31210. if (source._geometry) {
  31211. source._geometry.applyToMesh(_this);
  31212. }
  31213. // Deep copy
  31214. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31215. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31216. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31217. ], ["_poseMatrix"]);
  31218. // Source mesh
  31219. _this._source = source;
  31220. // Construction Params
  31221. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31222. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31223. var myAnyThis = _this;
  31224. var myAnySource = source;
  31225. myAnyThis._closePath = myAnySource._closePath;
  31226. myAnyThis._idx = myAnySource._idx;
  31227. myAnyThis.dashSize = myAnySource.dashSize;
  31228. myAnyThis.gapSize = myAnySource.gapSize;
  31229. myAnyThis.path3D = myAnySource.path3D;
  31230. myAnyThis.pathArray = myAnySource.pathArray;
  31231. myAnyThis.arc = myAnySource.arc;
  31232. myAnyThis.radius = myAnySource.radius;
  31233. // Animation ranges
  31234. if (_this._source._ranges) {
  31235. var ranges = _this._source._ranges;
  31236. for (var name in ranges) {
  31237. if (!ranges.hasOwnProperty(name)) {
  31238. continue;
  31239. }
  31240. if (!ranges[name]) {
  31241. continue;
  31242. }
  31243. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31244. }
  31245. }
  31246. // Metadata
  31247. if (source.metadata && source.metadata.clone) {
  31248. _this.metadata = source.metadata.clone();
  31249. }
  31250. else {
  31251. _this.metadata = source.metadata;
  31252. }
  31253. // Tags
  31254. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31255. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31256. }
  31257. // Parent
  31258. _this.parent = source.parent;
  31259. // Pivot
  31260. _this.setPivotMatrix(source.getPivotMatrix());
  31261. _this.id = name + "." + source.id;
  31262. // Material
  31263. _this.material = source.material;
  31264. var index;
  31265. if (!doNotCloneChildren) {
  31266. // Children
  31267. var directDescendants = source.getDescendants(true);
  31268. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31269. var child = directDescendants[index_1];
  31270. if (child.clone) {
  31271. child.clone(name + "." + child.name, _this);
  31272. }
  31273. }
  31274. }
  31275. // Physics clone
  31276. var physicsEngine = _this.getScene().getPhysicsEngine();
  31277. if (clonePhysicsImpostor && physicsEngine) {
  31278. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31279. if (impostor) {
  31280. _this.physicsImpostor = impostor.clone(_this);
  31281. }
  31282. }
  31283. // Particles
  31284. for (index = 0; index < scene.particleSystems.length; index++) {
  31285. var system = scene.particleSystems[index];
  31286. if (system.emitter === source) {
  31287. system.clone(system.name, _this);
  31288. }
  31289. }
  31290. _this.refreshBoundingInfo();
  31291. _this.computeWorldMatrix(true);
  31292. }
  31293. // Parent
  31294. if (parent !== null) {
  31295. _this.parent = parent;
  31296. }
  31297. return _this;
  31298. }
  31299. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31300. /**
  31301. * An event triggered before rendering the mesh
  31302. */
  31303. get: function () {
  31304. if (!this._onBeforeRenderObservable) {
  31305. this._onBeforeRenderObservable = new BABYLON.Observable();
  31306. }
  31307. return this._onBeforeRenderObservable;
  31308. },
  31309. enumerable: true,
  31310. configurable: true
  31311. });
  31312. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31313. /**
  31314. * An event triggered after rendering the mesh
  31315. */
  31316. get: function () {
  31317. if (!this._onAfterRenderObservable) {
  31318. this._onAfterRenderObservable = new BABYLON.Observable();
  31319. }
  31320. return this._onAfterRenderObservable;
  31321. },
  31322. enumerable: true,
  31323. configurable: true
  31324. });
  31325. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31326. /**
  31327. * An event triggered before drawing the mesh
  31328. */
  31329. get: function () {
  31330. if (!this._onBeforeDrawObservable) {
  31331. this._onBeforeDrawObservable = new BABYLON.Observable();
  31332. }
  31333. return this._onBeforeDrawObservable;
  31334. },
  31335. enumerable: true,
  31336. configurable: true
  31337. });
  31338. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31339. /**
  31340. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31341. */
  31342. set: function (callback) {
  31343. if (this._onBeforeDrawObserver) {
  31344. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31345. }
  31346. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31347. },
  31348. enumerable: true,
  31349. configurable: true
  31350. });
  31351. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31352. /**
  31353. * Gets or sets the morph target manager
  31354. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31355. */
  31356. get: function () {
  31357. return this._morphTargetManager;
  31358. },
  31359. set: function (value) {
  31360. if (this._morphTargetManager === value) {
  31361. return;
  31362. }
  31363. this._morphTargetManager = value;
  31364. this._syncGeometryWithMorphTargetManager();
  31365. },
  31366. enumerable: true,
  31367. configurable: true
  31368. });
  31369. Object.defineProperty(Mesh.prototype, "source", {
  31370. /**
  31371. * Gets the source mesh (the one used to clone this one from)
  31372. */
  31373. get: function () {
  31374. return this._source;
  31375. },
  31376. enumerable: true,
  31377. configurable: true
  31378. });
  31379. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31380. /**
  31381. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31382. */
  31383. get: function () {
  31384. return this._unIndexed;
  31385. },
  31386. set: function (value) {
  31387. if (this._unIndexed !== value) {
  31388. this._unIndexed = value;
  31389. this._markSubMeshesAsAttributesDirty();
  31390. }
  31391. },
  31392. enumerable: true,
  31393. configurable: true
  31394. });
  31395. // Methods
  31396. /**
  31397. * Gets the class name
  31398. * @returns the string "Mesh".
  31399. */
  31400. Mesh.prototype.getClassName = function () {
  31401. return "Mesh";
  31402. };
  31403. /**
  31404. * Returns a description of this mesh
  31405. * @param fullDetails define if full details about this mesh must be used
  31406. * @returns a descriptive string representing this mesh
  31407. */
  31408. Mesh.prototype.toString = function (fullDetails) {
  31409. var ret = _super.prototype.toString.call(this, fullDetails);
  31410. ret += ", n vertices: " + this.getTotalVertices();
  31411. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31412. if (this.animations) {
  31413. for (var i = 0; i < this.animations.length; i++) {
  31414. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31415. }
  31416. }
  31417. if (fullDetails) {
  31418. if (this._geometry) {
  31419. var ib = this.getIndices();
  31420. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31421. if (vb && ib) {
  31422. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31423. }
  31424. }
  31425. else {
  31426. ret += ", flat shading: UNKNOWN";
  31427. }
  31428. }
  31429. return ret;
  31430. };
  31431. /** @hidden */
  31432. Mesh.prototype._unBindEffect = function () {
  31433. _super.prototype._unBindEffect.call(this);
  31434. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31435. var instance = _a[_i];
  31436. instance._unBindEffect();
  31437. }
  31438. };
  31439. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31440. /**
  31441. * Gets a boolean indicating if this mesh has LOD
  31442. */
  31443. get: function () {
  31444. return this._LODLevels.length > 0;
  31445. },
  31446. enumerable: true,
  31447. configurable: true
  31448. });
  31449. /**
  31450. * Gets the list of MeshLODLevel associated with the current mesh
  31451. * @returns an array of MeshLODLevel
  31452. */
  31453. Mesh.prototype.getLODLevels = function () {
  31454. return this._LODLevels;
  31455. };
  31456. Mesh.prototype._sortLODLevels = function () {
  31457. this._LODLevels.sort(function (a, b) {
  31458. if (a.distance < b.distance) {
  31459. return 1;
  31460. }
  31461. if (a.distance > b.distance) {
  31462. return -1;
  31463. }
  31464. return 0;
  31465. });
  31466. };
  31467. /**
  31468. * Add a mesh as LOD level triggered at the given distance.
  31469. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31470. * @param distance The distance from the center of the object to show this level
  31471. * @param mesh The mesh to be added as LOD level (can be null)
  31472. * @return This mesh (for chaining)
  31473. */
  31474. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31475. if (mesh && mesh._masterMesh) {
  31476. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31477. return this;
  31478. }
  31479. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31480. this._LODLevels.push(level);
  31481. if (mesh) {
  31482. mesh._masterMesh = this;
  31483. }
  31484. this._sortLODLevels();
  31485. return this;
  31486. };
  31487. /**
  31488. * Returns the LOD level mesh at the passed distance or null if not found.
  31489. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31490. * @param distance The distance from the center of the object to show this level
  31491. * @returns a Mesh or `null`
  31492. */
  31493. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31494. for (var index = 0; index < this._LODLevels.length; index++) {
  31495. var level = this._LODLevels[index];
  31496. if (level.distance === distance) {
  31497. return level.mesh;
  31498. }
  31499. }
  31500. return null;
  31501. };
  31502. /**
  31503. * Remove a mesh from the LOD array
  31504. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31505. * @param mesh defines the mesh to be removed
  31506. * @return This mesh (for chaining)
  31507. */
  31508. Mesh.prototype.removeLODLevel = function (mesh) {
  31509. for (var index = 0; index < this._LODLevels.length; index++) {
  31510. if (this._LODLevels[index].mesh === mesh) {
  31511. this._LODLevels.splice(index, 1);
  31512. if (mesh) {
  31513. mesh._masterMesh = null;
  31514. }
  31515. }
  31516. }
  31517. this._sortLODLevels();
  31518. return this;
  31519. };
  31520. /**
  31521. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31522. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31523. * @param camera defines the camera to use to compute distance
  31524. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31525. * @return This mesh (for chaining)
  31526. */
  31527. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31528. if (!this._LODLevels || this._LODLevels.length === 0) {
  31529. return this;
  31530. }
  31531. var bSphere;
  31532. if (boundingSphere) {
  31533. bSphere = boundingSphere;
  31534. }
  31535. else {
  31536. var boundingInfo = this.getBoundingInfo();
  31537. bSphere = boundingInfo.boundingSphere;
  31538. }
  31539. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31540. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31541. if (this.onLODLevelSelection) {
  31542. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31543. }
  31544. return this;
  31545. }
  31546. for (var index = 0; index < this._LODLevels.length; index++) {
  31547. var level = this._LODLevels[index];
  31548. if (level.distance < distanceToCamera) {
  31549. if (level.mesh) {
  31550. level.mesh._preActivate();
  31551. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31552. }
  31553. if (this.onLODLevelSelection) {
  31554. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31555. }
  31556. return level.mesh;
  31557. }
  31558. }
  31559. if (this.onLODLevelSelection) {
  31560. this.onLODLevelSelection(distanceToCamera, this, this);
  31561. }
  31562. return this;
  31563. };
  31564. Object.defineProperty(Mesh.prototype, "geometry", {
  31565. /**
  31566. * Gets the mesh internal Geometry object
  31567. */
  31568. get: function () {
  31569. return this._geometry;
  31570. },
  31571. enumerable: true,
  31572. configurable: true
  31573. });
  31574. /**
  31575. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31576. * @returns the total number of vertices
  31577. */
  31578. Mesh.prototype.getTotalVertices = function () {
  31579. if (this._geometry === null || this._geometry === undefined) {
  31580. return 0;
  31581. }
  31582. return this._geometry.getTotalVertices();
  31583. };
  31584. /**
  31585. * Returns the content of an associated vertex buffer
  31586. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31587. * - BABYLON.VertexBuffer.PositionKind
  31588. * - BABYLON.VertexBuffer.UVKind
  31589. * - BABYLON.VertexBuffer.UV2Kind
  31590. * - BABYLON.VertexBuffer.UV3Kind
  31591. * - BABYLON.VertexBuffer.UV4Kind
  31592. * - BABYLON.VertexBuffer.UV5Kind
  31593. * - BABYLON.VertexBuffer.UV6Kind
  31594. * - BABYLON.VertexBuffer.ColorKind
  31595. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31596. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31597. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31598. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31599. * @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
  31600. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31601. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31602. */
  31603. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31604. if (!this._geometry) {
  31605. return null;
  31606. }
  31607. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31608. };
  31609. /**
  31610. * Returns the mesh VertexBuffer object from the requested `kind`
  31611. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31612. * - BABYLON.VertexBuffer.PositionKind
  31613. * - BABYLON.VertexBuffer.UVKind
  31614. * - BABYLON.VertexBuffer.UV2Kind
  31615. * - BABYLON.VertexBuffer.UV3Kind
  31616. * - BABYLON.VertexBuffer.UV4Kind
  31617. * - BABYLON.VertexBuffer.UV5Kind
  31618. * - BABYLON.VertexBuffer.UV6Kind
  31619. * - BABYLON.VertexBuffer.ColorKind
  31620. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31621. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31622. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31623. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31624. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31625. */
  31626. Mesh.prototype.getVertexBuffer = function (kind) {
  31627. if (!this._geometry) {
  31628. return null;
  31629. }
  31630. return this._geometry.getVertexBuffer(kind);
  31631. };
  31632. /**
  31633. * Tests if a specific vertex buffer is associated with this mesh
  31634. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31635. * - BABYLON.VertexBuffer.PositionKind
  31636. * - BABYLON.VertexBuffer.UVKind
  31637. * - BABYLON.VertexBuffer.UV2Kind
  31638. * - BABYLON.VertexBuffer.UV3Kind
  31639. * - BABYLON.VertexBuffer.UV4Kind
  31640. * - BABYLON.VertexBuffer.UV5Kind
  31641. * - BABYLON.VertexBuffer.UV6Kind
  31642. * - BABYLON.VertexBuffer.ColorKind
  31643. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31644. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31645. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31646. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31647. * @returns a boolean
  31648. */
  31649. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31650. if (!this._geometry) {
  31651. if (this._delayInfo) {
  31652. return this._delayInfo.indexOf(kind) !== -1;
  31653. }
  31654. return false;
  31655. }
  31656. return this._geometry.isVerticesDataPresent(kind);
  31657. };
  31658. /**
  31659. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31660. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31661. * - BABYLON.VertexBuffer.PositionKind
  31662. * - BABYLON.VertexBuffer.UVKind
  31663. * - BABYLON.VertexBuffer.UV2Kind
  31664. * - BABYLON.VertexBuffer.UV3Kind
  31665. * - BABYLON.VertexBuffer.UV4Kind
  31666. * - BABYLON.VertexBuffer.UV5Kind
  31667. * - BABYLON.VertexBuffer.UV6Kind
  31668. * - BABYLON.VertexBuffer.ColorKind
  31669. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31670. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31671. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31672. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31673. * @returns a boolean
  31674. */
  31675. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31676. if (!this._geometry) {
  31677. if (this._delayInfo) {
  31678. return this._delayInfo.indexOf(kind) !== -1;
  31679. }
  31680. return false;
  31681. }
  31682. return this._geometry.isVertexBufferUpdatable(kind);
  31683. };
  31684. /**
  31685. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31686. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31687. * - BABYLON.VertexBuffer.PositionKind
  31688. * - BABYLON.VertexBuffer.UVKind
  31689. * - BABYLON.VertexBuffer.UV2Kind
  31690. * - BABYLON.VertexBuffer.UV3Kind
  31691. * - BABYLON.VertexBuffer.UV4Kind
  31692. * - BABYLON.VertexBuffer.UV5Kind
  31693. * - BABYLON.VertexBuffer.UV6Kind
  31694. * - BABYLON.VertexBuffer.ColorKind
  31695. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31696. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31697. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31698. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31699. * @returns an array of strings
  31700. */
  31701. Mesh.prototype.getVerticesDataKinds = function () {
  31702. if (!this._geometry) {
  31703. var result = new Array();
  31704. if (this._delayInfo) {
  31705. this._delayInfo.forEach(function (kind, index, array) {
  31706. result.push(kind);
  31707. });
  31708. }
  31709. return result;
  31710. }
  31711. return this._geometry.getVerticesDataKinds();
  31712. };
  31713. /**
  31714. * Returns a positive integer : the total number of indices in this mesh geometry.
  31715. * @returns the numner of indices or zero if the mesh has no geometry.
  31716. */
  31717. Mesh.prototype.getTotalIndices = function () {
  31718. if (!this._geometry) {
  31719. return 0;
  31720. }
  31721. return this._geometry.getTotalIndices();
  31722. };
  31723. /**
  31724. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31725. * @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.
  31726. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31727. * @returns the indices array or an empty array if the mesh has no geometry
  31728. */
  31729. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31730. if (!this._geometry) {
  31731. return [];
  31732. }
  31733. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31734. };
  31735. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31736. get: function () {
  31737. return this._masterMesh !== null && this._masterMesh !== undefined;
  31738. },
  31739. enumerable: true,
  31740. configurable: true
  31741. });
  31742. /**
  31743. * Determine if the current mesh is ready to be rendered
  31744. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31745. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31746. * @returns true if all associated assets are ready (material, textures, shaders)
  31747. */
  31748. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31749. if (completeCheck === void 0) { completeCheck = false; }
  31750. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31751. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31752. return false;
  31753. }
  31754. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31755. return false;
  31756. }
  31757. if (!this.subMeshes || this.subMeshes.length === 0) {
  31758. return true;
  31759. }
  31760. if (!completeCheck) {
  31761. return true;
  31762. }
  31763. var engine = this.getEngine();
  31764. var scene = this.getScene();
  31765. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31766. this.computeWorldMatrix();
  31767. var mat = this.material || scene.defaultMaterial;
  31768. if (mat) {
  31769. if (mat.storeEffectOnSubMeshes) {
  31770. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31771. var subMesh = _a[_i];
  31772. var effectiveMaterial = subMesh.getMaterial();
  31773. if (effectiveMaterial) {
  31774. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31775. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31776. return false;
  31777. }
  31778. }
  31779. else {
  31780. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31781. return false;
  31782. }
  31783. }
  31784. }
  31785. }
  31786. }
  31787. else {
  31788. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31789. return false;
  31790. }
  31791. }
  31792. }
  31793. // Shadows
  31794. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31795. var light = _c[_b];
  31796. var generator = light.getShadowGenerator();
  31797. if (generator) {
  31798. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31799. var subMesh = _e[_d];
  31800. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31801. return false;
  31802. }
  31803. }
  31804. }
  31805. }
  31806. // LOD
  31807. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31808. var lod = _g[_f];
  31809. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31810. return false;
  31811. }
  31812. }
  31813. return true;
  31814. };
  31815. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31816. /**
  31817. * 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.
  31818. */
  31819. get: function () {
  31820. return this._areNormalsFrozen;
  31821. },
  31822. enumerable: true,
  31823. configurable: true
  31824. });
  31825. /**
  31826. * 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.
  31827. * @returns the current mesh
  31828. */
  31829. Mesh.prototype.freezeNormals = function () {
  31830. this._areNormalsFrozen = true;
  31831. return this;
  31832. };
  31833. /**
  31834. * 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
  31835. * @returns the current mesh
  31836. */
  31837. Mesh.prototype.unfreezeNormals = function () {
  31838. this._areNormalsFrozen = false;
  31839. return this;
  31840. };
  31841. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31842. /**
  31843. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31844. */
  31845. set: function (count) {
  31846. this._overridenInstanceCount = count;
  31847. },
  31848. enumerable: true,
  31849. configurable: true
  31850. });
  31851. // Methods
  31852. /** @hidden */
  31853. Mesh.prototype._preActivate = function () {
  31854. var sceneRenderId = this.getScene().getRenderId();
  31855. if (this._preActivateId === sceneRenderId) {
  31856. return this;
  31857. }
  31858. this._preActivateId = sceneRenderId;
  31859. this._visibleInstances = null;
  31860. return this;
  31861. };
  31862. /** @hidden */
  31863. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31864. if (this._visibleInstances) {
  31865. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31866. }
  31867. return this;
  31868. };
  31869. /** @hidden */
  31870. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31871. if (!this._visibleInstances) {
  31872. this._visibleInstances = {};
  31873. this._visibleInstances.defaultRenderId = renderId;
  31874. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31875. }
  31876. if (!this._visibleInstances[renderId]) {
  31877. this._visibleInstances[renderId] = new Array();
  31878. }
  31879. this._visibleInstances[renderId].push(instance);
  31880. return this;
  31881. };
  31882. /**
  31883. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31884. * This means the mesh underlying bounding box and sphere are recomputed.
  31885. * @returns the current mesh
  31886. */
  31887. Mesh.prototype.refreshBoundingInfo = function () {
  31888. return this._refreshBoundingInfo(false);
  31889. };
  31890. /** @hidden */
  31891. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31892. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31893. return this;
  31894. }
  31895. var data = this._getPositionData(applySkeleton);
  31896. if (data) {
  31897. var bias = this.geometry ? this.geometry.boundingBias : null;
  31898. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31899. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31900. }
  31901. if (this.subMeshes) {
  31902. for (var index = 0; index < this.subMeshes.length; index++) {
  31903. this.subMeshes[index].refreshBoundingInfo();
  31904. }
  31905. }
  31906. this._updateBoundingInfo();
  31907. return this;
  31908. };
  31909. Mesh.prototype._getPositionData = function (applySkeleton) {
  31910. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31911. if (data && applySkeleton && this.skeleton) {
  31912. data = BABYLON.Tools.Slice(data);
  31913. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31914. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31915. if (matricesWeightsData && matricesIndicesData) {
  31916. var needExtras = this.numBoneInfluencers > 4;
  31917. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31918. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31919. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31920. var tempVector = BABYLON.Tmp.Vector3[0];
  31921. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31922. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31923. var matWeightIdx = 0;
  31924. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31925. finalMatrix.reset();
  31926. var inf;
  31927. var weight;
  31928. for (inf = 0; inf < 4; inf++) {
  31929. weight = matricesWeightsData[matWeightIdx + inf];
  31930. if (weight > 0) {
  31931. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31932. finalMatrix.addToSelf(tempMatrix);
  31933. }
  31934. }
  31935. if (needExtras) {
  31936. for (inf = 0; inf < 4; inf++) {
  31937. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31938. if (weight > 0) {
  31939. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31940. finalMatrix.addToSelf(tempMatrix);
  31941. }
  31942. }
  31943. }
  31944. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31945. tempVector.toArray(data, index);
  31946. }
  31947. }
  31948. }
  31949. return data;
  31950. };
  31951. /** @hidden */
  31952. Mesh.prototype._createGlobalSubMesh = function (force) {
  31953. var totalVertices = this.getTotalVertices();
  31954. if (!totalVertices || !this.getIndices()) {
  31955. return null;
  31956. }
  31957. // Check if we need to recreate the submeshes
  31958. if (this.subMeshes && this.subMeshes.length > 0) {
  31959. var ib = this.getIndices();
  31960. if (!ib) {
  31961. return null;
  31962. }
  31963. var totalIndices = ib.length;
  31964. var needToRecreate = false;
  31965. if (force) {
  31966. needToRecreate = true;
  31967. }
  31968. else {
  31969. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31970. var submesh = _a[_i];
  31971. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31972. needToRecreate = true;
  31973. break;
  31974. }
  31975. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31976. needToRecreate = true;
  31977. break;
  31978. }
  31979. }
  31980. }
  31981. if (!needToRecreate) {
  31982. return this.subMeshes[0];
  31983. }
  31984. }
  31985. this.releaseSubMeshes();
  31986. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31987. };
  31988. /**
  31989. * This function will subdivide the mesh into multiple submeshes
  31990. * @param count defines the expected number of submeshes
  31991. */
  31992. Mesh.prototype.subdivide = function (count) {
  31993. if (count < 1) {
  31994. return;
  31995. }
  31996. var totalIndices = this.getTotalIndices();
  31997. var subdivisionSize = (totalIndices / count) | 0;
  31998. var offset = 0;
  31999. // Ensure that subdivisionSize is a multiple of 3
  32000. while (subdivisionSize % 3 !== 0) {
  32001. subdivisionSize++;
  32002. }
  32003. this.releaseSubMeshes();
  32004. for (var index = 0; index < count; index++) {
  32005. if (offset >= totalIndices) {
  32006. break;
  32007. }
  32008. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32009. offset += subdivisionSize;
  32010. }
  32011. this.synchronizeInstances();
  32012. };
  32013. /**
  32014. * Copy a FloatArray into a specific associated vertex buffer
  32015. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32016. * - BABYLON.VertexBuffer.PositionKind
  32017. * - BABYLON.VertexBuffer.UVKind
  32018. * - BABYLON.VertexBuffer.UV2Kind
  32019. * - BABYLON.VertexBuffer.UV3Kind
  32020. * - BABYLON.VertexBuffer.UV4Kind
  32021. * - BABYLON.VertexBuffer.UV5Kind
  32022. * - BABYLON.VertexBuffer.UV6Kind
  32023. * - BABYLON.VertexBuffer.ColorKind
  32024. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32025. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32026. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32027. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32028. * @param data defines the data source
  32029. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32030. * @param stride defines the data stride size (can be null)
  32031. * @returns the current mesh
  32032. */
  32033. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32034. if (updatable === void 0) { updatable = false; }
  32035. if (!this._geometry) {
  32036. var vertexData = new BABYLON.VertexData();
  32037. vertexData.set(data, kind);
  32038. var scene = this.getScene();
  32039. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32040. }
  32041. else {
  32042. this._geometry.setVerticesData(kind, data, updatable, stride);
  32043. }
  32044. return this;
  32045. };
  32046. /**
  32047. * Flags an associated vertex buffer as updatable
  32048. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32049. * - BABYLON.VertexBuffer.PositionKind
  32050. * - BABYLON.VertexBuffer.UVKind
  32051. * - BABYLON.VertexBuffer.UV2Kind
  32052. * - BABYLON.VertexBuffer.UV3Kind
  32053. * - BABYLON.VertexBuffer.UV4Kind
  32054. * - BABYLON.VertexBuffer.UV5Kind
  32055. * - BABYLON.VertexBuffer.UV6Kind
  32056. * - BABYLON.VertexBuffer.ColorKind
  32057. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32058. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32059. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32060. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32061. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32062. */
  32063. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32064. if (updatable === void 0) { updatable = true; }
  32065. var vb = this.getVertexBuffer(kind);
  32066. if (!vb || vb.isUpdatable() === updatable) {
  32067. return;
  32068. }
  32069. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32070. };
  32071. /**
  32072. * Sets the mesh global Vertex Buffer
  32073. * @param buffer defines the buffer to use
  32074. * @returns the current mesh
  32075. */
  32076. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32077. if (!this._geometry) {
  32078. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32079. }
  32080. this._geometry.setVerticesBuffer(buffer);
  32081. return this;
  32082. };
  32083. /**
  32084. * Update a specific associated vertex buffer
  32085. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32086. * - BABYLON.VertexBuffer.PositionKind
  32087. * - BABYLON.VertexBuffer.UVKind
  32088. * - BABYLON.VertexBuffer.UV2Kind
  32089. * - BABYLON.VertexBuffer.UV3Kind
  32090. * - BABYLON.VertexBuffer.UV4Kind
  32091. * - BABYLON.VertexBuffer.UV5Kind
  32092. * - BABYLON.VertexBuffer.UV6Kind
  32093. * - BABYLON.VertexBuffer.ColorKind
  32094. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32095. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32096. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32097. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32098. * @param data defines the data source
  32099. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32100. * @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)
  32101. * @returns the current mesh
  32102. */
  32103. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32104. if (!this._geometry) {
  32105. return this;
  32106. }
  32107. if (!makeItUnique) {
  32108. this._geometry.updateVerticesData(kind, data, updateExtends);
  32109. }
  32110. else {
  32111. this.makeGeometryUnique();
  32112. this.updateVerticesData(kind, data, updateExtends, false);
  32113. }
  32114. return this;
  32115. };
  32116. /**
  32117. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32118. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32119. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  32120. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  32121. * @returns the current mesh
  32122. */
  32123. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32124. if (computeNormals === void 0) { computeNormals = true; }
  32125. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32126. if (!positions) {
  32127. return this;
  32128. }
  32129. positionFunction(positions);
  32130. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32131. if (computeNormals) {
  32132. var indices = this.getIndices();
  32133. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32134. if (!normals) {
  32135. return this;
  32136. }
  32137. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32138. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32139. }
  32140. return this;
  32141. };
  32142. /**
  32143. * Creates a un-shared specific occurence of the geometry for the mesh.
  32144. * @returns the current mesh
  32145. */
  32146. Mesh.prototype.makeGeometryUnique = function () {
  32147. if (!this._geometry) {
  32148. return this;
  32149. }
  32150. var oldGeometry = this._geometry;
  32151. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32152. oldGeometry.releaseForMesh(this, true);
  32153. geometry.applyToMesh(this);
  32154. return this;
  32155. };
  32156. /**
  32157. * Set the index buffer of this mesh
  32158. * @param indices defines the source data
  32159. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  32160. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  32161. * @returns the current mesh
  32162. */
  32163. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32164. if (totalVertices === void 0) { totalVertices = null; }
  32165. if (updatable === void 0) { updatable = false; }
  32166. if (!this._geometry) {
  32167. var vertexData = new BABYLON.VertexData();
  32168. vertexData.indices = indices;
  32169. var scene = this.getScene();
  32170. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32171. }
  32172. else {
  32173. this._geometry.setIndices(indices, totalVertices, updatable);
  32174. }
  32175. return this;
  32176. };
  32177. /**
  32178. * Update the current index buffer
  32179. * @param indices defines the source data
  32180. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  32181. * @returns the current mesh
  32182. */
  32183. Mesh.prototype.updateIndices = function (indices, offset) {
  32184. if (!this._geometry) {
  32185. return this;
  32186. }
  32187. this._geometry.updateIndices(indices, offset);
  32188. return this;
  32189. };
  32190. /**
  32191. * Invert the geometry to move from a right handed system to a left handed one.
  32192. * @returns the current mesh
  32193. */
  32194. Mesh.prototype.toLeftHanded = function () {
  32195. if (!this._geometry) {
  32196. return this;
  32197. }
  32198. this._geometry.toLeftHanded();
  32199. return this;
  32200. };
  32201. /** @hidden */
  32202. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32203. if (!this._geometry) {
  32204. return this;
  32205. }
  32206. var engine = this.getScene().getEngine();
  32207. // Wireframe
  32208. var indexToBind;
  32209. if (this._unIndexed) {
  32210. indexToBind = null;
  32211. }
  32212. else {
  32213. switch (fillMode) {
  32214. case BABYLON.Material.PointFillMode:
  32215. indexToBind = null;
  32216. break;
  32217. case BABYLON.Material.WireFrameFillMode:
  32218. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  32219. break;
  32220. default:
  32221. case BABYLON.Material.TriangleFillMode:
  32222. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32223. break;
  32224. }
  32225. }
  32226. // VBOs
  32227. this._geometry._bind(effect, indexToBind);
  32228. return this;
  32229. };
  32230. /** @hidden */
  32231. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32232. if (alternate === void 0) { alternate = false; }
  32233. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32234. return this;
  32235. }
  32236. if (this._onBeforeDrawObservable) {
  32237. this._onBeforeDrawObservable.notifyObservers(this);
  32238. }
  32239. var scene = this.getScene();
  32240. var engine = scene.getEngine();
  32241. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32242. // or triangles as points
  32243. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32244. }
  32245. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32246. // Triangles as wireframe
  32247. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  32248. }
  32249. else {
  32250. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32251. }
  32252. if (scene._isAlternateRenderingEnabled && !alternate) {
  32253. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32254. if (!effect || !scene.activeCamera) {
  32255. return this;
  32256. }
  32257. scene._switchToAlternateCameraConfiguration(true);
  32258. this._effectiveMaterial.bindView(effect);
  32259. this._effectiveMaterial.bindViewProjection(effect);
  32260. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32261. this._draw(subMesh, fillMode, instancesCount, true);
  32262. engine.setViewport(scene.activeCamera.viewport);
  32263. scene._switchToAlternateCameraConfiguration(false);
  32264. this._effectiveMaterial.bindView(effect);
  32265. this._effectiveMaterial.bindViewProjection(effect);
  32266. }
  32267. return this;
  32268. };
  32269. /**
  32270. * Registers for this mesh a javascript function called just before the rendering process
  32271. * @param func defines the function to call before rendering this mesh
  32272. * @returns the current mesh
  32273. */
  32274. Mesh.prototype.registerBeforeRender = function (func) {
  32275. this.onBeforeRenderObservable.add(func);
  32276. return this;
  32277. };
  32278. /**
  32279. * Disposes a previously registered javascript function called before the rendering
  32280. * @param func defines the function to remove
  32281. * @returns the current mesh
  32282. */
  32283. Mesh.prototype.unregisterBeforeRender = function (func) {
  32284. this.onBeforeRenderObservable.removeCallback(func);
  32285. return this;
  32286. };
  32287. /**
  32288. * Registers for this mesh a javascript function called just after the rendering is complete
  32289. * @param func defines the function to call after rendering this mesh
  32290. * @returns the current mesh
  32291. */
  32292. Mesh.prototype.registerAfterRender = function (func) {
  32293. this.onAfterRenderObservable.add(func);
  32294. return this;
  32295. };
  32296. /**
  32297. * Disposes a previously registered javascript function called after the rendering.
  32298. * @param func defines the function to remove
  32299. * @returns the current mesh
  32300. */
  32301. Mesh.prototype.unregisterAfterRender = function (func) {
  32302. this.onAfterRenderObservable.removeCallback(func);
  32303. return this;
  32304. };
  32305. /** @hidden */
  32306. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32307. var scene = this.getScene();
  32308. this._batchCache.mustReturn = false;
  32309. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32310. this._batchCache.visibleInstances[subMeshId] = null;
  32311. if (this._visibleInstances) {
  32312. var currentRenderId = scene.getRenderId();
  32313. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32314. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32315. var selfRenderId = this._renderId;
  32316. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32317. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32318. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32319. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32320. }
  32321. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32322. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32323. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32324. this._batchCache.mustReturn = true;
  32325. return this._batchCache;
  32326. }
  32327. if (currentRenderId !== selfRenderId) {
  32328. this._batchCache.renderSelf[subMeshId] = false;
  32329. }
  32330. }
  32331. this._renderIdForInstances[subMeshId] = currentRenderId;
  32332. }
  32333. return this._batchCache;
  32334. };
  32335. /** @hidden */
  32336. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32337. var visibleInstances = batch.visibleInstances[subMesh._id];
  32338. if (!visibleInstances) {
  32339. return this;
  32340. }
  32341. var matricesCount = visibleInstances.length + 1;
  32342. var bufferSize = matricesCount * 16 * 4;
  32343. var currentInstancesBufferSize = this._instancesBufferSize;
  32344. var instancesBuffer = this._instancesBuffer;
  32345. while (this._instancesBufferSize < bufferSize) {
  32346. this._instancesBufferSize *= 2;
  32347. }
  32348. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32349. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32350. }
  32351. var offset = 0;
  32352. var instancesCount = 0;
  32353. var world = this.getWorldMatrix();
  32354. if (batch.renderSelf[subMesh._id]) {
  32355. world.copyToArray(this._instancesData, offset);
  32356. offset += 16;
  32357. instancesCount++;
  32358. }
  32359. if (visibleInstances) {
  32360. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32361. var instance = visibleInstances[instanceIndex];
  32362. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32363. offset += 16;
  32364. instancesCount++;
  32365. }
  32366. }
  32367. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32368. if (instancesBuffer) {
  32369. instancesBuffer.dispose();
  32370. }
  32371. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32372. this._instancesBuffer = instancesBuffer;
  32373. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32374. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32375. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32376. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32377. }
  32378. else {
  32379. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32380. }
  32381. this._bind(subMesh, effect, fillMode);
  32382. this._draw(subMesh, fillMode, instancesCount);
  32383. engine.unbindInstanceAttributes();
  32384. return this;
  32385. };
  32386. /** @hidden */
  32387. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32388. var scene = this.getScene();
  32389. var engine = scene.getEngine();
  32390. if (hardwareInstancedRendering) {
  32391. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32392. }
  32393. else {
  32394. if (batch.renderSelf[subMesh._id]) {
  32395. // Draw
  32396. if (onBeforeDraw) {
  32397. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32398. }
  32399. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32400. }
  32401. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32402. if (visibleInstancesForSubMesh) {
  32403. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32404. var instance = visibleInstancesForSubMesh[instanceIndex];
  32405. // World
  32406. var world = instance.getWorldMatrix();
  32407. if (onBeforeDraw) {
  32408. onBeforeDraw(true, world, effectiveMaterial);
  32409. }
  32410. // Draw
  32411. this._draw(subMesh, fillMode);
  32412. }
  32413. }
  32414. }
  32415. return this;
  32416. };
  32417. /**
  32418. * 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
  32419. * @param subMesh defines the subMesh to render
  32420. * @param enableAlphaMode defines if alpha mode can be changed
  32421. * @returns the current mesh
  32422. */
  32423. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32424. if (this._checkOcclusionQuery()) {
  32425. return this;
  32426. }
  32427. var scene = this.getScene();
  32428. // Managing instances
  32429. var batch = this._getInstancesRenderList(subMesh._id);
  32430. if (batch.mustReturn) {
  32431. return this;
  32432. }
  32433. // Checking geometry state
  32434. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32435. return this;
  32436. }
  32437. if (this._onBeforeRenderObservable) {
  32438. this._onBeforeRenderObservable.notifyObservers(this);
  32439. }
  32440. var engine = scene.getEngine();
  32441. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32442. // Material
  32443. var material = subMesh.getMaterial();
  32444. if (!material) {
  32445. return this;
  32446. }
  32447. this._effectiveMaterial = material;
  32448. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32449. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32450. return this;
  32451. }
  32452. }
  32453. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32454. return this;
  32455. }
  32456. // Alpha mode
  32457. if (enableAlphaMode) {
  32458. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32459. }
  32460. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32461. var step = _a[_i];
  32462. step.action(this, subMesh, batch);
  32463. }
  32464. var effect;
  32465. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32466. effect = subMesh.effect;
  32467. }
  32468. else {
  32469. effect = this._effectiveMaterial.getEffect();
  32470. }
  32471. if (!effect) {
  32472. return this;
  32473. }
  32474. var sideOrientation = this.overrideMaterialSideOrientation;
  32475. if (sideOrientation == null) {
  32476. sideOrientation = this._effectiveMaterial.sideOrientation;
  32477. if (this._getWorldMatrixDeterminant() < 0) {
  32478. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32479. }
  32480. }
  32481. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32482. if (this._effectiveMaterial.forceDepthWrite) {
  32483. engine.setDepthWrite(true);
  32484. }
  32485. // Bind
  32486. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32487. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32488. this._bind(subMesh, effect, fillMode);
  32489. }
  32490. var world = this.getWorldMatrix();
  32491. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32492. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32493. }
  32494. else {
  32495. this._effectiveMaterial.bind(world, this);
  32496. }
  32497. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32498. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32499. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32500. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32501. }
  32502. // Draw
  32503. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32504. // Unbind
  32505. this._effectiveMaterial.unbind();
  32506. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32507. var step = _c[_b];
  32508. step.action(this, subMesh, batch);
  32509. }
  32510. if (this._onAfterRenderObservable) {
  32511. this._onAfterRenderObservable.notifyObservers(this);
  32512. }
  32513. return this;
  32514. };
  32515. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32516. if (isInstance && effectiveMaterial) {
  32517. effectiveMaterial.bindOnlyWorldMatrix(world);
  32518. }
  32519. };
  32520. /**
  32521. * Normalize matrix weights so that all vertices have a total weight set to 1
  32522. */
  32523. Mesh.prototype.cleanMatrixWeights = function () {
  32524. var epsilon = 1e-3;
  32525. var noInfluenceBoneIndex = 0.0;
  32526. if (this.skeleton) {
  32527. noInfluenceBoneIndex = this.skeleton.bones.length;
  32528. }
  32529. else {
  32530. return;
  32531. }
  32532. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32533. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32534. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32535. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32536. var influencers = this.numBoneInfluencers;
  32537. var size = matricesWeights.length;
  32538. for (var i = 0; i < size; i += 4) {
  32539. var weight = 0.0;
  32540. var firstZeroWeight = -1;
  32541. for (var j = 0; j < 4; j++) {
  32542. var w = matricesWeights[i + j];
  32543. weight += w;
  32544. if (w < epsilon && firstZeroWeight < 0) {
  32545. firstZeroWeight = j;
  32546. }
  32547. }
  32548. if (matricesWeightsExtra) {
  32549. for (var j = 0; j < 4; j++) {
  32550. var w = matricesWeightsExtra[i + j];
  32551. weight += w;
  32552. if (w < epsilon && firstZeroWeight < 0) {
  32553. firstZeroWeight = j + 4;
  32554. }
  32555. }
  32556. }
  32557. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32558. firstZeroWeight = influencers - 1;
  32559. }
  32560. if (weight > epsilon) {
  32561. var mweight = 1.0 / weight;
  32562. for (var j = 0; j < 4; j++) {
  32563. matricesWeights[i + j] *= mweight;
  32564. }
  32565. if (matricesWeightsExtra) {
  32566. for (var j = 0; j < 4; j++) {
  32567. matricesWeightsExtra[i + j] *= mweight;
  32568. }
  32569. }
  32570. }
  32571. else {
  32572. if (firstZeroWeight >= 4) {
  32573. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32574. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32575. }
  32576. else {
  32577. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32578. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32579. }
  32580. }
  32581. }
  32582. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32583. if (matricesIndicesExtra) {
  32584. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32585. }
  32586. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32587. if (matricesWeightsExtra) {
  32588. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32589. }
  32590. };
  32591. /** @hidden */
  32592. Mesh.prototype._checkDelayState = function () {
  32593. var scene = this.getScene();
  32594. if (this._geometry) {
  32595. this._geometry.load(scene);
  32596. }
  32597. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32598. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32599. this._queueLoad(scene);
  32600. }
  32601. return this;
  32602. };
  32603. Mesh.prototype._queueLoad = function (scene) {
  32604. var _this = this;
  32605. scene._addPendingData(this);
  32606. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32607. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32608. if (data instanceof ArrayBuffer) {
  32609. _this._delayLoadingFunction(data, _this);
  32610. }
  32611. else {
  32612. _this._delayLoadingFunction(JSON.parse(data), _this);
  32613. }
  32614. _this.instances.forEach(function (instance) {
  32615. instance._syncSubMeshes();
  32616. });
  32617. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32618. scene._removePendingData(_this);
  32619. }, function () { }, scene.database, getBinaryData);
  32620. return this;
  32621. };
  32622. /**
  32623. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32624. * A mesh is in the frustum if its bounding box intersects the frustum
  32625. * @param frustumPlanes defines the frustum to test
  32626. * @returns true if the mesh is in the frustum planes
  32627. */
  32628. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32629. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32630. return false;
  32631. }
  32632. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32633. return false;
  32634. }
  32635. this._checkDelayState();
  32636. return true;
  32637. };
  32638. /**
  32639. * Sets the mesh material by the material or multiMaterial `id` property
  32640. * @param id is a string identifying the material or the multiMaterial
  32641. * @returns the current mesh
  32642. */
  32643. Mesh.prototype.setMaterialByID = function (id) {
  32644. var materials = this.getScene().materials;
  32645. var index;
  32646. for (index = materials.length - 1; index > -1; index--) {
  32647. if (materials[index].id === id) {
  32648. this.material = materials[index];
  32649. return this;
  32650. }
  32651. }
  32652. // Multi
  32653. var multiMaterials = this.getScene().multiMaterials;
  32654. for (index = multiMaterials.length - 1; index > -1; index--) {
  32655. if (multiMaterials[index].id === id) {
  32656. this.material = multiMaterials[index];
  32657. return this;
  32658. }
  32659. }
  32660. return this;
  32661. };
  32662. /**
  32663. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32664. * @returns an array of IAnimatable
  32665. */
  32666. Mesh.prototype.getAnimatables = function () {
  32667. var results = new Array();
  32668. if (this.material) {
  32669. results.push(this.material);
  32670. }
  32671. if (this.skeleton) {
  32672. results.push(this.skeleton);
  32673. }
  32674. return results;
  32675. };
  32676. /**
  32677. * Modifies the mesh geometry according to the passed transformation matrix.
  32678. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32679. * The mesh normals are modified using the same transformation.
  32680. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32681. * @param transform defines the transform matrix to use
  32682. * @see http://doc.babylonjs.com/resources/baking_transformations
  32683. * @returns the current mesh
  32684. */
  32685. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32686. // Position
  32687. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32688. return this;
  32689. }
  32690. var submeshes = this.subMeshes.splice(0);
  32691. this._resetPointsArrayCache();
  32692. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32693. var temp = new Array();
  32694. var index;
  32695. for (index = 0; index < data.length; index += 3) {
  32696. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32697. }
  32698. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32699. // Normals
  32700. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32701. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32702. temp = [];
  32703. for (index = 0; index < data.length; index += 3) {
  32704. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32705. }
  32706. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32707. }
  32708. // flip faces?
  32709. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32710. this.flipFaces();
  32711. }
  32712. // Restore submeshes
  32713. this.releaseSubMeshes();
  32714. this.subMeshes = submeshes;
  32715. return this;
  32716. };
  32717. /**
  32718. * Modifies the mesh geometry according to its own current World Matrix.
  32719. * The mesh World Matrix is then reset.
  32720. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32721. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32722. * @see http://doc.babylonjs.com/resources/baking_transformations
  32723. * @returns the current mesh
  32724. */
  32725. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32726. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32727. this.scaling.copyFromFloats(1, 1, 1);
  32728. this.position.copyFromFloats(0, 0, 0);
  32729. this.rotation.copyFromFloats(0, 0, 0);
  32730. //only if quaternion is already set
  32731. if (this.rotationQuaternion) {
  32732. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32733. }
  32734. this._worldMatrix = BABYLON.Matrix.Identity();
  32735. return this;
  32736. };
  32737. Object.defineProperty(Mesh.prototype, "_positions", {
  32738. // Cache
  32739. /** @hidden */
  32740. get: function () {
  32741. if (this._geometry) {
  32742. return this._geometry._positions;
  32743. }
  32744. return null;
  32745. },
  32746. enumerable: true,
  32747. configurable: true
  32748. });
  32749. /** @hidden */
  32750. Mesh.prototype._resetPointsArrayCache = function () {
  32751. if (this._geometry) {
  32752. this._geometry._resetPointsArrayCache();
  32753. }
  32754. return this;
  32755. };
  32756. /** @hidden */
  32757. Mesh.prototype._generatePointsArray = function () {
  32758. if (this._geometry) {
  32759. return this._geometry._generatePointsArray();
  32760. }
  32761. return false;
  32762. };
  32763. /**
  32764. * Returns a new Mesh object generated from the current mesh properties.
  32765. * This method must not get confused with createInstance()
  32766. * @param name is a string, the name given to the new mesh
  32767. * @param newParent can be any Node object (default `null`)
  32768. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  32769. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  32770. * @returns a new mesh
  32771. */
  32772. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32773. if (name === void 0) { name = ""; }
  32774. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32775. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32776. };
  32777. /**
  32778. * Releases resources associated with this mesh.
  32779. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32780. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32781. */
  32782. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32783. var _this = this;
  32784. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32785. this.morphTargetManager = null;
  32786. if (this._geometry) {
  32787. this._geometry.releaseForMesh(this, true);
  32788. }
  32789. if (this._onBeforeDrawObservable) {
  32790. this._onBeforeDrawObservable.clear();
  32791. }
  32792. if (this._onBeforeRenderObservable) {
  32793. this._onBeforeRenderObservable.clear();
  32794. }
  32795. if (this._onAfterRenderObservable) {
  32796. this._onAfterRenderObservable.clear();
  32797. }
  32798. // Sources
  32799. var meshes = this.getScene().meshes;
  32800. meshes.forEach(function (abstractMesh) {
  32801. var mesh = abstractMesh;
  32802. if (mesh._source && mesh._source === _this) {
  32803. mesh._source = null;
  32804. }
  32805. });
  32806. this._source = null;
  32807. // Instances
  32808. if (this._instancesBuffer) {
  32809. this._instancesBuffer.dispose();
  32810. this._instancesBuffer = null;
  32811. }
  32812. while (this.instances.length) {
  32813. this.instances[0].dispose();
  32814. }
  32815. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32816. };
  32817. /**
  32818. * Modifies the mesh geometry according to a displacement map.
  32819. * 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.
  32820. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32821. * @param url is a string, the URL from the image file is to be downloaded.
  32822. * @param minHeight is the lower limit of the displacement.
  32823. * @param maxHeight is the upper limit of the displacement.
  32824. * @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.
  32825. * @param uvOffset is an optional vector2 used to offset UV.
  32826. * @param uvScale is an optional vector2 used to scale UV.
  32827. * @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.
  32828. * @returns the Mesh.
  32829. */
  32830. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32831. var _this = this;
  32832. if (forceUpdate === void 0) { forceUpdate = false; }
  32833. var scene = this.getScene();
  32834. var onload = function (img) {
  32835. // Getting height map data
  32836. var canvas = document.createElement("canvas");
  32837. var context = canvas.getContext("2d");
  32838. var heightMapWidth = img.width;
  32839. var heightMapHeight = img.height;
  32840. canvas.width = heightMapWidth;
  32841. canvas.height = heightMapHeight;
  32842. context.drawImage(img, 0, 0);
  32843. // Create VertexData from map data
  32844. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32845. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32846. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32847. //execute success callback, if set
  32848. if (onSuccess) {
  32849. onSuccess(_this);
  32850. }
  32851. };
  32852. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32853. return this;
  32854. };
  32855. /**
  32856. * Modifies the mesh geometry according to a displacementMap buffer.
  32857. * 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.
  32858. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32859. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32860. * @param heightMapWidth is the width of the buffer image.
  32861. * @param heightMapHeight is the height of the buffer image.
  32862. * @param minHeight is the lower limit of the displacement.
  32863. * @param maxHeight is the upper limit of the displacement.
  32864. * @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.
  32865. * @param uvOffset is an optional vector2 used to offset UV.
  32866. * @param uvScale is an optional vector2 used to scale UV.
  32867. * @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.
  32868. * @returns the Mesh.
  32869. */
  32870. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32871. if (forceUpdate === void 0) { forceUpdate = false; }
  32872. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32873. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32874. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32875. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32876. return this;
  32877. }
  32878. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32879. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32880. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32881. var position = BABYLON.Vector3.Zero();
  32882. var normal = BABYLON.Vector3.Zero();
  32883. var uv = BABYLON.Vector2.Zero();
  32884. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32885. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32886. for (var index = 0; index < positions.length; index += 3) {
  32887. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32888. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32889. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32890. // Compute height
  32891. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32892. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32893. var pos = (u + v * heightMapWidth) * 4;
  32894. var r = buffer[pos] / 255.0;
  32895. var g = buffer[pos + 1] / 255.0;
  32896. var b = buffer[pos + 2] / 255.0;
  32897. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32898. normal.normalize();
  32899. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32900. position = position.add(normal);
  32901. position.toArray(positions, index);
  32902. }
  32903. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32904. if (forceUpdate) {
  32905. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32906. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32907. }
  32908. else {
  32909. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32910. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32911. }
  32912. return this;
  32913. };
  32914. /**
  32915. * Modify the mesh to get a flat shading rendering.
  32916. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32917. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32918. * @returns current mesh
  32919. */
  32920. Mesh.prototype.convertToFlatShadedMesh = function () {
  32921. var kinds = this.getVerticesDataKinds();
  32922. var vbs = {};
  32923. var data = {};
  32924. var newdata = {};
  32925. var updatableNormals = false;
  32926. var kindIndex;
  32927. var kind;
  32928. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32929. kind = kinds[kindIndex];
  32930. var vertexBuffer = this.getVertexBuffer(kind);
  32931. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32932. updatableNormals = vertexBuffer.isUpdatable();
  32933. kinds.splice(kindIndex, 1);
  32934. kindIndex--;
  32935. continue;
  32936. }
  32937. vbs[kind] = vertexBuffer;
  32938. data[kind] = vbs[kind].getData();
  32939. newdata[kind] = [];
  32940. }
  32941. // Save previous submeshes
  32942. var previousSubmeshes = this.subMeshes.slice(0);
  32943. var indices = this.getIndices();
  32944. var totalIndices = this.getTotalIndices();
  32945. // Generating unique vertices per face
  32946. var index;
  32947. for (index = 0; index < totalIndices; index++) {
  32948. var vertexIndex = indices[index];
  32949. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32950. kind = kinds[kindIndex];
  32951. var stride = vbs[kind].getStrideSize();
  32952. for (var offset = 0; offset < stride; offset++) {
  32953. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32954. }
  32955. }
  32956. }
  32957. // Updating faces & normal
  32958. var normals = [];
  32959. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32960. for (index = 0; index < totalIndices; index += 3) {
  32961. indices[index] = index;
  32962. indices[index + 1] = index + 1;
  32963. indices[index + 2] = index + 2;
  32964. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32965. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32966. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32967. var p1p2 = p1.subtract(p2);
  32968. var p3p2 = p3.subtract(p2);
  32969. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32970. // Store same normals for every vertex
  32971. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32972. normals.push(normal.x);
  32973. normals.push(normal.y);
  32974. normals.push(normal.z);
  32975. }
  32976. }
  32977. this.setIndices(indices);
  32978. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32979. // Updating vertex buffers
  32980. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32981. kind = kinds[kindIndex];
  32982. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32983. }
  32984. // Updating submeshes
  32985. this.releaseSubMeshes();
  32986. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32987. var previousOne = previousSubmeshes[submeshIndex];
  32988. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32989. }
  32990. this.synchronizeInstances();
  32991. return this;
  32992. };
  32993. /**
  32994. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32995. * In other words, more vertices, no more indices and a single bigger VBO.
  32996. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32997. * @returns current mesh
  32998. */
  32999. Mesh.prototype.convertToUnIndexedMesh = function () {
  33000. var kinds = this.getVerticesDataKinds();
  33001. var vbs = {};
  33002. var data = {};
  33003. var newdata = {};
  33004. var kindIndex;
  33005. var kind;
  33006. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33007. kind = kinds[kindIndex];
  33008. var vertexBuffer = this.getVertexBuffer(kind);
  33009. vbs[kind] = vertexBuffer;
  33010. data[kind] = vbs[kind].getData();
  33011. newdata[kind] = [];
  33012. }
  33013. // Save previous submeshes
  33014. var previousSubmeshes = this.subMeshes.slice(0);
  33015. var indices = this.getIndices();
  33016. var totalIndices = this.getTotalIndices();
  33017. // Generating unique vertices per face
  33018. var index;
  33019. for (index = 0; index < totalIndices; index++) {
  33020. var vertexIndex = indices[index];
  33021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33022. kind = kinds[kindIndex];
  33023. var stride = vbs[kind].getStrideSize();
  33024. for (var offset = 0; offset < stride; offset++) {
  33025. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33026. }
  33027. }
  33028. }
  33029. // Updating indices
  33030. for (index = 0; index < totalIndices; index += 3) {
  33031. indices[index] = index;
  33032. indices[index + 1] = index + 1;
  33033. indices[index + 2] = index + 2;
  33034. }
  33035. this.setIndices(indices);
  33036. // Updating vertex buffers
  33037. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33038. kind = kinds[kindIndex];
  33039. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33040. }
  33041. // Updating submeshes
  33042. this.releaseSubMeshes();
  33043. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33044. var previousOne = previousSubmeshes[submeshIndex];
  33045. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33046. }
  33047. this._unIndexed = true;
  33048. this.synchronizeInstances();
  33049. return this;
  33050. };
  33051. /**
  33052. * Inverses facet orientations.
  33053. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33054. * @param flipNormals will also inverts the normals
  33055. * @returns current mesh
  33056. */
  33057. Mesh.prototype.flipFaces = function (flipNormals) {
  33058. if (flipNormals === void 0) { flipNormals = false; }
  33059. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33060. var i;
  33061. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33062. for (i = 0; i < vertex_data.normals.length; i++) {
  33063. vertex_data.normals[i] *= -1;
  33064. }
  33065. }
  33066. if (vertex_data.indices) {
  33067. var temp;
  33068. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33069. // reassign indices
  33070. temp = vertex_data.indices[i + 1];
  33071. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33072. vertex_data.indices[i + 2] = temp;
  33073. }
  33074. }
  33075. vertex_data.applyToMesh(this);
  33076. return this;
  33077. };
  33078. // Instances
  33079. /**
  33080. * Creates a new InstancedMesh object from the mesh model.
  33081. * Warning : this method is not supported for Line mesh and LineSystem
  33082. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33083. * @param name defines the name of the new instance
  33084. * @returns a new InstancedMesh
  33085. */
  33086. Mesh.prototype.createInstance = function (name) {
  33087. return new BABYLON.InstancedMesh(name, this);
  33088. };
  33089. /**
  33090. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33091. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33092. * @returns the current mesh
  33093. */
  33094. Mesh.prototype.synchronizeInstances = function () {
  33095. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33096. var instance = this.instances[instanceIndex];
  33097. instance._syncSubMeshes();
  33098. }
  33099. return this;
  33100. };
  33101. /**
  33102. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33103. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33104. * This should be used together with the simplification to avoid disappearing triangles.
  33105. * @param successCallback an optional success callback to be called after the optimization finished.
  33106. * @returns the current mesh
  33107. */
  33108. Mesh.prototype.optimizeIndices = function (successCallback) {
  33109. var _this = this;
  33110. var indices = this.getIndices();
  33111. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33112. if (!positions || !indices) {
  33113. return this;
  33114. }
  33115. var vectorPositions = new Array();
  33116. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33117. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33118. }
  33119. var dupes = new Array();
  33120. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33121. var realPos = vectorPositions.length - 1 - iteration;
  33122. var testedPosition = vectorPositions[realPos];
  33123. for (var j = 0; j < realPos; ++j) {
  33124. var againstPosition = vectorPositions[j];
  33125. if (testedPosition.equals(againstPosition)) {
  33126. dupes[realPos] = j;
  33127. break;
  33128. }
  33129. }
  33130. }, function () {
  33131. for (var i = 0; i < indices.length; ++i) {
  33132. indices[i] = dupes[indices[i]] || indices[i];
  33133. }
  33134. //indices are now reordered
  33135. var originalSubMeshes = _this.subMeshes.slice(0);
  33136. _this.setIndices(indices);
  33137. _this.subMeshes = originalSubMeshes;
  33138. if (successCallback) {
  33139. successCallback(_this);
  33140. }
  33141. });
  33142. return this;
  33143. };
  33144. /**
  33145. * Serialize current mesh
  33146. * @param serializationObject defines the object which will receive the serialization data
  33147. */
  33148. Mesh.prototype.serialize = function (serializationObject) {
  33149. serializationObject.name = this.name;
  33150. serializationObject.id = this.id;
  33151. serializationObject.type = this.getClassName();
  33152. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33153. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33154. }
  33155. serializationObject.position = this.position.asArray();
  33156. if (this.rotationQuaternion) {
  33157. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33158. }
  33159. else if (this.rotation) {
  33160. serializationObject.rotation = this.rotation.asArray();
  33161. }
  33162. serializationObject.scaling = this.scaling.asArray();
  33163. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33164. serializationObject.isEnabled = this.isEnabled(false);
  33165. serializationObject.isVisible = this.isVisible;
  33166. serializationObject.infiniteDistance = this.infiniteDistance;
  33167. serializationObject.pickable = this.isPickable;
  33168. serializationObject.receiveShadows = this.receiveShadows;
  33169. serializationObject.billboardMode = this.billboardMode;
  33170. serializationObject.visibility = this.visibility;
  33171. serializationObject.checkCollisions = this.checkCollisions;
  33172. serializationObject.isBlocker = this.isBlocker;
  33173. // Parent
  33174. if (this.parent) {
  33175. serializationObject.parentId = this.parent.id;
  33176. }
  33177. // Geometry
  33178. serializationObject.isUnIndexed = this.isUnIndexed;
  33179. var geometry = this._geometry;
  33180. if (geometry) {
  33181. var geometryId = geometry.id;
  33182. serializationObject.geometryId = geometryId;
  33183. // SubMeshes
  33184. serializationObject.subMeshes = [];
  33185. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33186. var subMesh = this.subMeshes[subIndex];
  33187. serializationObject.subMeshes.push({
  33188. materialIndex: subMesh.materialIndex,
  33189. verticesStart: subMesh.verticesStart,
  33190. verticesCount: subMesh.verticesCount,
  33191. indexStart: subMesh.indexStart,
  33192. indexCount: subMesh.indexCount
  33193. });
  33194. }
  33195. }
  33196. // Material
  33197. if (this.material) {
  33198. serializationObject.materialId = this.material.id;
  33199. }
  33200. else {
  33201. this.material = null;
  33202. }
  33203. // Morph targets
  33204. if (this.morphTargetManager) {
  33205. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33206. }
  33207. // Skeleton
  33208. if (this.skeleton) {
  33209. serializationObject.skeletonId = this.skeleton.id;
  33210. }
  33211. // Physics
  33212. //TODO implement correct serialization for physics impostors.
  33213. var impostor = this.getPhysicsImpostor();
  33214. if (impostor) {
  33215. serializationObject.physicsMass = impostor.getParam("mass");
  33216. serializationObject.physicsFriction = impostor.getParam("friction");
  33217. serializationObject.physicsRestitution = impostor.getParam("mass");
  33218. serializationObject.physicsImpostor = impostor.type;
  33219. }
  33220. // Metadata
  33221. if (this.metadata) {
  33222. serializationObject.metadata = this.metadata;
  33223. }
  33224. // Instances
  33225. serializationObject.instances = [];
  33226. for (var index = 0; index < this.instances.length; index++) {
  33227. var instance = this.instances[index];
  33228. if (instance.doNotSerialize) {
  33229. continue;
  33230. }
  33231. var serializationInstance = {
  33232. name: instance.name,
  33233. id: instance.id,
  33234. position: instance.position.asArray(),
  33235. scaling: instance.scaling.asArray()
  33236. };
  33237. if (instance.parent) {
  33238. serializationInstance.parentId = instance.parent.id;
  33239. }
  33240. if (instance.rotationQuaternion) {
  33241. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33242. }
  33243. else if (instance.rotation) {
  33244. serializationInstance.rotation = instance.rotation.asArray();
  33245. }
  33246. serializationObject.instances.push(serializationInstance);
  33247. // Animations
  33248. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33249. serializationInstance.ranges = instance.serializeAnimationRanges();
  33250. }
  33251. //
  33252. // Animations
  33253. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33254. serializationObject.ranges = this.serializeAnimationRanges();
  33255. // Layer mask
  33256. serializationObject.layerMask = this.layerMask;
  33257. // Alpha
  33258. serializationObject.alphaIndex = this.alphaIndex;
  33259. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33260. // Overlay
  33261. serializationObject.overlayAlpha = this.overlayAlpha;
  33262. serializationObject.overlayColor = this.overlayColor.asArray();
  33263. serializationObject.renderOverlay = this.renderOverlay;
  33264. // Fog
  33265. serializationObject.applyFog = this.applyFog;
  33266. // Action Manager
  33267. if (this.actionManager) {
  33268. serializationObject.actions = this.actionManager.serialize(this.name);
  33269. }
  33270. };
  33271. /** @hidden */
  33272. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33273. if (!this.geometry) {
  33274. return;
  33275. }
  33276. this._markSubMeshesAsAttributesDirty();
  33277. var morphTargetManager = this._morphTargetManager;
  33278. if (morphTargetManager && morphTargetManager.vertexCount) {
  33279. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33280. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33281. this.morphTargetManager = null;
  33282. return;
  33283. }
  33284. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33285. var morphTarget = morphTargetManager.getActiveTarget(index);
  33286. var positions = morphTarget.getPositions();
  33287. if (!positions) {
  33288. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33289. return;
  33290. }
  33291. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33292. var normals = morphTarget.getNormals();
  33293. if (normals) {
  33294. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33295. }
  33296. var tangents = morphTarget.getTangents();
  33297. if (tangents) {
  33298. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33299. }
  33300. }
  33301. }
  33302. else {
  33303. var index = 0;
  33304. // Positions
  33305. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33306. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33307. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33308. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33309. }
  33310. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33311. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33312. }
  33313. index++;
  33314. }
  33315. }
  33316. };
  33317. // Statics
  33318. /**
  33319. * Returns a new Mesh object parsed from the source provided.
  33320. * @param parsedMesh is the source
  33321. * @param scene defines the hosting scene
  33322. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33323. * @returns a new Mesh
  33324. */
  33325. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33326. var mesh;
  33327. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33328. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33329. }
  33330. else {
  33331. mesh = new Mesh(parsedMesh.name, scene);
  33332. }
  33333. mesh.id = parsedMesh.id;
  33334. if (BABYLON.Tags) {
  33335. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33336. }
  33337. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33338. if (parsedMesh.metadata !== undefined) {
  33339. mesh.metadata = parsedMesh.metadata;
  33340. }
  33341. if (parsedMesh.rotationQuaternion) {
  33342. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33343. }
  33344. else if (parsedMesh.rotation) {
  33345. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33346. }
  33347. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33348. if (parsedMesh.localMatrix) {
  33349. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33350. }
  33351. else if (parsedMesh.pivotMatrix) {
  33352. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33353. }
  33354. mesh.setEnabled(parsedMesh.isEnabled);
  33355. mesh.isVisible = parsedMesh.isVisible;
  33356. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33357. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33358. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33359. if (parsedMesh.applyFog !== undefined) {
  33360. mesh.applyFog = parsedMesh.applyFog;
  33361. }
  33362. if (parsedMesh.pickable !== undefined) {
  33363. mesh.isPickable = parsedMesh.pickable;
  33364. }
  33365. if (parsedMesh.alphaIndex !== undefined) {
  33366. mesh.alphaIndex = parsedMesh.alphaIndex;
  33367. }
  33368. mesh.receiveShadows = parsedMesh.receiveShadows;
  33369. mesh.billboardMode = parsedMesh.billboardMode;
  33370. if (parsedMesh.visibility !== undefined) {
  33371. mesh.visibility = parsedMesh.visibility;
  33372. }
  33373. mesh.checkCollisions = parsedMesh.checkCollisions;
  33374. if (parsedMesh.isBlocker !== undefined) {
  33375. mesh.isBlocker = parsedMesh.isBlocker;
  33376. }
  33377. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33378. // freezeWorldMatrix
  33379. if (parsedMesh.freezeWorldMatrix) {
  33380. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33381. }
  33382. // Parent
  33383. if (parsedMesh.parentId) {
  33384. mesh._waitingParentId = parsedMesh.parentId;
  33385. }
  33386. // Actions
  33387. if (parsedMesh.actions !== undefined) {
  33388. mesh._waitingActions = parsedMesh.actions;
  33389. }
  33390. // Overlay
  33391. if (parsedMesh.overlayAlpha !== undefined) {
  33392. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33393. }
  33394. if (parsedMesh.overlayColor !== undefined) {
  33395. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33396. }
  33397. if (parsedMesh.renderOverlay !== undefined) {
  33398. mesh.renderOverlay = parsedMesh.renderOverlay;
  33399. }
  33400. // Geometry
  33401. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33402. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33403. if (parsedMesh.delayLoadingFile) {
  33404. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33405. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33406. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33407. if (parsedMesh._binaryInfo) {
  33408. mesh._binaryInfo = parsedMesh._binaryInfo;
  33409. }
  33410. mesh._delayInfo = [];
  33411. if (parsedMesh.hasUVs) {
  33412. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33413. }
  33414. if (parsedMesh.hasUVs2) {
  33415. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33416. }
  33417. if (parsedMesh.hasUVs3) {
  33418. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33419. }
  33420. if (parsedMesh.hasUVs4) {
  33421. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33422. }
  33423. if (parsedMesh.hasUVs5) {
  33424. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33425. }
  33426. if (parsedMesh.hasUVs6) {
  33427. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33428. }
  33429. if (parsedMesh.hasColors) {
  33430. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33431. }
  33432. if (parsedMesh.hasMatricesIndices) {
  33433. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33434. }
  33435. if (parsedMesh.hasMatricesWeights) {
  33436. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33437. }
  33438. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33439. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33440. mesh._checkDelayState();
  33441. }
  33442. }
  33443. else {
  33444. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33445. }
  33446. // Material
  33447. if (parsedMesh.materialId) {
  33448. mesh.setMaterialByID(parsedMesh.materialId);
  33449. }
  33450. else {
  33451. mesh.material = null;
  33452. }
  33453. // Morph targets
  33454. if (parsedMesh.morphTargetManagerId > -1) {
  33455. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33456. }
  33457. // Skeleton
  33458. if (parsedMesh.skeletonId > -1) {
  33459. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33460. if (parsedMesh.numBoneInfluencers) {
  33461. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33462. }
  33463. }
  33464. // Animations
  33465. if (parsedMesh.animations) {
  33466. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33467. var parsedAnimation = parsedMesh.animations[animationIndex];
  33468. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33469. }
  33470. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33471. }
  33472. if (parsedMesh.autoAnimate) {
  33473. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33474. }
  33475. // Layer Mask
  33476. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33477. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33478. }
  33479. else {
  33480. mesh.layerMask = 0x0FFFFFFF;
  33481. }
  33482. // Physics
  33483. if (parsedMesh.physicsImpostor) {
  33484. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33485. mass: parsedMesh.physicsMass,
  33486. friction: parsedMesh.physicsFriction,
  33487. restitution: parsedMesh.physicsRestitution
  33488. }, scene);
  33489. }
  33490. // Instances
  33491. if (parsedMesh.instances) {
  33492. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33493. var parsedInstance = parsedMesh.instances[index];
  33494. var instance = mesh.createInstance(parsedInstance.name);
  33495. if (parsedInstance.id) {
  33496. instance.id = parsedInstance.id;
  33497. }
  33498. if (BABYLON.Tags) {
  33499. if (parsedInstance.tags) {
  33500. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33501. }
  33502. else {
  33503. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33504. }
  33505. }
  33506. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33507. if (parsedInstance.parentId) {
  33508. instance._waitingParentId = parsedInstance.parentId;
  33509. }
  33510. if (parsedInstance.rotationQuaternion) {
  33511. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33512. }
  33513. else if (parsedInstance.rotation) {
  33514. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33515. }
  33516. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33517. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33518. instance.checkCollisions = parsedInstance.checkCollisions;
  33519. }
  33520. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33521. instance.isPickable = parsedInstance.pickable;
  33522. }
  33523. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33524. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33525. }
  33526. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33527. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33528. }
  33529. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33530. instance.alphaIndex = parsedInstance.alphaIndex;
  33531. }
  33532. // Physics
  33533. if (parsedInstance.physicsImpostor) {
  33534. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33535. mass: parsedInstance.physicsMass,
  33536. friction: parsedInstance.physicsFriction,
  33537. restitution: parsedInstance.physicsRestitution
  33538. }, scene);
  33539. }
  33540. // Animation
  33541. if (parsedInstance.animations) {
  33542. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33543. parsedAnimation = parsedInstance.animations[animationIndex];
  33544. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33545. }
  33546. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33547. if (parsedInstance.autoAnimate) {
  33548. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33549. }
  33550. }
  33551. }
  33552. }
  33553. return mesh;
  33554. };
  33555. /**
  33556. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33557. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33558. * @param name defines the name of the mesh to create
  33559. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33560. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33561. * @param closePath creates a seam between the first and the last points of each path of the path array
  33562. * @param offset is taken in account only if the `pathArray` is containing a single path
  33563. * @param scene defines the hosting scene
  33564. * @param updatable defines if the mesh must be flagged as updatable
  33565. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33566. * @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)
  33567. * @returns a new Mesh
  33568. */
  33569. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33570. if (closeArray === void 0) { closeArray = false; }
  33571. if (updatable === void 0) { updatable = false; }
  33572. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33573. pathArray: pathArray,
  33574. closeArray: closeArray,
  33575. closePath: closePath,
  33576. offset: offset,
  33577. updatable: updatable,
  33578. sideOrientation: sideOrientation,
  33579. instance: instance
  33580. }, scene);
  33581. };
  33582. /**
  33583. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33584. * @param name defines the name of the mesh to create
  33585. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33586. * @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
  33587. * @param scene defines the hosting scene
  33588. * @param updatable defines if the mesh must be flagged as updatable
  33589. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33590. * @returns a new Mesh
  33591. */
  33592. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33593. if (scene === void 0) { scene = null; }
  33594. var options = {
  33595. radius: radius,
  33596. tessellation: tessellation,
  33597. sideOrientation: sideOrientation,
  33598. updatable: updatable
  33599. };
  33600. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33601. };
  33602. /**
  33603. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33604. * @param name defines the name of the mesh to create
  33605. * @param size sets the size (float) of each box side (default 1)
  33606. * @param scene defines the hosting scene
  33607. * @param updatable defines if the mesh must be flagged as updatable
  33608. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33609. * @returns a new Mesh
  33610. */
  33611. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33612. if (scene === void 0) { scene = null; }
  33613. var options = {
  33614. size: size,
  33615. sideOrientation: sideOrientation,
  33616. updatable: updatable
  33617. };
  33618. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33619. };
  33620. /**
  33621. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33622. * @param name defines the name of the mesh to create
  33623. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33624. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33625. * @param scene defines the hosting scene
  33626. * @param updatable defines if the mesh must be flagged as updatable
  33627. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33628. * @returns a new Mesh
  33629. */
  33630. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33631. var options = {
  33632. segments: segments,
  33633. diameterX: diameter,
  33634. diameterY: diameter,
  33635. diameterZ: diameter,
  33636. sideOrientation: sideOrientation,
  33637. updatable: updatable
  33638. };
  33639. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33640. };
  33641. /**
  33642. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33643. * @param name defines the name of the mesh to create
  33644. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33645. * @param diameterTop set the top cap diameter (floats, default 1)
  33646. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33647. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33648. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33649. * @param scene defines the hosting scene
  33650. * @param updatable defines if the mesh must be flagged as updatable
  33651. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33652. * @returns a new Mesh
  33653. */
  33654. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33655. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33656. if (scene !== undefined) {
  33657. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33658. updatable = scene;
  33659. }
  33660. scene = subdivisions;
  33661. subdivisions = 1;
  33662. }
  33663. var options = {
  33664. height: height,
  33665. diameterTop: diameterTop,
  33666. diameterBottom: diameterBottom,
  33667. tessellation: tessellation,
  33668. subdivisions: subdivisions,
  33669. sideOrientation: sideOrientation,
  33670. updatable: updatable
  33671. };
  33672. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33673. };
  33674. // Torus (Code from SharpDX.org)
  33675. /**
  33676. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33677. * @param name defines the name of the mesh to create
  33678. * @param diameter sets the diameter size (float) of the torus (default 1)
  33679. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33680. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33681. * @param scene defines the hosting scene
  33682. * @param updatable defines if the mesh must be flagged as updatable
  33683. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33684. * @returns a new Mesh
  33685. */
  33686. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33687. var options = {
  33688. diameter: diameter,
  33689. thickness: thickness,
  33690. tessellation: tessellation,
  33691. sideOrientation: sideOrientation,
  33692. updatable: updatable
  33693. };
  33694. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33695. };
  33696. /**
  33697. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33698. * @param name defines the name of the mesh to create
  33699. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33700. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33701. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  33702. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  33703. * @param p the number of windings on X axis (positive integers, default 2)
  33704. * @param q the number of windings on Y axis (positive integers, default 3)
  33705. * @param scene defines the hosting scene
  33706. * @param updatable defines if the mesh must be flagged as updatable
  33707. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33708. * @returns a new Mesh
  33709. */
  33710. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33711. var options = {
  33712. radius: radius,
  33713. tube: tube,
  33714. radialSegments: radialSegments,
  33715. tubularSegments: tubularSegments,
  33716. p: p,
  33717. q: q,
  33718. sideOrientation: sideOrientation,
  33719. updatable: updatable
  33720. };
  33721. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33722. };
  33723. /**
  33724. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  33725. * @param name defines the name of the mesh to create
  33726. * @param points is an array successive Vector3
  33727. * @param scene defines the hosting scene
  33728. * @param updatable defines if the mesh must be flagged as updatable
  33729. * @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).
  33730. * @returns a new Mesh
  33731. */
  33732. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33733. if (scene === void 0) { scene = null; }
  33734. if (updatable === void 0) { updatable = false; }
  33735. if (instance === void 0) { instance = null; }
  33736. var options = {
  33737. points: points,
  33738. updatable: updatable,
  33739. instance: instance
  33740. };
  33741. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33742. };
  33743. /**
  33744. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  33745. * @param name defines the name of the mesh to create
  33746. * @param points is an array successive Vector3
  33747. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  33748. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  33749. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  33750. * @param scene defines the hosting scene
  33751. * @param updatable defines if the mesh must be flagged as updatable
  33752. * @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)
  33753. * @returns a new Mesh
  33754. */
  33755. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33756. if (scene === void 0) { scene = null; }
  33757. var options = {
  33758. points: points,
  33759. dashSize: dashSize,
  33760. gapSize: gapSize,
  33761. dashNb: dashNb,
  33762. updatable: updatable,
  33763. instance: instance
  33764. };
  33765. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33766. };
  33767. /**
  33768. * Creates a polygon mesh.
  33769. * Please consider using the same method from the MeshBuilder class instead.
  33770. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33771. * 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.
  33772. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33773. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33774. * Remember you can only change the shape positions, not their number when updating a polygon.
  33775. */
  33776. /**
  33777. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  33778. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  33779. * @param name defines the name of the mesh to create
  33780. * @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
  33781. * @param scene defines the hosting scene
  33782. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33783. * @param updatable defines if the mesh must be flagged as updatable
  33784. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33785. * @returns a new Mesh
  33786. */
  33787. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33788. var options = {
  33789. shape: shape,
  33790. holes: holes,
  33791. updatable: updatable,
  33792. sideOrientation: sideOrientation
  33793. };
  33794. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33795. };
  33796. /**
  33797. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  33798. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  33799. * @param name defines the name of the mesh to create
  33800. * @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
  33801. * @param depth defines the height of extrusion
  33802. * @param scene defines the hosting scene
  33803. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33804. * @param updatable defines if the mesh must be flagged as updatable
  33805. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33806. * @returns a new Mesh
  33807. */
  33808. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33809. var options = {
  33810. shape: shape,
  33811. holes: holes,
  33812. depth: depth,
  33813. updatable: updatable,
  33814. sideOrientation: sideOrientation
  33815. };
  33816. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33817. };
  33818. /**
  33819. * Creates an extruded shape mesh.
  33820. * 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
  33821. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33822. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33823. * @param name defines the name of the mesh to create
  33824. * @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
  33825. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33826. * @param scale is the value to scale the shape
  33827. * @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
  33828. * @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
  33829. * @param scene defines the hosting scene
  33830. * @param updatable defines if the mesh must be flagged as updatable
  33831. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33832. * @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)
  33833. * @returns a new Mesh
  33834. */
  33835. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33836. if (scene === void 0) { scene = null; }
  33837. var options = {
  33838. shape: shape,
  33839. path: path,
  33840. scale: scale,
  33841. rotation: rotation,
  33842. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33843. sideOrientation: sideOrientation,
  33844. instance: instance,
  33845. updatable: updatable
  33846. };
  33847. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33848. };
  33849. /**
  33850. * Creates an custom extruded shape mesh.
  33851. * The custom extrusion is a parametric shape.
  33852. * It has no predefined shape. Its final shape will depend on the input parameters.
  33853. * Please consider using the same method from the MeshBuilder class instead
  33854. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33855. * @param name defines the name of the mesh to create
  33856. * @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
  33857. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33858. * @param scaleFunction is a custom Javascript function called on each path point
  33859. * @param rotationFunction is a custom Javascript function called on each path point
  33860. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  33861. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  33862. * @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
  33863. * @param scene defines the hosting scene
  33864. * @param updatable defines if the mesh must be flagged as updatable
  33865. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33866. * @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)
  33867. * @returns a new Mesh
  33868. */
  33869. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33870. var options = {
  33871. shape: shape,
  33872. path: path,
  33873. scaleFunction: scaleFunction,
  33874. rotationFunction: rotationFunction,
  33875. ribbonCloseArray: ribbonCloseArray,
  33876. ribbonClosePath: ribbonClosePath,
  33877. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33878. sideOrientation: sideOrientation,
  33879. instance: instance,
  33880. updatable: updatable
  33881. };
  33882. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33883. };
  33884. /**
  33885. * Creates lathe mesh.
  33886. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33887. * Please consider using the same method from the MeshBuilder class instead
  33888. * @param name defines the name of the mesh to create
  33889. * @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
  33890. * @param radius is the radius value of the lathe
  33891. * @param tessellation is the side number of the lathe.
  33892. * @param scene defines the hosting scene
  33893. * @param updatable defines if the mesh must be flagged as updatable
  33894. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33895. * @returns a new Mesh
  33896. */
  33897. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33898. var options = {
  33899. shape: shape,
  33900. radius: radius,
  33901. tessellation: tessellation,
  33902. sideOrientation: sideOrientation,
  33903. updatable: updatable
  33904. };
  33905. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33906. };
  33907. /**
  33908. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  33909. * @param name defines the name of the mesh to create
  33910. * @param size sets the size (float) of both sides of the plane at once (default 1)
  33911. * @param scene defines the hosting scene
  33912. * @param updatable defines if the mesh must be flagged as updatable
  33913. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33914. * @returns a new Mesh
  33915. */
  33916. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33917. var options = {
  33918. size: size,
  33919. width: size,
  33920. height: size,
  33921. sideOrientation: sideOrientation,
  33922. updatable: updatable
  33923. };
  33924. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33925. };
  33926. /**
  33927. * Creates a ground mesh.
  33928. * Please consider using the same method from the MeshBuilder class instead
  33929. * @param name defines the name of the mesh to create
  33930. * @param width set the width of the ground
  33931. * @param height set the height of the ground
  33932. * @param subdivisions sets the number of subdivisions per side
  33933. * @param scene defines the hosting scene
  33934. * @param updatable defines if the mesh must be flagged as updatable
  33935. * @returns a new Mesh
  33936. */
  33937. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33938. var options = {
  33939. width: width,
  33940. height: height,
  33941. subdivisions: subdivisions,
  33942. updatable: updatable
  33943. };
  33944. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33945. };
  33946. /**
  33947. * Creates a tiled ground mesh.
  33948. * Please consider using the same method from the MeshBuilder class instead
  33949. * @param name defines the name of the mesh to create
  33950. * @param xmin set the ground minimum X coordinate
  33951. * @param zmin set the ground minimum Y coordinate
  33952. * @param xmax set the ground maximum X coordinate
  33953. * @param zmax set the ground maximum Z coordinate
  33954. * @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
  33955. * @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
  33956. * @param scene defines the hosting scene
  33957. * @param updatable defines if the mesh must be flagged as updatable
  33958. * @returns a new Mesh
  33959. */
  33960. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33961. var options = {
  33962. xmin: xmin,
  33963. zmin: zmin,
  33964. xmax: xmax,
  33965. zmax: zmax,
  33966. subdivisions: subdivisions,
  33967. precision: precision,
  33968. updatable: updatable
  33969. };
  33970. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33971. };
  33972. /**
  33973. * Creates a ground mesh from a height map.
  33974. * Please consider using the same method from the MeshBuilder class instead
  33975. * @see http://doc.babylonjs.com/babylon101/height_map
  33976. * @param name defines the name of the mesh to create
  33977. * @param url sets the URL of the height map image resource
  33978. * @param width set the ground width size
  33979. * @param height set the ground height size
  33980. * @param subdivisions sets the number of subdivision per side
  33981. * @param minHeight is the minimum altitude on the ground
  33982. * @param maxHeight is the maximum altitude on the ground
  33983. * @param scene defines the hosting scene
  33984. * @param updatable defines if the mesh must be flagged as updatable
  33985. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  33986. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  33987. * @returns a new Mesh
  33988. */
  33989. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33990. var options = {
  33991. width: width,
  33992. height: height,
  33993. subdivisions: subdivisions,
  33994. minHeight: minHeight,
  33995. maxHeight: maxHeight,
  33996. updatable: updatable,
  33997. onReady: onReady,
  33998. alphaFilter: alphaFilter
  33999. };
  34000. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34001. };
  34002. /**
  34003. * Creates a tube mesh.
  34004. * The tube is a parametric shape.
  34005. * It has no predefined shape. Its final shape will depend on the input parameters.
  34006. * Please consider using the same method from the MeshBuilder class instead
  34007. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34008. * @param name defines the name of the mesh to create
  34009. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  34010. * @param radius sets the tube radius size
  34011. * @param tessellation is the number of sides on the tubular surface
  34012. * @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
  34013. * @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
  34014. * @param scene defines the hosting scene
  34015. * @param updatable defines if the mesh must be flagged as updatable
  34016. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34017. * @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)
  34018. * @returns a new Mesh
  34019. */
  34020. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34021. var options = {
  34022. path: path,
  34023. radius: radius,
  34024. tessellation: tessellation,
  34025. radiusFunction: radiusFunction,
  34026. arc: 1,
  34027. cap: cap,
  34028. updatable: updatable,
  34029. sideOrientation: sideOrientation,
  34030. instance: instance
  34031. };
  34032. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34033. };
  34034. /**
  34035. * Creates a polyhedron mesh.
  34036. * Please consider using the same method from the MeshBuilder class instead.
  34037. * * 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
  34038. * * The parameter `size` (positive float, default 1) sets the polygon size
  34039. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  34040. * * 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`
  34041. * * 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
  34042. * * 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)`)
  34043. * * 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
  34044. * * 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
  34045. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34046. * * 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
  34047. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34048. * @param name defines the name of the mesh to create
  34049. * @param options defines the options used to create the mesh
  34050. * @param scene defines the hosting scene
  34051. * @returns a new Mesh
  34052. */
  34053. Mesh.CreatePolyhedron = function (name, options, scene) {
  34054. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34055. };
  34056. /**
  34057. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  34058. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  34059. * * 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`)
  34060. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  34061. * * 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
  34062. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34063. * * 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
  34064. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34065. * @param name defines the name of the mesh
  34066. * @param options defines the options used to create the mesh
  34067. * @param scene defines the hosting scene
  34068. * @returns a new Mesh
  34069. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  34070. */
  34071. Mesh.CreateIcoSphere = function (name, options, scene) {
  34072. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34073. };
  34074. /**
  34075. * Creates a decal mesh.
  34076. * Please consider using the same method from the MeshBuilder class instead.
  34077. * A decal is a mesh usually applied as a model onto the surface of another mesh
  34078. * @param name defines the name of the mesh
  34079. * @param sourceMesh defines the mesh receiving the decal
  34080. * @param position sets the position of the decal in world coordinates
  34081. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  34082. * @param size sets the decal scaling
  34083. * @param angle sets the angle to rotate the decal
  34084. * @returns a new Mesh
  34085. */
  34086. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34087. var options = {
  34088. position: position,
  34089. normal: normal,
  34090. size: size,
  34091. angle: angle
  34092. };
  34093. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34094. };
  34095. // Skeletons
  34096. /**
  34097. * Prepare internal position array for software CPU skinning
  34098. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  34099. */
  34100. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34101. if (!this._sourcePositions) {
  34102. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34103. if (!source) {
  34104. return this._sourcePositions;
  34105. }
  34106. this._sourcePositions = new Float32Array(source);
  34107. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34108. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34109. }
  34110. }
  34111. return this._sourcePositions;
  34112. };
  34113. /**
  34114. * Prepare internal normal array for software CPU skinning
  34115. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34116. */
  34117. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34118. if (!this._sourceNormals) {
  34119. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34120. if (!source) {
  34121. return this._sourceNormals;
  34122. }
  34123. this._sourceNormals = new Float32Array(source);
  34124. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34125. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34126. }
  34127. }
  34128. return this._sourceNormals;
  34129. };
  34130. /**
  34131. * Updates the vertex buffer by applying transformation from the bones
  34132. * @param skeleton defines the skeleton to apply to current mesh
  34133. * @returns the current mesh
  34134. */
  34135. Mesh.prototype.applySkeleton = function (skeleton) {
  34136. if (!this.geometry) {
  34137. return this;
  34138. }
  34139. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  34140. return this;
  34141. }
  34142. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  34143. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34144. return this;
  34145. }
  34146. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34147. return this;
  34148. }
  34149. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34150. return this;
  34151. }
  34152. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34153. return this;
  34154. }
  34155. if (!this._sourcePositions) {
  34156. var submeshes = this.subMeshes.slice();
  34157. this.setPositionsForCPUSkinning();
  34158. this.subMeshes = submeshes;
  34159. }
  34160. if (!this._sourceNormals) {
  34161. this.setNormalsForCPUSkinning();
  34162. }
  34163. // positionsData checks for not being Float32Array will only pass at most once
  34164. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34165. if (!positionsData) {
  34166. return this;
  34167. }
  34168. if (!(positionsData instanceof Float32Array)) {
  34169. positionsData = new Float32Array(positionsData);
  34170. }
  34171. // normalsData checks for not being Float32Array will only pass at most once
  34172. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34173. if (!normalsData) {
  34174. return this;
  34175. }
  34176. if (!(normalsData instanceof Float32Array)) {
  34177. normalsData = new Float32Array(normalsData);
  34178. }
  34179. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34180. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34181. if (!matricesWeightsData || !matricesIndicesData) {
  34182. return this;
  34183. }
  34184. var needExtras = this.numBoneInfluencers > 4;
  34185. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34186. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34187. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34188. var tempVector3 = BABYLON.Vector3.Zero();
  34189. var finalMatrix = new BABYLON.Matrix();
  34190. var tempMatrix = new BABYLON.Matrix();
  34191. var matWeightIdx = 0;
  34192. var inf;
  34193. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34194. var weight;
  34195. for (inf = 0; inf < 4; inf++) {
  34196. weight = matricesWeightsData[matWeightIdx + inf];
  34197. if (weight > 0) {
  34198. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34199. finalMatrix.addToSelf(tempMatrix);
  34200. }
  34201. }
  34202. if (needExtras) {
  34203. for (inf = 0; inf < 4; inf++) {
  34204. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34205. if (weight > 0) {
  34206. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34207. finalMatrix.addToSelf(tempMatrix);
  34208. }
  34209. }
  34210. }
  34211. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34212. tempVector3.toArray(positionsData, index);
  34213. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34214. tempVector3.toArray(normalsData, index);
  34215. finalMatrix.reset();
  34216. }
  34217. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34218. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34219. return this;
  34220. };
  34221. // Tools
  34222. /**
  34223. * 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
  34224. * @param meshes defines the list of meshes to scan
  34225. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34226. */
  34227. Mesh.MinMax = function (meshes) {
  34228. var minVector = null;
  34229. var maxVector = null;
  34230. meshes.forEach(function (mesh, index, array) {
  34231. var boundingInfo = mesh.getBoundingInfo();
  34232. var boundingBox = boundingInfo.boundingBox;
  34233. if (!minVector || !maxVector) {
  34234. minVector = boundingBox.minimumWorld;
  34235. maxVector = boundingBox.maximumWorld;
  34236. }
  34237. else {
  34238. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34239. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34240. }
  34241. });
  34242. if (!minVector || !maxVector) {
  34243. return {
  34244. min: BABYLON.Vector3.Zero(),
  34245. max: BABYLON.Vector3.Zero()
  34246. };
  34247. }
  34248. return {
  34249. min: minVector,
  34250. max: maxVector
  34251. };
  34252. };
  34253. /**
  34254. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34255. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34256. * @returns a vector3
  34257. */
  34258. Mesh.Center = function (meshesOrMinMaxVector) {
  34259. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34260. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34261. };
  34262. /**
  34263. * Merge the array of meshes into a single mesh for performance reasons.
  34264. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34265. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34266. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34267. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34268. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34269. * @returns a new mesh
  34270. */
  34271. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34272. if (disposeSource === void 0) { disposeSource = true; }
  34273. var index;
  34274. if (!allow32BitsIndices) {
  34275. var totalVertices = 0;
  34276. // Counting vertices
  34277. for (index = 0; index < meshes.length; index++) {
  34278. if (meshes[index]) {
  34279. totalVertices += meshes[index].getTotalVertices();
  34280. if (totalVertices > 65536) {
  34281. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34282. return null;
  34283. }
  34284. }
  34285. }
  34286. }
  34287. // Merge
  34288. var vertexData = null;
  34289. var otherVertexData;
  34290. var indiceArray = new Array();
  34291. var source = null;
  34292. for (index = 0; index < meshes.length; index++) {
  34293. if (meshes[index]) {
  34294. var wm = meshes[index].computeWorldMatrix(true);
  34295. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34296. otherVertexData.transform(wm);
  34297. if (vertexData) {
  34298. vertexData.merge(otherVertexData, allow32BitsIndices);
  34299. }
  34300. else {
  34301. vertexData = otherVertexData;
  34302. source = meshes[index];
  34303. }
  34304. if (subdivideWithSubMeshes) {
  34305. indiceArray.push(meshes[index].getTotalIndices());
  34306. }
  34307. }
  34308. }
  34309. source = source;
  34310. if (!meshSubclass) {
  34311. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34312. }
  34313. vertexData.applyToMesh(meshSubclass);
  34314. // Setting properties
  34315. meshSubclass.material = source.material;
  34316. meshSubclass.checkCollisions = source.checkCollisions;
  34317. // Cleaning
  34318. if (disposeSource) {
  34319. for (index = 0; index < meshes.length; index++) {
  34320. if (meshes[index]) {
  34321. meshes[index].dispose();
  34322. }
  34323. }
  34324. }
  34325. // Subdivide
  34326. if (subdivideWithSubMeshes) {
  34327. //-- removal of global submesh
  34328. meshSubclass.releaseSubMeshes();
  34329. index = 0;
  34330. var offset = 0;
  34331. //-- apply subdivision according to index table
  34332. while (index < indiceArray.length) {
  34333. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34334. offset += indiceArray[index];
  34335. index++;
  34336. }
  34337. }
  34338. return meshSubclass;
  34339. };
  34340. // Consts
  34341. /**
  34342. * Mesh side orientation : usually the external or front surface
  34343. */
  34344. Mesh.FRONTSIDE = 0;
  34345. /**
  34346. * Mesh side orientation : usually the internal or back surface
  34347. */
  34348. Mesh.BACKSIDE = 1;
  34349. /**
  34350. * Mesh side orientation : both internal and external or front and back surfaces
  34351. */
  34352. Mesh.DOUBLESIDE = 2;
  34353. /**
  34354. * Mesh side orientation : by default, `FRONTSIDE`
  34355. */
  34356. Mesh.DEFAULTSIDE = 0;
  34357. /**
  34358. * Mesh cap setting : no cap
  34359. */
  34360. Mesh.NO_CAP = 0;
  34361. /**
  34362. * Mesh cap setting : one cap at the beginning of the mesh
  34363. */
  34364. Mesh.CAP_START = 1;
  34365. /**
  34366. * Mesh cap setting : one cap at the end of the mesh
  34367. */
  34368. Mesh.CAP_END = 2;
  34369. /**
  34370. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34371. */
  34372. Mesh.CAP_ALL = 3;
  34373. return Mesh;
  34374. }(BABYLON.AbstractMesh));
  34375. BABYLON.Mesh = Mesh;
  34376. })(BABYLON || (BABYLON = {}));
  34377. //# sourceMappingURL=babylon.mesh.js.map
  34378. var BABYLON;
  34379. (function (BABYLON) {
  34380. /**
  34381. * Base class for submeshes
  34382. */
  34383. var BaseSubMesh = /** @class */ (function () {
  34384. function BaseSubMesh() {
  34385. }
  34386. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34387. /**
  34388. * Gets associated effect
  34389. */
  34390. get: function () {
  34391. return this._materialEffect;
  34392. },
  34393. enumerable: true,
  34394. configurable: true
  34395. });
  34396. /**
  34397. * Sets associated effect (effect used to render this submesh)
  34398. * @param effect defines the effect to associate with
  34399. * @param defines defines the set of defines used to compile this effect
  34400. */
  34401. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34402. if (defines === void 0) { defines = null; }
  34403. if (this._materialEffect === effect) {
  34404. if (!effect) {
  34405. this._materialDefines = null;
  34406. }
  34407. return;
  34408. }
  34409. this._materialDefines = defines;
  34410. this._materialEffect = effect;
  34411. };
  34412. return BaseSubMesh;
  34413. }());
  34414. BABYLON.BaseSubMesh = BaseSubMesh;
  34415. /**
  34416. * Defines a subdivision inside a mesh
  34417. */
  34418. var SubMesh = /** @class */ (function (_super) {
  34419. __extends(SubMesh, _super);
  34420. /**
  34421. * Creates a new submesh
  34422. * @param materialIndex defines the material index to use
  34423. * @param verticesStart defines vertex index start
  34424. * @param verticesCount defines vertices count
  34425. * @param indexStart defines index start
  34426. * @param indexCount defines indices count
  34427. * @param mesh defines the parent mesh
  34428. * @param renderingMesh defines an optional rendering mesh
  34429. * @param createBoundingBox defines if bounding box should be created for this submesh
  34430. */
  34431. function SubMesh(
  34432. /** the material index to use */
  34433. materialIndex,
  34434. /** vertex index start */
  34435. verticesStart,
  34436. /** vertices count */
  34437. verticesCount,
  34438. /** index start */
  34439. indexStart,
  34440. /** indices count */
  34441. indexCount, mesh, renderingMesh, createBoundingBox) {
  34442. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34443. var _this = _super.call(this) || this;
  34444. _this.materialIndex = materialIndex;
  34445. _this.verticesStart = verticesStart;
  34446. _this.verticesCount = verticesCount;
  34447. _this.indexStart = indexStart;
  34448. _this.indexCount = indexCount;
  34449. /** @hidden */
  34450. _this._renderId = 0;
  34451. _this._mesh = mesh;
  34452. _this._renderingMesh = renderingMesh || mesh;
  34453. mesh.subMeshes.push(_this);
  34454. _this._trianglePlanes = [];
  34455. _this._id = mesh.subMeshes.length - 1;
  34456. if (createBoundingBox) {
  34457. _this.refreshBoundingInfo();
  34458. mesh.computeWorldMatrix(true);
  34459. }
  34460. return _this;
  34461. }
  34462. /**
  34463. * Add a new submesh to a mesh
  34464. * @param materialIndex defines the material index to use
  34465. * @param verticesStart defines vertex index start
  34466. * @param verticesCount defines vertices count
  34467. * @param indexStart defines index start
  34468. * @param indexCount defines indices count
  34469. * @param mesh defines the parent mesh
  34470. * @param renderingMesh defines an optional rendering mesh
  34471. * @param createBoundingBox defines if bounding box should be created for this submesh
  34472. * @returns the new submesh
  34473. */
  34474. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34475. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34476. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34477. };
  34478. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34479. /**
  34480. * Returns true if this submesh covers the entire parent mesh
  34481. * @ignorenaming
  34482. */
  34483. get: function () {
  34484. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34485. },
  34486. enumerable: true,
  34487. configurable: true
  34488. });
  34489. /**
  34490. * Returns the submesh BoudingInfo object
  34491. * @returns current bounding info (or mesh's one if the submesh is global)
  34492. */
  34493. SubMesh.prototype.getBoundingInfo = function () {
  34494. if (this.IsGlobal) {
  34495. return this._mesh.getBoundingInfo();
  34496. }
  34497. return this._boundingInfo;
  34498. };
  34499. /**
  34500. * Sets the submesh BoundingInfo
  34501. * @param boundingInfo defines the new bounding info to use
  34502. * @returns the SubMesh
  34503. */
  34504. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34505. this._boundingInfo = boundingInfo;
  34506. return this;
  34507. };
  34508. /**
  34509. * Returns the mesh of the current submesh
  34510. * @return the parent mesh
  34511. */
  34512. SubMesh.prototype.getMesh = function () {
  34513. return this._mesh;
  34514. };
  34515. /**
  34516. * Returns the rendering mesh of the submesh
  34517. * @returns the rendering mesh (could be different from parent mesh)
  34518. */
  34519. SubMesh.prototype.getRenderingMesh = function () {
  34520. return this._renderingMesh;
  34521. };
  34522. /**
  34523. * Returns the submesh material
  34524. * @returns null or the current material
  34525. */
  34526. SubMesh.prototype.getMaterial = function () {
  34527. var rootMaterial = this._renderingMesh.material;
  34528. if (rootMaterial === null || rootMaterial === undefined) {
  34529. return this._mesh.getScene().defaultMaterial;
  34530. }
  34531. else if (rootMaterial.getSubMaterial) {
  34532. var multiMaterial = rootMaterial;
  34533. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34534. if (this._currentMaterial !== effectiveMaterial) {
  34535. this._currentMaterial = effectiveMaterial;
  34536. this._materialDefines = null;
  34537. }
  34538. return effectiveMaterial;
  34539. }
  34540. return rootMaterial;
  34541. };
  34542. // Methods
  34543. /**
  34544. * Sets a new updated BoundingInfo object to the submesh
  34545. * @returns the SubMesh
  34546. */
  34547. SubMesh.prototype.refreshBoundingInfo = function () {
  34548. this._lastColliderWorldVertices = null;
  34549. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34550. return this;
  34551. }
  34552. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34553. if (!data) {
  34554. this._boundingInfo = this._mesh.getBoundingInfo();
  34555. return this;
  34556. }
  34557. var indices = this._renderingMesh.getIndices();
  34558. var extend;
  34559. //is this the only submesh?
  34560. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34561. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34562. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34563. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34564. }
  34565. else {
  34566. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34567. }
  34568. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34569. return this;
  34570. };
  34571. /** @hidden */
  34572. SubMesh.prototype._checkCollision = function (collider) {
  34573. var boundingInfo = this.getBoundingInfo();
  34574. return boundingInfo._checkCollision(collider);
  34575. };
  34576. /**
  34577. * Updates the submesh BoundingInfo
  34578. * @param world defines the world matrix to use to update the bounding info
  34579. * @returns the submesh
  34580. */
  34581. SubMesh.prototype.updateBoundingInfo = function (world) {
  34582. var boundingInfo = this.getBoundingInfo();
  34583. if (!boundingInfo) {
  34584. this.refreshBoundingInfo();
  34585. boundingInfo = this.getBoundingInfo();
  34586. }
  34587. boundingInfo.update(world);
  34588. return this;
  34589. };
  34590. /**
  34591. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34592. * @param frustumPlanes defines the frustum planes
  34593. * @returns true if the submesh is intersecting with the frustum
  34594. */
  34595. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34596. var boundingInfo = this.getBoundingInfo();
  34597. if (!boundingInfo) {
  34598. return false;
  34599. }
  34600. return boundingInfo.isInFrustum(frustumPlanes);
  34601. };
  34602. /**
  34603. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  34604. * @param frustumPlanes defines the frustum planes
  34605. * @returns true if the submesh is inside the frustum
  34606. */
  34607. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34608. var boundingInfo = this.getBoundingInfo();
  34609. if (!boundingInfo) {
  34610. return false;
  34611. }
  34612. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34613. };
  34614. /**
  34615. * Renders the submesh
  34616. * @param enableAlphaMode defines if alpha needs to be used
  34617. * @returns the submesh
  34618. */
  34619. SubMesh.prototype.render = function (enableAlphaMode) {
  34620. this._renderingMesh.render(this, enableAlphaMode);
  34621. return this;
  34622. };
  34623. /**
  34624. * @hidden
  34625. */
  34626. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  34627. if (!this._linesIndexBuffer) {
  34628. var linesIndices = [];
  34629. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34630. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34631. }
  34632. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34633. this._linesIndexCount = linesIndices.length;
  34634. }
  34635. return this._linesIndexBuffer;
  34636. };
  34637. /**
  34638. * Checks if the submesh intersects with a ray
  34639. * @param ray defines the ray to test
  34640. * @returns true is the passed ray intersects the submesh bounding box
  34641. */
  34642. SubMesh.prototype.canIntersects = function (ray) {
  34643. var boundingInfo = this.getBoundingInfo();
  34644. if (!boundingInfo) {
  34645. return false;
  34646. }
  34647. return ray.intersectsBox(boundingInfo.boundingBox);
  34648. };
  34649. /**
  34650. * Intersects current submesh with a ray
  34651. * @param ray defines the ray to test
  34652. * @param positions defines mesh's positions array
  34653. * @param indices defines mesh's indices array
  34654. * @param fastCheck defines if only bounding info should be used
  34655. * @returns intersection info or null if no intersection
  34656. */
  34657. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34658. var intersectInfo = null;
  34659. var material = this.getMaterial();
  34660. if (!material) {
  34661. return null;
  34662. }
  34663. switch (material.fillMode) {
  34664. case BABYLON.Material.PointListDrawMode:
  34665. case BABYLON.Material.LineListDrawMode:
  34666. case BABYLON.Material.LineLoopDrawMode:
  34667. case BABYLON.Material.LineStripDrawMode:
  34668. case BABYLON.Material.TriangleFanDrawMode:
  34669. case BABYLON.Material.TriangleStripDrawMode:
  34670. return null;
  34671. }
  34672. // LineMesh first as it's also a Mesh...
  34673. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34674. var lineMesh = this._mesh;
  34675. // Line test
  34676. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34677. var p0 = positions[indices[index]];
  34678. var p1 = positions[indices[index + 1]];
  34679. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34680. if (length < 0) {
  34681. continue;
  34682. }
  34683. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34684. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34685. if (fastCheck) {
  34686. break;
  34687. }
  34688. }
  34689. }
  34690. }
  34691. else {
  34692. // Triangles test
  34693. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34694. var p0 = positions[indices[index]];
  34695. var p1 = positions[indices[index + 1]];
  34696. var p2 = positions[indices[index + 2]];
  34697. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34698. if (currentIntersectInfo) {
  34699. if (currentIntersectInfo.distance < 0) {
  34700. continue;
  34701. }
  34702. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34703. intersectInfo = currentIntersectInfo;
  34704. intersectInfo.faceId = index / 3;
  34705. if (fastCheck) {
  34706. break;
  34707. }
  34708. }
  34709. }
  34710. }
  34711. }
  34712. return intersectInfo;
  34713. };
  34714. /** @hidden */
  34715. SubMesh.prototype._rebuild = function () {
  34716. if (this._linesIndexBuffer) {
  34717. this._linesIndexBuffer = null;
  34718. }
  34719. };
  34720. // Clone
  34721. /**
  34722. * Creates a new submesh from the passed mesh
  34723. * @param newMesh defines the new hosting mesh
  34724. * @param newRenderingMesh defines an optional rendering mesh
  34725. * @returns the new submesh
  34726. */
  34727. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34728. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34729. if (!this.IsGlobal) {
  34730. var boundingInfo = this.getBoundingInfo();
  34731. if (!boundingInfo) {
  34732. return result;
  34733. }
  34734. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34735. }
  34736. return result;
  34737. };
  34738. // Dispose
  34739. /**
  34740. * Release associated resources
  34741. */
  34742. SubMesh.prototype.dispose = function () {
  34743. if (this._linesIndexBuffer) {
  34744. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34745. this._linesIndexBuffer = null;
  34746. }
  34747. // Remove from mesh
  34748. var index = this._mesh.subMeshes.indexOf(this);
  34749. this._mesh.subMeshes.splice(index, 1);
  34750. };
  34751. // Statics
  34752. /**
  34753. * Creates a new submesh from indices data
  34754. * @param materialIndex the index of the main mesh material
  34755. * @param startIndex the index where to start the copy in the mesh indices array
  34756. * @param indexCount the number of indices to copy then from the startIndex
  34757. * @param mesh the main mesh to create the submesh from
  34758. * @param renderingMesh the optional rendering mesh
  34759. * @returns a new submesh
  34760. */
  34761. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34762. var minVertexIndex = Number.MAX_VALUE;
  34763. var maxVertexIndex = -Number.MAX_VALUE;
  34764. renderingMesh = (renderingMesh || mesh);
  34765. var indices = renderingMesh.getIndices();
  34766. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34767. var vertexIndex = indices[index];
  34768. if (vertexIndex < minVertexIndex)
  34769. minVertexIndex = vertexIndex;
  34770. if (vertexIndex > maxVertexIndex)
  34771. maxVertexIndex = vertexIndex;
  34772. }
  34773. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34774. };
  34775. return SubMesh;
  34776. }(BaseSubMesh));
  34777. BABYLON.SubMesh = SubMesh;
  34778. })(BABYLON || (BABYLON = {}));
  34779. //# sourceMappingURL=babylon.subMesh.js.map
  34780. var __assign = (this && this.__assign) || function () {
  34781. __assign = Object.assign || function(t) {
  34782. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34783. s = arguments[i];
  34784. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34785. t[p] = s[p];
  34786. }
  34787. return t;
  34788. };
  34789. return __assign.apply(this, arguments);
  34790. };
  34791. var BABYLON;
  34792. (function (BABYLON) {
  34793. /**
  34794. * Manages the defines for the Material
  34795. */
  34796. var MaterialDefines = /** @class */ (function () {
  34797. function MaterialDefines() {
  34798. this._isDirty = true;
  34799. /** @hidden */
  34800. this._areLightsDirty = true;
  34801. /** @hidden */
  34802. this._areAttributesDirty = true;
  34803. /** @hidden */
  34804. this._areTexturesDirty = true;
  34805. /** @hidden */
  34806. this._areFresnelDirty = true;
  34807. /** @hidden */
  34808. this._areMiscDirty = true;
  34809. /** @hidden */
  34810. this._areImageProcessingDirty = true;
  34811. /** @hidden */
  34812. this._normals = false;
  34813. /** @hidden */
  34814. this._uvs = false;
  34815. /** @hidden */
  34816. this._needNormals = false;
  34817. /** @hidden */
  34818. this._needUVs = false;
  34819. }
  34820. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34821. /**
  34822. * Specifies if the material needs to be re-calculated
  34823. */
  34824. get: function () {
  34825. return this._isDirty;
  34826. },
  34827. enumerable: true,
  34828. configurable: true
  34829. });
  34830. /**
  34831. * Marks the material to indicate that it has been re-calculated
  34832. */
  34833. MaterialDefines.prototype.markAsProcessed = function () {
  34834. this._isDirty = false;
  34835. this._areAttributesDirty = false;
  34836. this._areTexturesDirty = false;
  34837. this._areFresnelDirty = false;
  34838. this._areLightsDirty = false;
  34839. this._areMiscDirty = false;
  34840. this._areImageProcessingDirty = false;
  34841. };
  34842. /**
  34843. * Marks the material to indicate that it needs to be re-calculated
  34844. */
  34845. MaterialDefines.prototype.markAsUnprocessed = function () {
  34846. this._isDirty = true;
  34847. };
  34848. /**
  34849. * Marks the material to indicate all of its defines need to be re-calculated
  34850. */
  34851. MaterialDefines.prototype.markAllAsDirty = function () {
  34852. this._areTexturesDirty = true;
  34853. this._areAttributesDirty = true;
  34854. this._areLightsDirty = true;
  34855. this._areFresnelDirty = true;
  34856. this._areMiscDirty = true;
  34857. this._areImageProcessingDirty = true;
  34858. this._isDirty = true;
  34859. };
  34860. /**
  34861. * Marks the material to indicate that image processing needs to be re-calculated
  34862. */
  34863. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34864. this._areImageProcessingDirty = true;
  34865. this._isDirty = true;
  34866. };
  34867. /**
  34868. * Marks the material to indicate the lights need to be re-calculated
  34869. */
  34870. MaterialDefines.prototype.markAsLightDirty = function () {
  34871. this._areLightsDirty = true;
  34872. this._isDirty = true;
  34873. };
  34874. /**
  34875. * Marks the attribute state as changed
  34876. */
  34877. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34878. this._areAttributesDirty = true;
  34879. this._isDirty = true;
  34880. };
  34881. /**
  34882. * Marks the texture state as changed
  34883. */
  34884. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34885. this._areTexturesDirty = true;
  34886. this._isDirty = true;
  34887. };
  34888. /**
  34889. * Marks the fresnel state as changed
  34890. */
  34891. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34892. this._areFresnelDirty = true;
  34893. this._isDirty = true;
  34894. };
  34895. /**
  34896. * Marks the misc state as changed
  34897. */
  34898. MaterialDefines.prototype.markAsMiscDirty = function () {
  34899. this._areMiscDirty = true;
  34900. this._isDirty = true;
  34901. };
  34902. /**
  34903. * Rebuilds the material defines
  34904. */
  34905. MaterialDefines.prototype.rebuild = function () {
  34906. if (this._keys) {
  34907. delete this._keys;
  34908. }
  34909. this._keys = [];
  34910. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34911. var key = _a[_i];
  34912. if (key[0] === "_") {
  34913. continue;
  34914. }
  34915. this._keys.push(key);
  34916. }
  34917. };
  34918. /**
  34919. * Specifies if two material defines are equal
  34920. * @param other - A material define instance to compare to
  34921. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34922. */
  34923. MaterialDefines.prototype.isEqual = function (other) {
  34924. if (this._keys.length !== other._keys.length) {
  34925. return false;
  34926. }
  34927. for (var index = 0; index < this._keys.length; index++) {
  34928. var prop = this._keys[index];
  34929. if (this[prop] !== other[prop]) {
  34930. return false;
  34931. }
  34932. }
  34933. return true;
  34934. };
  34935. /**
  34936. * Clones this instance's defines to another instance
  34937. * @param other - material defines to clone values to
  34938. */
  34939. MaterialDefines.prototype.cloneTo = function (other) {
  34940. if (this._keys.length !== other._keys.length) {
  34941. other._keys = this._keys.slice(0);
  34942. }
  34943. for (var index = 0; index < this._keys.length; index++) {
  34944. var prop = this._keys[index];
  34945. other[prop] = this[prop];
  34946. }
  34947. };
  34948. /**
  34949. * Resets the material define values
  34950. */
  34951. MaterialDefines.prototype.reset = function () {
  34952. for (var index = 0; index < this._keys.length; index++) {
  34953. var prop = this._keys[index];
  34954. var type = typeof this[prop];
  34955. switch (type) {
  34956. case "number":
  34957. this[prop] = 0;
  34958. break;
  34959. case "string":
  34960. this[prop] = "";
  34961. break;
  34962. default:
  34963. this[prop] = false;
  34964. break;
  34965. }
  34966. }
  34967. };
  34968. /**
  34969. * Converts the material define values to a string
  34970. * @returns - String of material define information
  34971. */
  34972. MaterialDefines.prototype.toString = function () {
  34973. var result = "";
  34974. for (var index = 0; index < this._keys.length; index++) {
  34975. var prop = this._keys[index];
  34976. var value = this[prop];
  34977. var type = typeof value;
  34978. switch (type) {
  34979. case "number":
  34980. case "string":
  34981. result += "#define " + prop + " " + value + "\n";
  34982. break;
  34983. default:
  34984. if (value) {
  34985. result += "#define " + prop + "\n";
  34986. }
  34987. break;
  34988. }
  34989. }
  34990. return result;
  34991. };
  34992. return MaterialDefines;
  34993. }());
  34994. BABYLON.MaterialDefines = MaterialDefines;
  34995. /**
  34996. * Base class for the main features of a material in Babylon.js
  34997. */
  34998. var Material = /** @class */ (function () {
  34999. /**
  35000. * Creates a material instance
  35001. * @param name defines the name of the material
  35002. * @param scene defines the scene to reference
  35003. * @param doNotAdd specifies if the material should be added to the scene
  35004. */
  35005. function Material(name, scene, doNotAdd) {
  35006. /**
  35007. * Specifies if the ready state should be checked on each call
  35008. */
  35009. this.checkReadyOnEveryCall = false;
  35010. /**
  35011. * Specifies if the ready state should be checked once
  35012. */
  35013. this.checkReadyOnlyOnce = false;
  35014. /**
  35015. * The state of the material
  35016. */
  35017. this.state = "";
  35018. /**
  35019. * The alpha value of the material
  35020. */
  35021. this._alpha = 1.0;
  35022. /**
  35023. * Specifies if back face culling is enabled
  35024. */
  35025. this._backFaceCulling = true;
  35026. /**
  35027. * Specifies if the material should be serialized
  35028. */
  35029. this.doNotSerialize = false;
  35030. /**
  35031. * Specifies if the effect should be stored on sub meshes
  35032. */
  35033. this.storeEffectOnSubMeshes = false;
  35034. /**
  35035. * An event triggered when the material is disposed
  35036. */
  35037. this.onDisposeObservable = new BABYLON.Observable();
  35038. /**
  35039. * Stores the value of the alpha mode
  35040. */
  35041. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35042. /**
  35043. * Stores the state of the need depth pre-pass value
  35044. */
  35045. this._needDepthPrePass = false;
  35046. /**
  35047. * Specifies if depth writing should be disabled
  35048. */
  35049. this.disableDepthWrite = false;
  35050. /**
  35051. * Specifies if depth writing should be forced
  35052. */
  35053. this.forceDepthWrite = false;
  35054. /**
  35055. * Specifies if there should be a separate pass for culling
  35056. */
  35057. this.separateCullingPass = false;
  35058. /**
  35059. * Stores the state specifing if fog should be enabled
  35060. */
  35061. this._fogEnabled = true;
  35062. /**
  35063. * Stores the size of points
  35064. */
  35065. this.pointSize = 1.0;
  35066. /**
  35067. * Stores the z offset value
  35068. */
  35069. this.zOffset = 0;
  35070. /**
  35071. * @hidden
  35072. * Specifies if the material was previously ready
  35073. */
  35074. this._wasPreviouslyReady = false;
  35075. /**
  35076. * Stores the fill mode state
  35077. */
  35078. this._fillMode = Material.TriangleFillMode;
  35079. this.name = name;
  35080. this.id = name || BABYLON.Tools.RandomId();
  35081. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35082. this.uniqueId = this._scene.getUniqueId();
  35083. if (this._scene.useRightHandedSystem) {
  35084. this.sideOrientation = Material.ClockWiseSideOrientation;
  35085. }
  35086. else {
  35087. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35088. }
  35089. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35090. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35091. if (!doNotAdd) {
  35092. this._scene.materials.push(this);
  35093. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  35094. }
  35095. }
  35096. Object.defineProperty(Material, "TriangleFillMode", {
  35097. /**
  35098. * Returns the triangle fill mode
  35099. */
  35100. get: function () {
  35101. return Material._TriangleFillMode;
  35102. },
  35103. enumerable: true,
  35104. configurable: true
  35105. });
  35106. Object.defineProperty(Material, "WireFrameFillMode", {
  35107. /**
  35108. * Returns the wireframe mode
  35109. */
  35110. get: function () {
  35111. return Material._WireFrameFillMode;
  35112. },
  35113. enumerable: true,
  35114. configurable: true
  35115. });
  35116. Object.defineProperty(Material, "PointFillMode", {
  35117. /**
  35118. * Returns the point fill mode
  35119. */
  35120. get: function () {
  35121. return Material._PointFillMode;
  35122. },
  35123. enumerable: true,
  35124. configurable: true
  35125. });
  35126. Object.defineProperty(Material, "PointListDrawMode", {
  35127. /**
  35128. * Returns the point list draw mode
  35129. */
  35130. get: function () {
  35131. return Material._PointListDrawMode;
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(Material, "LineListDrawMode", {
  35137. /**
  35138. * Returns the line list draw mode
  35139. */
  35140. get: function () {
  35141. return Material._LineListDrawMode;
  35142. },
  35143. enumerable: true,
  35144. configurable: true
  35145. });
  35146. Object.defineProperty(Material, "LineLoopDrawMode", {
  35147. /**
  35148. * Returns the line loop draw mode
  35149. */
  35150. get: function () {
  35151. return Material._LineLoopDrawMode;
  35152. },
  35153. enumerable: true,
  35154. configurable: true
  35155. });
  35156. Object.defineProperty(Material, "LineStripDrawMode", {
  35157. /**
  35158. * Returns the line strip draw mode
  35159. */
  35160. get: function () {
  35161. return Material._LineStripDrawMode;
  35162. },
  35163. enumerable: true,
  35164. configurable: true
  35165. });
  35166. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35167. /**
  35168. * Returns the triangle strip draw mode
  35169. */
  35170. get: function () {
  35171. return Material._TriangleStripDrawMode;
  35172. },
  35173. enumerable: true,
  35174. configurable: true
  35175. });
  35176. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35177. /**
  35178. * Returns the triangle fan draw mode
  35179. */
  35180. get: function () {
  35181. return Material._TriangleFanDrawMode;
  35182. },
  35183. enumerable: true,
  35184. configurable: true
  35185. });
  35186. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35187. /**
  35188. * Returns the clock-wise side orientation
  35189. */
  35190. get: function () {
  35191. return Material._ClockWiseSideOrientation;
  35192. },
  35193. enumerable: true,
  35194. configurable: true
  35195. });
  35196. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35197. /**
  35198. * Returns the counter clock-wise side orientation
  35199. */
  35200. get: function () {
  35201. return Material._CounterClockWiseSideOrientation;
  35202. },
  35203. enumerable: true,
  35204. configurable: true
  35205. });
  35206. Object.defineProperty(Material.prototype, "alpha", {
  35207. /**
  35208. * Gets the alpha value of the material
  35209. */
  35210. get: function () {
  35211. return this._alpha;
  35212. },
  35213. /**
  35214. * Sets the alpha value of the material
  35215. */
  35216. set: function (value) {
  35217. if (this._alpha === value) {
  35218. return;
  35219. }
  35220. this._alpha = value;
  35221. this.markAsDirty(Material.MiscDirtyFlag);
  35222. },
  35223. enumerable: true,
  35224. configurable: true
  35225. });
  35226. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35227. /**
  35228. * Gets the back-face culling state
  35229. */
  35230. get: function () {
  35231. return this._backFaceCulling;
  35232. },
  35233. /**
  35234. * Sets the back-face culling state
  35235. */
  35236. set: function (value) {
  35237. if (this._backFaceCulling === value) {
  35238. return;
  35239. }
  35240. this._backFaceCulling = value;
  35241. this.markAsDirty(Material.TextureDirtyFlag);
  35242. },
  35243. enumerable: true,
  35244. configurable: true
  35245. });
  35246. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  35247. /**
  35248. * Gets a boolean indicating that current material needs to register RTT
  35249. */
  35250. get: function () {
  35251. return false;
  35252. },
  35253. enumerable: true,
  35254. configurable: true
  35255. });
  35256. Object.defineProperty(Material.prototype, "onDispose", {
  35257. /**
  35258. * Called during a dispose event
  35259. */
  35260. set: function (callback) {
  35261. if (this._onDisposeObserver) {
  35262. this.onDisposeObservable.remove(this._onDisposeObserver);
  35263. }
  35264. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35265. },
  35266. enumerable: true,
  35267. configurable: true
  35268. });
  35269. Object.defineProperty(Material.prototype, "onBindObservable", {
  35270. /**
  35271. * An event triggered when the material is bound
  35272. */
  35273. get: function () {
  35274. if (!this._onBindObservable) {
  35275. this._onBindObservable = new BABYLON.Observable();
  35276. }
  35277. return this._onBindObservable;
  35278. },
  35279. enumerable: true,
  35280. configurable: true
  35281. });
  35282. Object.defineProperty(Material.prototype, "onBind", {
  35283. /**
  35284. * Called during a bind event
  35285. */
  35286. set: function (callback) {
  35287. if (this._onBindObserver) {
  35288. this.onBindObservable.remove(this._onBindObserver);
  35289. }
  35290. this._onBindObserver = this.onBindObservable.add(callback);
  35291. },
  35292. enumerable: true,
  35293. configurable: true
  35294. });
  35295. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35296. /**
  35297. * An event triggered when the material is unbound
  35298. */
  35299. get: function () {
  35300. if (!this._onUnBindObservable) {
  35301. this._onUnBindObservable = new BABYLON.Observable();
  35302. }
  35303. return this._onUnBindObservable;
  35304. },
  35305. enumerable: true,
  35306. configurable: true
  35307. });
  35308. Object.defineProperty(Material.prototype, "alphaMode", {
  35309. /**
  35310. * Gets the value of the alpha mode
  35311. */
  35312. get: function () {
  35313. return this._alphaMode;
  35314. },
  35315. /**
  35316. * Sets the value of the alpha mode.
  35317. *
  35318. * | Value | Type | Description |
  35319. * | --- | --- | --- |
  35320. * | 0 | ALPHA_DISABLE | |
  35321. * | 1 | ALPHA_ADD | |
  35322. * | 2 | ALPHA_COMBINE | |
  35323. * | 3 | ALPHA_SUBTRACT | |
  35324. * | 4 | ALPHA_MULTIPLY | |
  35325. * | 5 | ALPHA_MAXIMIZED | |
  35326. * | 6 | ALPHA_ONEONE | |
  35327. * | 7 | ALPHA_PREMULTIPLIED | |
  35328. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35329. * | 9 | ALPHA_INTERPOLATE | |
  35330. * | 10 | ALPHA_SCREENMODE | |
  35331. *
  35332. */
  35333. set: function (value) {
  35334. if (this._alphaMode === value) {
  35335. return;
  35336. }
  35337. this._alphaMode = value;
  35338. this.markAsDirty(Material.TextureDirtyFlag);
  35339. },
  35340. enumerable: true,
  35341. configurable: true
  35342. });
  35343. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35344. /**
  35345. * Gets the depth pre-pass value
  35346. */
  35347. get: function () {
  35348. return this._needDepthPrePass;
  35349. },
  35350. /**
  35351. * Sets the need depth pre-pass value
  35352. */
  35353. set: function (value) {
  35354. if (this._needDepthPrePass === value) {
  35355. return;
  35356. }
  35357. this._needDepthPrePass = value;
  35358. if (this._needDepthPrePass) {
  35359. this.checkReadyOnEveryCall = true;
  35360. }
  35361. },
  35362. enumerable: true,
  35363. configurable: true
  35364. });
  35365. Object.defineProperty(Material.prototype, "fogEnabled", {
  35366. /**
  35367. * Gets the value of the fog enabled state
  35368. */
  35369. get: function () {
  35370. return this._fogEnabled;
  35371. },
  35372. /**
  35373. * Sets the state for enabling fog
  35374. */
  35375. set: function (value) {
  35376. if (this._fogEnabled === value) {
  35377. return;
  35378. }
  35379. this._fogEnabled = value;
  35380. this.markAsDirty(Material.MiscDirtyFlag);
  35381. },
  35382. enumerable: true,
  35383. configurable: true
  35384. });
  35385. Object.defineProperty(Material.prototype, "wireframe", {
  35386. /**
  35387. * Gets a value specifying if wireframe mode is enabled
  35388. */
  35389. get: function () {
  35390. switch (this._fillMode) {
  35391. case Material.WireFrameFillMode:
  35392. case Material.LineListDrawMode:
  35393. case Material.LineLoopDrawMode:
  35394. case Material.LineStripDrawMode:
  35395. return true;
  35396. }
  35397. return this._scene.forceWireframe;
  35398. },
  35399. /**
  35400. * Sets the state of wireframe mode
  35401. */
  35402. set: function (value) {
  35403. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35404. },
  35405. enumerable: true,
  35406. configurable: true
  35407. });
  35408. Object.defineProperty(Material.prototype, "pointsCloud", {
  35409. /**
  35410. * Gets the value specifying if point clouds are enabled
  35411. */
  35412. get: function () {
  35413. switch (this._fillMode) {
  35414. case Material.PointFillMode:
  35415. case Material.PointListDrawMode:
  35416. return true;
  35417. }
  35418. return this._scene.forcePointsCloud;
  35419. },
  35420. /**
  35421. * Sets the state of point cloud mode
  35422. */
  35423. set: function (value) {
  35424. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35425. },
  35426. enumerable: true,
  35427. configurable: true
  35428. });
  35429. Object.defineProperty(Material.prototype, "fillMode", {
  35430. /**
  35431. * Gets the material fill mode
  35432. */
  35433. get: function () {
  35434. return this._fillMode;
  35435. },
  35436. /**
  35437. * Sets the material fill mode
  35438. */
  35439. set: function (value) {
  35440. if (this._fillMode === value) {
  35441. return;
  35442. }
  35443. this._fillMode = value;
  35444. this.markAsDirty(Material.MiscDirtyFlag);
  35445. },
  35446. enumerable: true,
  35447. configurable: true
  35448. });
  35449. /**
  35450. * Returns a string representation of the current material
  35451. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35452. * @returns a string with material information
  35453. */
  35454. Material.prototype.toString = function (fullDetails) {
  35455. var ret = "Name: " + this.name;
  35456. if (fullDetails) {
  35457. }
  35458. return ret;
  35459. };
  35460. /**
  35461. * Gets the class name of the material
  35462. * @returns a string with the class name of the material
  35463. */
  35464. Material.prototype.getClassName = function () {
  35465. return "Material";
  35466. };
  35467. Object.defineProperty(Material.prototype, "isFrozen", {
  35468. /**
  35469. * Specifies if updates for the material been locked
  35470. */
  35471. get: function () {
  35472. return this.checkReadyOnlyOnce;
  35473. },
  35474. enumerable: true,
  35475. configurable: true
  35476. });
  35477. /**
  35478. * Locks updates for the material
  35479. */
  35480. Material.prototype.freeze = function () {
  35481. this.checkReadyOnlyOnce = true;
  35482. };
  35483. /**
  35484. * Unlocks updates for the material
  35485. */
  35486. Material.prototype.unfreeze = function () {
  35487. this.checkReadyOnlyOnce = false;
  35488. };
  35489. /**
  35490. * Specifies if the material is ready to be used
  35491. * @param mesh defines the mesh to check
  35492. * @param useInstances specifies if instances should be used
  35493. * @returns a boolean indicating if the material is ready to be used
  35494. */
  35495. Material.prototype.isReady = function (mesh, useInstances) {
  35496. return true;
  35497. };
  35498. /**
  35499. * Specifies that the submesh is ready to be used
  35500. * @param mesh defines the mesh to check
  35501. * @param subMesh defines which submesh to check
  35502. * @param useInstances specifies that instances should be used
  35503. * @returns a boolean indicating that the submesh is ready or not
  35504. */
  35505. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35506. return false;
  35507. };
  35508. /**
  35509. * Returns the material effect
  35510. * @returns the effect associated with the material
  35511. */
  35512. Material.prototype.getEffect = function () {
  35513. return this._effect;
  35514. };
  35515. /**
  35516. * Returns the current scene
  35517. * @returns a Scene
  35518. */
  35519. Material.prototype.getScene = function () {
  35520. return this._scene;
  35521. };
  35522. /**
  35523. * Specifies if the material will require alpha blending
  35524. * @returns a boolean specifying if alpha blending is needed
  35525. */
  35526. Material.prototype.needAlphaBlending = function () {
  35527. return (this.alpha < 1.0);
  35528. };
  35529. /**
  35530. * Specifies if the mesh will require alpha blending
  35531. * @param mesh defines the mesh to check
  35532. * @returns a boolean specifying if alpha blending is needed for the mesh
  35533. */
  35534. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35535. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35536. };
  35537. /**
  35538. * Specifies if this material should be rendered in alpha test mode
  35539. * @returns a boolean specifying if an alpha test is needed.
  35540. */
  35541. Material.prototype.needAlphaTesting = function () {
  35542. return false;
  35543. };
  35544. /**
  35545. * Gets the texture used for the alpha test
  35546. * @returns the texture to use for alpha testing
  35547. */
  35548. Material.prototype.getAlphaTestTexture = function () {
  35549. return null;
  35550. };
  35551. /**
  35552. * Marks the material to indicate that it needs to be re-calculated
  35553. */
  35554. Material.prototype.markDirty = function () {
  35555. this._wasPreviouslyReady = false;
  35556. };
  35557. /** @hidden */
  35558. Material.prototype._preBind = function (effect, overrideOrientation) {
  35559. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35560. var engine = this._scene.getEngine();
  35561. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35562. var reverse = orientation === Material.ClockWiseSideOrientation;
  35563. engine.enableEffect(effect ? effect : this._effect);
  35564. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35565. return reverse;
  35566. };
  35567. /**
  35568. * Binds the material to the mesh
  35569. * @param world defines the world transformation matrix
  35570. * @param mesh defines the mesh to bind the material to
  35571. */
  35572. Material.prototype.bind = function (world, mesh) {
  35573. };
  35574. /**
  35575. * Binds the submesh to the material
  35576. * @param world defines the world transformation matrix
  35577. * @param mesh defines the mesh containing the submesh
  35578. * @param subMesh defines the submesh to bind the material to
  35579. */
  35580. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35581. };
  35582. /**
  35583. * Binds the world matrix to the material
  35584. * @param world defines the world transformation matrix
  35585. */
  35586. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35587. };
  35588. /**
  35589. * Binds the scene's uniform buffer to the effect.
  35590. * @param effect defines the effect to bind to the scene uniform buffer
  35591. * @param sceneUbo defines the uniform buffer storing scene data
  35592. */
  35593. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35594. sceneUbo.bindToEffect(effect, "Scene");
  35595. };
  35596. /**
  35597. * Binds the view matrix to the effect
  35598. * @param effect defines the effect to bind the view matrix to
  35599. */
  35600. Material.prototype.bindView = function (effect) {
  35601. if (!this._useUBO) {
  35602. effect.setMatrix("view", this.getScene().getViewMatrix());
  35603. }
  35604. else {
  35605. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35606. }
  35607. };
  35608. /**
  35609. * Binds the view projection matrix to the effect
  35610. * @param effect defines the effect to bind the view projection matrix to
  35611. */
  35612. Material.prototype.bindViewProjection = function (effect) {
  35613. if (!this._useUBO) {
  35614. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35615. }
  35616. else {
  35617. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35618. }
  35619. };
  35620. /**
  35621. * Specifies if material alpha testing should be turned on for the mesh
  35622. * @param mesh defines the mesh to check
  35623. */
  35624. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35625. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35626. };
  35627. /**
  35628. * Processes to execute after binding the material to a mesh
  35629. * @param mesh defines the rendered mesh
  35630. */
  35631. Material.prototype._afterBind = function (mesh) {
  35632. this._scene._cachedMaterial = this;
  35633. if (mesh) {
  35634. this._scene._cachedVisibility = mesh.visibility;
  35635. }
  35636. else {
  35637. this._scene._cachedVisibility = 1;
  35638. }
  35639. if (this._onBindObservable && mesh) {
  35640. this._onBindObservable.notifyObservers(mesh);
  35641. }
  35642. if (this.disableDepthWrite) {
  35643. var engine = this._scene.getEngine();
  35644. this._cachedDepthWriteState = engine.getDepthWrite();
  35645. engine.setDepthWrite(false);
  35646. }
  35647. };
  35648. /**
  35649. * Unbinds the material from the mesh
  35650. */
  35651. Material.prototype.unbind = function () {
  35652. if (this._onUnBindObservable) {
  35653. this._onUnBindObservable.notifyObservers(this);
  35654. }
  35655. if (this.disableDepthWrite) {
  35656. var engine = this._scene.getEngine();
  35657. engine.setDepthWrite(this._cachedDepthWriteState);
  35658. }
  35659. };
  35660. /**
  35661. * Gets the active textures from the material
  35662. * @returns an array of textures
  35663. */
  35664. Material.prototype.getActiveTextures = function () {
  35665. return [];
  35666. };
  35667. /**
  35668. * Specifies if the material uses a texture
  35669. * @param texture defines the texture to check against the material
  35670. * @returns a boolean specifying if the material uses the texture
  35671. */
  35672. Material.prototype.hasTexture = function (texture) {
  35673. return false;
  35674. };
  35675. /**
  35676. * Makes a duplicate of the material, and gives it a new name
  35677. * @param name defines the new name for the duplicated material
  35678. * @returns the cloned material
  35679. */
  35680. Material.prototype.clone = function (name) {
  35681. return null;
  35682. };
  35683. /**
  35684. * Gets the meshes bound to the material
  35685. * @returns an array of meshes bound to the material
  35686. */
  35687. Material.prototype.getBindedMeshes = function () {
  35688. var result = new Array();
  35689. for (var index = 0; index < this._scene.meshes.length; index++) {
  35690. var mesh = this._scene.meshes[index];
  35691. if (mesh.material === this) {
  35692. result.push(mesh);
  35693. }
  35694. }
  35695. return result;
  35696. };
  35697. /**
  35698. * Force shader compilation
  35699. * @param mesh defines the mesh associated with this material
  35700. * @param onCompiled defines a function to execute once the material is compiled
  35701. * @param options defines the options to configure the compilation
  35702. */
  35703. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35704. var _this = this;
  35705. var localOptions = __assign({ clipPlane: false }, options);
  35706. var subMesh = new BABYLON.BaseSubMesh();
  35707. var scene = this.getScene();
  35708. var checkReady = function () {
  35709. if (!_this._scene || !_this._scene.getEngine()) {
  35710. return;
  35711. }
  35712. if (subMesh._materialDefines) {
  35713. subMesh._materialDefines._renderId = -1;
  35714. }
  35715. var clipPlaneState = scene.clipPlane;
  35716. if (localOptions.clipPlane) {
  35717. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35718. }
  35719. if (_this.storeEffectOnSubMeshes) {
  35720. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35721. if (onCompiled) {
  35722. onCompiled(_this);
  35723. }
  35724. }
  35725. else {
  35726. setTimeout(checkReady, 16);
  35727. }
  35728. }
  35729. else {
  35730. if (_this.isReady(mesh)) {
  35731. if (onCompiled) {
  35732. onCompiled(_this);
  35733. }
  35734. }
  35735. else {
  35736. setTimeout(checkReady, 16);
  35737. }
  35738. }
  35739. if (localOptions.clipPlane) {
  35740. scene.clipPlane = clipPlaneState;
  35741. }
  35742. };
  35743. checkReady();
  35744. };
  35745. /**
  35746. * Force shader compilation
  35747. * @param mesh defines the mesh that will use this material
  35748. * @param options defines additional options for compiling the shaders
  35749. * @returns a promise that resolves when the compilation completes
  35750. */
  35751. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35752. var _this = this;
  35753. return new Promise(function (resolve) {
  35754. _this.forceCompilation(mesh, function () {
  35755. resolve();
  35756. }, options);
  35757. });
  35758. };
  35759. /**
  35760. * Marks a define in the material to indicate that it needs to be re-computed
  35761. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35762. */
  35763. Material.prototype.markAsDirty = function (flag) {
  35764. if (flag & Material.TextureDirtyFlag) {
  35765. this._markAllSubMeshesAsTexturesDirty();
  35766. }
  35767. if (flag & Material.LightDirtyFlag) {
  35768. this._markAllSubMeshesAsLightsDirty();
  35769. }
  35770. if (flag & Material.FresnelDirtyFlag) {
  35771. this._markAllSubMeshesAsFresnelDirty();
  35772. }
  35773. if (flag & Material.AttributesDirtyFlag) {
  35774. this._markAllSubMeshesAsAttributesDirty();
  35775. }
  35776. if (flag & Material.MiscDirtyFlag) {
  35777. this._markAllSubMeshesAsMiscDirty();
  35778. }
  35779. this.getScene().resetCachedMaterial();
  35780. };
  35781. /**
  35782. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35783. * @param func defines a function which checks material defines against the submeshes
  35784. */
  35785. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35786. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35787. var mesh = _a[_i];
  35788. if (!mesh.subMeshes) {
  35789. continue;
  35790. }
  35791. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35792. var subMesh = _c[_b];
  35793. if (subMesh.getMaterial() !== this) {
  35794. continue;
  35795. }
  35796. if (!subMesh._materialDefines) {
  35797. continue;
  35798. }
  35799. func(subMesh._materialDefines);
  35800. }
  35801. }
  35802. };
  35803. /**
  35804. * Indicates that image processing needs to be re-calculated for all submeshes
  35805. */
  35806. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35807. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35808. };
  35809. /**
  35810. * Indicates that textures need to be re-calculated for all submeshes
  35811. */
  35812. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35813. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35814. };
  35815. /**
  35816. * Indicates that fresnel needs to be re-calculated for all submeshes
  35817. */
  35818. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35819. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35820. };
  35821. /**
  35822. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35823. */
  35824. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35825. this._markAllSubMeshesAsDirty(function (defines) {
  35826. defines.markAsFresnelDirty();
  35827. defines.markAsMiscDirty();
  35828. });
  35829. };
  35830. /**
  35831. * Indicates that lights need to be re-calculated for all submeshes
  35832. */
  35833. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35834. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35835. };
  35836. /**
  35837. * Indicates that attributes need to be re-calculated for all submeshes
  35838. */
  35839. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35840. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35841. };
  35842. /**
  35843. * Indicates that misc needs to be re-calculated for all submeshes
  35844. */
  35845. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35846. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35847. };
  35848. /**
  35849. * Indicates that textures and misc need to be re-calculated for all submeshes
  35850. */
  35851. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35852. this._markAllSubMeshesAsDirty(function (defines) {
  35853. defines.markAsTexturesDirty();
  35854. defines.markAsMiscDirty();
  35855. });
  35856. };
  35857. /**
  35858. * Disposes the material
  35859. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35860. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35861. */
  35862. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35863. // Animations
  35864. this.getScene().stopAnimation(this);
  35865. this.getScene().freeProcessedMaterials();
  35866. // Remove from scene
  35867. var index = this._scene.materials.indexOf(this);
  35868. if (index >= 0) {
  35869. this._scene.materials.splice(index, 1);
  35870. }
  35871. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  35872. // Remove from meshes
  35873. for (index = 0; index < this._scene.meshes.length; index++) {
  35874. var mesh = this._scene.meshes[index];
  35875. if (mesh.material === this) {
  35876. mesh.material = null;
  35877. if (mesh.geometry) {
  35878. var geometry = (mesh.geometry);
  35879. if (this.storeEffectOnSubMeshes) {
  35880. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35881. var subMesh = _a[_i];
  35882. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35883. if (forceDisposeEffect && subMesh._materialEffect) {
  35884. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35885. }
  35886. }
  35887. }
  35888. else {
  35889. geometry._releaseVertexArrayObject(this._effect);
  35890. }
  35891. }
  35892. }
  35893. }
  35894. this._uniformBuffer.dispose();
  35895. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35896. if (forceDisposeEffect && this._effect) {
  35897. if (!this.storeEffectOnSubMeshes) {
  35898. this._scene.getEngine()._releaseEffect(this._effect);
  35899. }
  35900. this._effect = null;
  35901. }
  35902. // Callback
  35903. this.onDisposeObservable.notifyObservers(this);
  35904. this.onDisposeObservable.clear();
  35905. if (this._onBindObservable) {
  35906. this._onBindObservable.clear();
  35907. }
  35908. if (this._onUnBindObservable) {
  35909. this._onUnBindObservable.clear();
  35910. }
  35911. };
  35912. /**
  35913. * Serializes this material
  35914. * @returns the serialized material object
  35915. */
  35916. Material.prototype.serialize = function () {
  35917. return BABYLON.SerializationHelper.Serialize(this);
  35918. };
  35919. /**
  35920. * Creates a MultiMaterial from parsed MultiMaterial data.
  35921. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35922. * @param scene defines the hosting scene
  35923. * @returns a new MultiMaterial
  35924. */
  35925. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35926. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35927. multiMaterial.id = parsedMultiMaterial.id;
  35928. if (BABYLON.Tags) {
  35929. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35930. }
  35931. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35932. var subMatId = parsedMultiMaterial.materials[matIndex];
  35933. if (subMatId) {
  35934. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35935. }
  35936. else {
  35937. multiMaterial.subMaterials.push(null);
  35938. }
  35939. }
  35940. return multiMaterial;
  35941. };
  35942. /**
  35943. * Creates a material from parsed material data
  35944. * @param parsedMaterial defines parsed material data
  35945. * @param scene defines the hosting scene
  35946. * @param rootUrl defines the root URL to use to load textures
  35947. * @returns a new material
  35948. */
  35949. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35950. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35951. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35952. }
  35953. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35954. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35955. if (!BABYLON.LegacyPBRMaterial) {
  35956. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35957. return;
  35958. }
  35959. }
  35960. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35961. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35962. };
  35963. // Triangle views
  35964. Material._TriangleFillMode = 0;
  35965. Material._WireFrameFillMode = 1;
  35966. Material._PointFillMode = 2;
  35967. // Draw modes
  35968. Material._PointListDrawMode = 3;
  35969. Material._LineListDrawMode = 4;
  35970. Material._LineLoopDrawMode = 5;
  35971. Material._LineStripDrawMode = 6;
  35972. Material._TriangleStripDrawMode = 7;
  35973. Material._TriangleFanDrawMode = 8;
  35974. /**
  35975. * Stores the clock-wise side orientation
  35976. */
  35977. Material._ClockWiseSideOrientation = 0;
  35978. /**
  35979. * Stores the counter clock-wise side orientation
  35980. */
  35981. Material._CounterClockWiseSideOrientation = 1;
  35982. /**
  35983. * The dirty texture flag value
  35984. */
  35985. Material.TextureDirtyFlag = 1;
  35986. /**
  35987. * The dirty light flag value
  35988. */
  35989. Material.LightDirtyFlag = 2;
  35990. /**
  35991. * The dirty fresnel flag value
  35992. */
  35993. Material.FresnelDirtyFlag = 4;
  35994. /**
  35995. * The dirty attribute flag value
  35996. */
  35997. Material.AttributesDirtyFlag = 8;
  35998. /**
  35999. * The dirty misc flag value
  36000. */
  36001. Material.MiscDirtyFlag = 16;
  36002. /**
  36003. * The all dirty flag value
  36004. */
  36005. Material.AllDirtyFlag = 31;
  36006. __decorate([
  36007. BABYLON.serialize()
  36008. ], Material.prototype, "id", void 0);
  36009. __decorate([
  36010. BABYLON.serialize()
  36011. ], Material.prototype, "uniqueId", void 0);
  36012. __decorate([
  36013. BABYLON.serialize()
  36014. ], Material.prototype, "name", void 0);
  36015. __decorate([
  36016. BABYLON.serialize()
  36017. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36018. __decorate([
  36019. BABYLON.serialize()
  36020. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36021. __decorate([
  36022. BABYLON.serialize()
  36023. ], Material.prototype, "state", void 0);
  36024. __decorate([
  36025. BABYLON.serialize("alpha")
  36026. ], Material.prototype, "_alpha", void 0);
  36027. __decorate([
  36028. BABYLON.serialize("backFaceCulling")
  36029. ], Material.prototype, "_backFaceCulling", void 0);
  36030. __decorate([
  36031. BABYLON.serialize()
  36032. ], Material.prototype, "sideOrientation", void 0);
  36033. __decorate([
  36034. BABYLON.serialize("alphaMode")
  36035. ], Material.prototype, "_alphaMode", void 0);
  36036. __decorate([
  36037. BABYLON.serialize()
  36038. ], Material.prototype, "_needDepthPrePass", void 0);
  36039. __decorate([
  36040. BABYLON.serialize()
  36041. ], Material.prototype, "disableDepthWrite", void 0);
  36042. __decorate([
  36043. BABYLON.serialize()
  36044. ], Material.prototype, "forceDepthWrite", void 0);
  36045. __decorate([
  36046. BABYLON.serialize()
  36047. ], Material.prototype, "separateCullingPass", void 0);
  36048. __decorate([
  36049. BABYLON.serialize("fogEnabled")
  36050. ], Material.prototype, "_fogEnabled", void 0);
  36051. __decorate([
  36052. BABYLON.serialize()
  36053. ], Material.prototype, "pointSize", void 0);
  36054. __decorate([
  36055. BABYLON.serialize()
  36056. ], Material.prototype, "zOffset", void 0);
  36057. __decorate([
  36058. BABYLON.serialize()
  36059. ], Material.prototype, "wireframe", null);
  36060. __decorate([
  36061. BABYLON.serialize()
  36062. ], Material.prototype, "pointsCloud", null);
  36063. __decorate([
  36064. BABYLON.serialize()
  36065. ], Material.prototype, "fillMode", null);
  36066. return Material;
  36067. }());
  36068. BABYLON.Material = Material;
  36069. })(BABYLON || (BABYLON = {}));
  36070. //# sourceMappingURL=babylon.material.js.map
  36071. var BABYLON;
  36072. (function (BABYLON) {
  36073. var UniformBuffer = /** @class */ (function () {
  36074. /**
  36075. * Uniform buffer objects.
  36076. *
  36077. * Handles blocks of uniform on the GPU.
  36078. *
  36079. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36080. *
  36081. * For more information, please refer to :
  36082. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36083. */
  36084. function UniformBuffer(engine, data, dynamic) {
  36085. this._engine = engine;
  36086. this._noUBO = !engine.supportsUniformBuffers;
  36087. this._dynamic = dynamic;
  36088. this._data = data || [];
  36089. this._uniformLocations = {};
  36090. this._uniformSizes = {};
  36091. this._uniformLocationPointer = 0;
  36092. this._needSync = false;
  36093. if (this._noUBO) {
  36094. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36095. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36096. this.updateFloat = this._updateFloatForEffect;
  36097. this.updateFloat2 = this._updateFloat2ForEffect;
  36098. this.updateFloat3 = this._updateFloat3ForEffect;
  36099. this.updateFloat4 = this._updateFloat4ForEffect;
  36100. this.updateMatrix = this._updateMatrixForEffect;
  36101. this.updateVector3 = this._updateVector3ForEffect;
  36102. this.updateVector4 = this._updateVector4ForEffect;
  36103. this.updateColor3 = this._updateColor3ForEffect;
  36104. this.updateColor4 = this._updateColor4ForEffect;
  36105. }
  36106. else {
  36107. this._engine._uniformBuffers.push(this);
  36108. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36109. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36110. this.updateFloat = this._updateFloatForUniform;
  36111. this.updateFloat2 = this._updateFloat2ForUniform;
  36112. this.updateFloat3 = this._updateFloat3ForUniform;
  36113. this.updateFloat4 = this._updateFloat4ForUniform;
  36114. this.updateMatrix = this._updateMatrixForUniform;
  36115. this.updateVector3 = this._updateVector3ForUniform;
  36116. this.updateVector4 = this._updateVector4ForUniform;
  36117. this.updateColor3 = this._updateColor3ForUniform;
  36118. this.updateColor4 = this._updateColor4ForUniform;
  36119. }
  36120. }
  36121. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36122. // Properties
  36123. /**
  36124. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36125. * or just falling back on setUniformXXX calls.
  36126. */
  36127. get: function () {
  36128. return !this._noUBO;
  36129. },
  36130. enumerable: true,
  36131. configurable: true
  36132. });
  36133. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36134. /**
  36135. * Indicates if the WebGL underlying uniform buffer is in sync
  36136. * with the javascript cache data.
  36137. */
  36138. get: function () {
  36139. return !this._needSync;
  36140. },
  36141. enumerable: true,
  36142. configurable: true
  36143. });
  36144. /**
  36145. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36146. * Also, a dynamic UniformBuffer will disable cache verification and always
  36147. * update the underlying WebGL uniform buffer to the GPU.
  36148. */
  36149. UniformBuffer.prototype.isDynamic = function () {
  36150. return this._dynamic !== undefined;
  36151. };
  36152. /**
  36153. * The data cache on JS side.
  36154. */
  36155. UniformBuffer.prototype.getData = function () {
  36156. return this._bufferData;
  36157. };
  36158. /**
  36159. * The underlying WebGL Uniform buffer.
  36160. */
  36161. UniformBuffer.prototype.getBuffer = function () {
  36162. return this._buffer;
  36163. };
  36164. /**
  36165. * std140 layout specifies how to align data within an UBO structure.
  36166. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36167. * for specs.
  36168. */
  36169. UniformBuffer.prototype._fillAlignment = function (size) {
  36170. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36171. // and 4x4 matrices
  36172. // TODO : change if other types are used
  36173. var alignment;
  36174. if (size <= 2) {
  36175. alignment = size;
  36176. }
  36177. else {
  36178. alignment = 4;
  36179. }
  36180. if ((this._uniformLocationPointer % alignment) !== 0) {
  36181. var oldPointer = this._uniformLocationPointer;
  36182. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36183. var diff = this._uniformLocationPointer - oldPointer;
  36184. for (var i = 0; i < diff; i++) {
  36185. this._data.push(0);
  36186. }
  36187. }
  36188. };
  36189. /**
  36190. * Adds an uniform in the buffer.
  36191. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36192. * for the layout to be correct !
  36193. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36194. * @param {number|number[]} size Data size, or data directly.
  36195. */
  36196. UniformBuffer.prototype.addUniform = function (name, size) {
  36197. if (this._noUBO) {
  36198. return;
  36199. }
  36200. if (this._uniformLocations[name] !== undefined) {
  36201. // Already existing uniform
  36202. return;
  36203. }
  36204. // This function must be called in the order of the shader layout !
  36205. // size can be the size of the uniform, or data directly
  36206. var data;
  36207. if (size instanceof Array) {
  36208. data = size;
  36209. size = data.length;
  36210. }
  36211. else {
  36212. size = size;
  36213. data = [];
  36214. // Fill with zeros
  36215. for (var i = 0; i < size; i++) {
  36216. data.push(0);
  36217. }
  36218. }
  36219. this._fillAlignment(size);
  36220. this._uniformSizes[name] = size;
  36221. this._uniformLocations[name] = this._uniformLocationPointer;
  36222. this._uniformLocationPointer += size;
  36223. for (var i = 0; i < size; i++) {
  36224. this._data.push(data[i]);
  36225. }
  36226. this._needSync = true;
  36227. };
  36228. /**
  36229. * Wrapper for addUniform.
  36230. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36231. * @param {Matrix} mat A 4x4 matrix.
  36232. */
  36233. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36234. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36235. };
  36236. /**
  36237. * Wrapper for addUniform.
  36238. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36239. * @param {number} x
  36240. * @param {number} y
  36241. */
  36242. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36243. var temp = [x, y];
  36244. this.addUniform(name, temp);
  36245. };
  36246. /**
  36247. * Wrapper for addUniform.
  36248. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36249. * @param {number} x
  36250. * @param {number} y
  36251. * @param {number} z
  36252. */
  36253. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36254. var temp = [x, y, z];
  36255. this.addUniform(name, temp);
  36256. };
  36257. /**
  36258. * Wrapper for addUniform.
  36259. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36260. * @param {Color3} color
  36261. */
  36262. UniformBuffer.prototype.addColor3 = function (name, color) {
  36263. var temp = new Array();
  36264. color.toArray(temp);
  36265. this.addUniform(name, temp);
  36266. };
  36267. /**
  36268. * Wrapper for addUniform.
  36269. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36270. * @param {Color3} color
  36271. * @param {number} alpha
  36272. */
  36273. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36274. var temp = new Array();
  36275. color.toArray(temp);
  36276. temp.push(alpha);
  36277. this.addUniform(name, temp);
  36278. };
  36279. /**
  36280. * Wrapper for addUniform.
  36281. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36282. * @param {Vector3} vector
  36283. */
  36284. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36285. var temp = new Array();
  36286. vector.toArray(temp);
  36287. this.addUniform(name, temp);
  36288. };
  36289. /**
  36290. * Wrapper for addUniform.
  36291. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36292. */
  36293. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36294. this.addUniform(name, 12);
  36295. };
  36296. /**
  36297. * Wrapper for addUniform.
  36298. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36299. */
  36300. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36301. this.addUniform(name, 8);
  36302. };
  36303. /**
  36304. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36305. */
  36306. UniformBuffer.prototype.create = function () {
  36307. if (this._noUBO) {
  36308. return;
  36309. }
  36310. if (this._buffer) {
  36311. return; // nothing to do
  36312. }
  36313. // See spec, alignment must be filled as a vec4
  36314. this._fillAlignment(4);
  36315. this._bufferData = new Float32Array(this._data);
  36316. this._rebuild();
  36317. this._needSync = true;
  36318. };
  36319. /** @hidden */
  36320. UniformBuffer.prototype._rebuild = function () {
  36321. if (this._noUBO) {
  36322. return;
  36323. }
  36324. if (this._dynamic) {
  36325. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36326. }
  36327. else {
  36328. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36329. }
  36330. };
  36331. /**
  36332. * Updates the WebGL Uniform Buffer on the GPU.
  36333. * If the `dynamic` flag is set to true, no cache comparison is done.
  36334. * Otherwise, the buffer will be updated only if the cache differs.
  36335. */
  36336. UniformBuffer.prototype.update = function () {
  36337. if (!this._buffer) {
  36338. this.create();
  36339. return;
  36340. }
  36341. if (!this._dynamic && !this._needSync) {
  36342. return;
  36343. }
  36344. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36345. this._needSync = false;
  36346. };
  36347. /**
  36348. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36349. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36350. * @param {number[]|Float32Array} data Flattened data
  36351. * @param {number} size Size of the data.
  36352. */
  36353. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36354. var location = this._uniformLocations[uniformName];
  36355. if (location === undefined) {
  36356. if (this._buffer) {
  36357. // Cannot add an uniform if the buffer is already created
  36358. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36359. return;
  36360. }
  36361. this.addUniform(uniformName, size);
  36362. location = this._uniformLocations[uniformName];
  36363. }
  36364. if (!this._buffer) {
  36365. this.create();
  36366. }
  36367. if (!this._dynamic) {
  36368. // Cache for static uniform buffers
  36369. var changed = false;
  36370. for (var i = 0; i < size; i++) {
  36371. if (this._bufferData[location + i] !== data[i]) {
  36372. changed = true;
  36373. this._bufferData[location + i] = data[i];
  36374. }
  36375. }
  36376. this._needSync = this._needSync || changed;
  36377. }
  36378. else {
  36379. // No cache for dynamic
  36380. for (var i = 0; i < size; i++) {
  36381. this._bufferData[location + i] = data[i];
  36382. }
  36383. }
  36384. };
  36385. // Update methods
  36386. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36387. // To match std140, matrix must be realigned
  36388. for (var i = 0; i < 3; i++) {
  36389. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36390. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36391. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36392. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36393. }
  36394. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36395. };
  36396. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36397. this._currentEffect.setMatrix3x3(name, matrix);
  36398. };
  36399. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36400. this._currentEffect.setMatrix2x2(name, matrix);
  36401. };
  36402. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36403. // To match std140, matrix must be realigned
  36404. for (var i = 0; i < 2; i++) {
  36405. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36406. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36407. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36408. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36409. }
  36410. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36411. };
  36412. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36413. this._currentEffect.setFloat(name, x);
  36414. };
  36415. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36416. UniformBuffer._tempBuffer[0] = x;
  36417. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36418. };
  36419. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36420. if (suffix === void 0) { suffix = ""; }
  36421. this._currentEffect.setFloat2(name + suffix, x, y);
  36422. };
  36423. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36424. if (suffix === void 0) { suffix = ""; }
  36425. UniformBuffer._tempBuffer[0] = x;
  36426. UniformBuffer._tempBuffer[1] = y;
  36427. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36428. };
  36429. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36430. if (suffix === void 0) { suffix = ""; }
  36431. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36432. };
  36433. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36434. if (suffix === void 0) { suffix = ""; }
  36435. UniformBuffer._tempBuffer[0] = x;
  36436. UniformBuffer._tempBuffer[1] = y;
  36437. UniformBuffer._tempBuffer[2] = z;
  36438. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36439. };
  36440. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36441. if (suffix === void 0) { suffix = ""; }
  36442. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36443. };
  36444. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36445. if (suffix === void 0) { suffix = ""; }
  36446. UniformBuffer._tempBuffer[0] = x;
  36447. UniformBuffer._tempBuffer[1] = y;
  36448. UniformBuffer._tempBuffer[2] = z;
  36449. UniformBuffer._tempBuffer[3] = w;
  36450. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36451. };
  36452. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36453. this._currentEffect.setMatrix(name, mat);
  36454. };
  36455. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36456. this.updateUniform(name, mat.toArray(), 16);
  36457. };
  36458. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36459. this._currentEffect.setVector3(name, vector);
  36460. };
  36461. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36462. vector.toArray(UniformBuffer._tempBuffer);
  36463. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36464. };
  36465. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36466. this._currentEffect.setVector4(name, vector);
  36467. };
  36468. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36469. vector.toArray(UniformBuffer._tempBuffer);
  36470. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36471. };
  36472. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36473. if (suffix === void 0) { suffix = ""; }
  36474. this._currentEffect.setColor3(name + suffix, color);
  36475. };
  36476. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36477. if (suffix === void 0) { suffix = ""; }
  36478. color.toArray(UniformBuffer._tempBuffer);
  36479. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36480. };
  36481. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36482. if (suffix === void 0) { suffix = ""; }
  36483. this._currentEffect.setColor4(name + suffix, color, alpha);
  36484. };
  36485. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36486. if (suffix === void 0) { suffix = ""; }
  36487. color.toArray(UniformBuffer._tempBuffer);
  36488. UniformBuffer._tempBuffer[3] = alpha;
  36489. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36490. };
  36491. /**
  36492. * Sets a sampler uniform on the effect.
  36493. * @param {string} name Name of the sampler.
  36494. * @param {Texture} texture
  36495. */
  36496. UniformBuffer.prototype.setTexture = function (name, texture) {
  36497. this._currentEffect.setTexture(name, texture);
  36498. };
  36499. /**
  36500. * Directly updates the value of the uniform in the cache AND on the GPU.
  36501. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36502. * @param {number[]|Float32Array} data Flattened data
  36503. */
  36504. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36505. this.updateUniform(uniformName, data, data.length);
  36506. this.update();
  36507. };
  36508. /**
  36509. * Binds this uniform buffer to an effect.
  36510. * @param {Effect} effect
  36511. * @param {string} name Name of the uniform block in the shader.
  36512. */
  36513. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36514. this._currentEffect = effect;
  36515. if (this._noUBO || !this._buffer) {
  36516. return;
  36517. }
  36518. effect.bindUniformBuffer(this._buffer, name);
  36519. };
  36520. /**
  36521. * Disposes the uniform buffer.
  36522. */
  36523. UniformBuffer.prototype.dispose = function () {
  36524. if (this._noUBO) {
  36525. return;
  36526. }
  36527. var index = this._engine._uniformBuffers.indexOf(this);
  36528. if (index !== -1) {
  36529. this._engine._uniformBuffers.splice(index, 1);
  36530. }
  36531. if (!this._buffer) {
  36532. return;
  36533. }
  36534. if (this._engine._releaseBuffer(this._buffer)) {
  36535. this._buffer = null;
  36536. }
  36537. };
  36538. // Pool for avoiding memory leaks
  36539. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36540. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36541. return UniformBuffer;
  36542. }());
  36543. BABYLON.UniformBuffer = UniformBuffer;
  36544. })(BABYLON || (BABYLON = {}));
  36545. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36546. var BABYLON;
  36547. (function (BABYLON) {
  36548. /**
  36549. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36550. */
  36551. var VertexData = /** @class */ (function () {
  36552. function VertexData() {
  36553. }
  36554. /**
  36555. * Uses the passed data array to set the set the values for the specified kind of data
  36556. * @param data a linear array of floating numbers
  36557. * @param kind the type of data that is being set, eg positions, colors etc
  36558. */
  36559. VertexData.prototype.set = function (data, kind) {
  36560. switch (kind) {
  36561. case BABYLON.VertexBuffer.PositionKind:
  36562. this.positions = data;
  36563. break;
  36564. case BABYLON.VertexBuffer.NormalKind:
  36565. this.normals = data;
  36566. break;
  36567. case BABYLON.VertexBuffer.TangentKind:
  36568. this.tangents = data;
  36569. break;
  36570. case BABYLON.VertexBuffer.UVKind:
  36571. this.uvs = data;
  36572. break;
  36573. case BABYLON.VertexBuffer.UV2Kind:
  36574. this.uvs2 = data;
  36575. break;
  36576. case BABYLON.VertexBuffer.UV3Kind:
  36577. this.uvs3 = data;
  36578. break;
  36579. case BABYLON.VertexBuffer.UV4Kind:
  36580. this.uvs4 = data;
  36581. break;
  36582. case BABYLON.VertexBuffer.UV5Kind:
  36583. this.uvs5 = data;
  36584. break;
  36585. case BABYLON.VertexBuffer.UV6Kind:
  36586. this.uvs6 = data;
  36587. break;
  36588. case BABYLON.VertexBuffer.ColorKind:
  36589. this.colors = data;
  36590. break;
  36591. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36592. this.matricesIndices = data;
  36593. break;
  36594. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36595. this.matricesWeights = data;
  36596. break;
  36597. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36598. this.matricesIndicesExtra = data;
  36599. break;
  36600. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36601. this.matricesWeightsExtra = data;
  36602. break;
  36603. }
  36604. };
  36605. /**
  36606. * Associates the vertexData to the passed Mesh.
  36607. * Sets it as updatable or not (default `false`)
  36608. * @param mesh the mesh the vertexData is applied to
  36609. * @param updatable when used and having the value true allows new data to update the vertexData
  36610. * @returns the VertexData
  36611. */
  36612. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36613. this._applyTo(mesh, updatable);
  36614. return this;
  36615. };
  36616. /**
  36617. * Associates the vertexData to the passed Geometry.
  36618. * Sets it as updatable or not (default `false`)
  36619. * @param geometry the geometry the vertexData is applied to
  36620. * @param updatable when used and having the value true allows new data to update the vertexData
  36621. * @returns VertexData
  36622. */
  36623. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36624. this._applyTo(geometry, updatable);
  36625. return this;
  36626. };
  36627. /**
  36628. * Updates the associated mesh
  36629. * @param mesh the mesh to be updated
  36630. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36631. * @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
  36632. * @returns VertexData
  36633. */
  36634. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36635. this._update(mesh);
  36636. return this;
  36637. };
  36638. /**
  36639. * Updates the associated geometry
  36640. * @param geometry the geometry to be updated
  36641. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36642. * @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
  36643. * @returns VertexData.
  36644. */
  36645. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36646. this._update(geometry);
  36647. return this;
  36648. };
  36649. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36650. if (updatable === void 0) { updatable = false; }
  36651. if (this.positions) {
  36652. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36653. }
  36654. if (this.normals) {
  36655. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36656. }
  36657. if (this.tangents) {
  36658. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36659. }
  36660. if (this.uvs) {
  36661. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36662. }
  36663. if (this.uvs2) {
  36664. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36665. }
  36666. if (this.uvs3) {
  36667. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36668. }
  36669. if (this.uvs4) {
  36670. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36671. }
  36672. if (this.uvs5) {
  36673. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36674. }
  36675. if (this.uvs6) {
  36676. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36677. }
  36678. if (this.colors) {
  36679. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36680. }
  36681. if (this.matricesIndices) {
  36682. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36683. }
  36684. if (this.matricesWeights) {
  36685. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36686. }
  36687. if (this.matricesIndicesExtra) {
  36688. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36689. }
  36690. if (this.matricesWeightsExtra) {
  36691. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36692. }
  36693. if (this.indices) {
  36694. meshOrGeometry.setIndices(this.indices, null, updatable);
  36695. }
  36696. else {
  36697. meshOrGeometry.setIndices([], null);
  36698. }
  36699. return this;
  36700. };
  36701. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36702. if (this.positions) {
  36703. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36704. }
  36705. if (this.normals) {
  36706. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36707. }
  36708. if (this.tangents) {
  36709. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36710. }
  36711. if (this.uvs) {
  36712. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36713. }
  36714. if (this.uvs2) {
  36715. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36716. }
  36717. if (this.uvs3) {
  36718. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36719. }
  36720. if (this.uvs4) {
  36721. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36722. }
  36723. if (this.uvs5) {
  36724. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36725. }
  36726. if (this.uvs6) {
  36727. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36728. }
  36729. if (this.colors) {
  36730. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36731. }
  36732. if (this.matricesIndices) {
  36733. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36734. }
  36735. if (this.matricesWeights) {
  36736. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36737. }
  36738. if (this.matricesIndicesExtra) {
  36739. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36740. }
  36741. if (this.matricesWeightsExtra) {
  36742. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36743. }
  36744. if (this.indices) {
  36745. meshOrGeometry.setIndices(this.indices, null);
  36746. }
  36747. return this;
  36748. };
  36749. /**
  36750. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36751. * @param matrix the transforming matrix
  36752. * @returns the VertexData
  36753. */
  36754. VertexData.prototype.transform = function (matrix) {
  36755. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36756. var transformed = BABYLON.Vector3.Zero();
  36757. var index;
  36758. if (this.positions) {
  36759. var position = BABYLON.Vector3.Zero();
  36760. for (index = 0; index < this.positions.length; index += 3) {
  36761. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36762. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36763. this.positions[index] = transformed.x;
  36764. this.positions[index + 1] = transformed.y;
  36765. this.positions[index + 2] = transformed.z;
  36766. }
  36767. }
  36768. if (this.normals) {
  36769. var normal = BABYLON.Vector3.Zero();
  36770. for (index = 0; index < this.normals.length; index += 3) {
  36771. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36772. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36773. this.normals[index] = transformed.x;
  36774. this.normals[index + 1] = transformed.y;
  36775. this.normals[index + 2] = transformed.z;
  36776. }
  36777. }
  36778. if (this.tangents) {
  36779. var tangent = BABYLON.Vector4.Zero();
  36780. var tangentTransformed = BABYLON.Vector4.Zero();
  36781. for (index = 0; index < this.tangents.length; index += 4) {
  36782. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36783. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36784. this.tangents[index] = tangentTransformed.x;
  36785. this.tangents[index + 1] = tangentTransformed.y;
  36786. this.tangents[index + 2] = tangentTransformed.z;
  36787. this.tangents[index + 3] = tangentTransformed.w;
  36788. }
  36789. }
  36790. if (flip && this.indices) {
  36791. for (index = 0; index < this.indices.length; index += 3) {
  36792. var tmp = this.indices[index + 1];
  36793. this.indices[index + 1] = this.indices[index + 2];
  36794. this.indices[index + 2] = tmp;
  36795. }
  36796. }
  36797. return this;
  36798. };
  36799. /**
  36800. * Merges the passed VertexData into the current one
  36801. * @param other the VertexData to be merged into the current one
  36802. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36803. * @returns the modified VertexData
  36804. */
  36805. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36806. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36807. this._validate();
  36808. other._validate();
  36809. if (!this.normals !== !other.normals ||
  36810. !this.tangents !== !other.tangents ||
  36811. !this.uvs !== !other.uvs ||
  36812. !this.uvs2 !== !other.uvs2 ||
  36813. !this.uvs3 !== !other.uvs3 ||
  36814. !this.uvs4 !== !other.uvs4 ||
  36815. !this.uvs5 !== !other.uvs5 ||
  36816. !this.uvs6 !== !other.uvs6 ||
  36817. !this.colors !== !other.colors ||
  36818. !this.matricesIndices !== !other.matricesIndices ||
  36819. !this.matricesWeights !== !other.matricesWeights ||
  36820. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36821. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36822. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36823. }
  36824. if (other.indices) {
  36825. if (!this.indices) {
  36826. this.indices = [];
  36827. }
  36828. var offset = this.positions ? this.positions.length / 3 : 0;
  36829. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36830. if (isSrcTypedArray) {
  36831. var len = this.indices.length + other.indices.length;
  36832. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36833. temp.set(this.indices);
  36834. var decal = this.indices.length;
  36835. for (var index = 0; index < other.indices.length; index++) {
  36836. temp[decal + index] = other.indices[index] + offset;
  36837. }
  36838. this.indices = temp;
  36839. }
  36840. else {
  36841. for (var index = 0; index < other.indices.length; index++) {
  36842. this.indices.push(other.indices[index] + offset);
  36843. }
  36844. }
  36845. }
  36846. this.positions = this._mergeElement(this.positions, other.positions);
  36847. this.normals = this._mergeElement(this.normals, other.normals);
  36848. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36849. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36850. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36851. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36852. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36853. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36854. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36855. this.colors = this._mergeElement(this.colors, other.colors);
  36856. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36857. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36858. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36859. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36860. return this;
  36861. };
  36862. VertexData.prototype._mergeElement = function (source, other) {
  36863. if (!source) {
  36864. return other;
  36865. }
  36866. if (!other) {
  36867. return source;
  36868. }
  36869. var len = other.length + source.length;
  36870. var isSrcTypedArray = source instanceof Float32Array;
  36871. var isOthTypedArray = other instanceof Float32Array;
  36872. // use non-loop method when the source is Float32Array
  36873. if (isSrcTypedArray) {
  36874. var ret32 = new Float32Array(len);
  36875. ret32.set(source);
  36876. ret32.set(other, source.length);
  36877. return ret32;
  36878. // source is number[], when other is also use concat
  36879. }
  36880. else if (!isOthTypedArray) {
  36881. return source.concat(other);
  36882. // source is a number[], but other is a Float32Array, loop required
  36883. }
  36884. else {
  36885. var ret = source.slice(0); // copy source to a separate array
  36886. for (var i = 0, len = other.length; i < len; i++) {
  36887. ret.push(other[i]);
  36888. }
  36889. return ret;
  36890. }
  36891. };
  36892. VertexData.prototype._validate = function () {
  36893. if (!this.positions) {
  36894. throw new Error("Positions are required");
  36895. }
  36896. var getElementCount = function (kind, values) {
  36897. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36898. if ((values.length % stride) !== 0) {
  36899. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36900. }
  36901. return values.length / stride;
  36902. };
  36903. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36904. var validateElementCount = function (kind, values) {
  36905. var elementCount = getElementCount(kind, values);
  36906. if (elementCount !== positionsElementCount) {
  36907. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36908. }
  36909. };
  36910. if (this.normals)
  36911. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36912. if (this.tangents)
  36913. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36914. if (this.uvs)
  36915. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36916. if (this.uvs2)
  36917. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36918. if (this.uvs3)
  36919. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36920. if (this.uvs4)
  36921. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36922. if (this.uvs5)
  36923. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36924. if (this.uvs6)
  36925. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36926. if (this.colors)
  36927. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36928. if (this.matricesIndices)
  36929. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36930. if (this.matricesWeights)
  36931. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36932. if (this.matricesIndicesExtra)
  36933. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36934. if (this.matricesWeightsExtra)
  36935. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36936. };
  36937. /**
  36938. * Serializes the VertexData
  36939. * @returns a serialized object
  36940. */
  36941. VertexData.prototype.serialize = function () {
  36942. var serializationObject = this.serialize();
  36943. if (this.positions) {
  36944. serializationObject.positions = this.positions;
  36945. }
  36946. if (this.normals) {
  36947. serializationObject.normals = this.normals;
  36948. }
  36949. if (this.tangents) {
  36950. serializationObject.tangents = this.tangents;
  36951. }
  36952. if (this.uvs) {
  36953. serializationObject.uvs = this.uvs;
  36954. }
  36955. if (this.uvs2) {
  36956. serializationObject.uvs2 = this.uvs2;
  36957. }
  36958. if (this.uvs3) {
  36959. serializationObject.uvs3 = this.uvs3;
  36960. }
  36961. if (this.uvs4) {
  36962. serializationObject.uvs4 = this.uvs4;
  36963. }
  36964. if (this.uvs5) {
  36965. serializationObject.uvs5 = this.uvs5;
  36966. }
  36967. if (this.uvs6) {
  36968. serializationObject.uvs6 = this.uvs6;
  36969. }
  36970. if (this.colors) {
  36971. serializationObject.colors = this.colors;
  36972. }
  36973. if (this.matricesIndices) {
  36974. serializationObject.matricesIndices = this.matricesIndices;
  36975. serializationObject.matricesIndices._isExpanded = true;
  36976. }
  36977. if (this.matricesWeights) {
  36978. serializationObject.matricesWeights = this.matricesWeights;
  36979. }
  36980. if (this.matricesIndicesExtra) {
  36981. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36982. serializationObject.matricesIndicesExtra._isExpanded = true;
  36983. }
  36984. if (this.matricesWeightsExtra) {
  36985. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36986. }
  36987. serializationObject.indices = this.indices;
  36988. return serializationObject;
  36989. };
  36990. // Statics
  36991. /**
  36992. * Extracts the vertexData from a mesh
  36993. * @param mesh the mesh from which to extract the VertexData
  36994. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36995. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36996. * @returns the object VertexData associated to the passed mesh
  36997. */
  36998. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36999. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37000. };
  37001. /**
  37002. * Extracts the vertexData from the geometry
  37003. * @param geometry the geometry from which to extract the VertexData
  37004. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37005. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37006. * @returns the object VertexData associated to the passed mesh
  37007. */
  37008. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37009. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37010. };
  37011. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37012. var result = new VertexData();
  37013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37014. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37015. }
  37016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37017. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37018. }
  37019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37020. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37021. }
  37022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37023. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37024. }
  37025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37026. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37027. }
  37028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37029. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37030. }
  37031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37032. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37033. }
  37034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37035. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37036. }
  37037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37038. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37039. }
  37040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37041. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37042. }
  37043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37044. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37045. }
  37046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37047. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37048. }
  37049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37050. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37051. }
  37052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37053. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37054. }
  37055. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  37056. return result;
  37057. };
  37058. /**
  37059. * Creates the VertexData for a Ribbon
  37060. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37061. * * pathArray array of paths, each of which an array of successive Vector3
  37062. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37063. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37064. * * 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
  37065. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37066. * * 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)
  37067. * * 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)
  37068. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37069. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37070. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37071. * @returns the VertexData of the ribbon
  37072. */
  37073. VertexData.CreateRibbon = function (options) {
  37074. var pathArray = options.pathArray;
  37075. var closeArray = options.closeArray || false;
  37076. var closePath = options.closePath || false;
  37077. var invertUV = options.invertUV || false;
  37078. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37079. var offset = options.offset || defaultOffset;
  37080. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37081. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37082. var customUV = options.uvs;
  37083. var customColors = options.colors;
  37084. var positions = [];
  37085. var indices = [];
  37086. var normals = [];
  37087. var uvs = [];
  37088. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37089. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37090. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37091. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37092. var minlg; // minimal length among all paths from pathArray
  37093. var lg = []; // array of path lengths : nb of vertex per path
  37094. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37095. var p; // path iterator
  37096. var i; // point iterator
  37097. var j; // point iterator
  37098. // if single path in pathArray
  37099. if (pathArray.length < 2) {
  37100. var ar1 = [];
  37101. var ar2 = [];
  37102. for (i = 0; i < pathArray[0].length - offset; i++) {
  37103. ar1.push(pathArray[0][i]);
  37104. ar2.push(pathArray[0][i + offset]);
  37105. }
  37106. pathArray = [ar1, ar2];
  37107. }
  37108. // positions and horizontal distances (u)
  37109. var idc = 0;
  37110. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37111. var path;
  37112. var l;
  37113. minlg = pathArray[0].length;
  37114. var vectlg;
  37115. var dist;
  37116. for (p = 0; p < pathArray.length; p++) {
  37117. uTotalDistance[p] = 0;
  37118. us[p] = [0];
  37119. path = pathArray[p];
  37120. l = path.length;
  37121. minlg = (minlg < l) ? minlg : l;
  37122. j = 0;
  37123. while (j < l) {
  37124. positions.push(path[j].x, path[j].y, path[j].z);
  37125. if (j > 0) {
  37126. vectlg = path[j].subtract(path[j - 1]).length();
  37127. dist = vectlg + uTotalDistance[p];
  37128. us[p].push(dist);
  37129. uTotalDistance[p] = dist;
  37130. }
  37131. j++;
  37132. }
  37133. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37134. j--;
  37135. positions.push(path[0].x, path[0].y, path[0].z);
  37136. vectlg = path[j].subtract(path[0]).length();
  37137. dist = vectlg + uTotalDistance[p];
  37138. us[p].push(dist);
  37139. uTotalDistance[p] = dist;
  37140. }
  37141. lg[p] = l + closePathCorr;
  37142. idx[p] = idc;
  37143. idc += (l + closePathCorr);
  37144. }
  37145. // vertical distances (v)
  37146. var path1;
  37147. var path2;
  37148. var vertex1 = null;
  37149. var vertex2 = null;
  37150. for (i = 0; i < minlg + closePathCorr; i++) {
  37151. vTotalDistance[i] = 0;
  37152. vs[i] = [0];
  37153. for (p = 0; p < pathArray.length - 1; p++) {
  37154. path1 = pathArray[p];
  37155. path2 = pathArray[p + 1];
  37156. if (i === minlg) { // closePath
  37157. vertex1 = path1[0];
  37158. vertex2 = path2[0];
  37159. }
  37160. else {
  37161. vertex1 = path1[i];
  37162. vertex2 = path2[i];
  37163. }
  37164. vectlg = vertex2.subtract(vertex1).length();
  37165. dist = vectlg + vTotalDistance[i];
  37166. vs[i].push(dist);
  37167. vTotalDistance[i] = dist;
  37168. }
  37169. if (closeArray && vertex2 && vertex1) {
  37170. path1 = pathArray[p];
  37171. path2 = pathArray[0];
  37172. if (i === minlg) { // closePath
  37173. vertex2 = path2[0];
  37174. }
  37175. vectlg = vertex2.subtract(vertex1).length();
  37176. dist = vectlg + vTotalDistance[i];
  37177. vTotalDistance[i] = dist;
  37178. }
  37179. }
  37180. // uvs
  37181. var u;
  37182. var v;
  37183. if (customUV) {
  37184. for (p = 0; p < customUV.length; p++) {
  37185. uvs.push(customUV[p].x, customUV[p].y);
  37186. }
  37187. }
  37188. else {
  37189. for (p = 0; p < pathArray.length; p++) {
  37190. for (i = 0; i < minlg + closePathCorr; i++) {
  37191. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37192. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37193. if (invertUV) {
  37194. uvs.push(v, u);
  37195. }
  37196. else {
  37197. uvs.push(u, v);
  37198. }
  37199. }
  37200. }
  37201. }
  37202. // indices
  37203. p = 0; // path index
  37204. var pi = 0; // positions array index
  37205. var l1 = lg[p] - 1; // path1 length
  37206. var l2 = lg[p + 1] - 1; // path2 length
  37207. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37208. var shft = idx[1] - idx[0]; // shift
  37209. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37210. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37211. // 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
  37212. indices.push(pi, pi + shft, pi + 1);
  37213. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37214. pi += 1;
  37215. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37216. p++;
  37217. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37218. shft = idx[0] - idx[p];
  37219. l1 = lg[p] - 1;
  37220. l2 = lg[0] - 1;
  37221. }
  37222. else {
  37223. shft = idx[p + 1] - idx[p];
  37224. l1 = lg[p] - 1;
  37225. l2 = lg[p + 1] - 1;
  37226. }
  37227. pi = idx[p];
  37228. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37229. }
  37230. }
  37231. // normals
  37232. VertexData.ComputeNormals(positions, indices, normals);
  37233. if (closePath) { // update both the first and last vertex normals to their average value
  37234. var indexFirst = 0;
  37235. var indexLast = 0;
  37236. for (p = 0; p < pathArray.length; p++) {
  37237. indexFirst = idx[p] * 3;
  37238. if (p + 1 < pathArray.length) {
  37239. indexLast = (idx[p + 1] - 1) * 3;
  37240. }
  37241. else {
  37242. indexLast = normals.length - 3;
  37243. }
  37244. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37245. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37246. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37247. normals[indexLast] = normals[indexFirst];
  37248. normals[indexLast + 1] = normals[indexFirst + 1];
  37249. normals[indexLast + 2] = normals[indexFirst + 2];
  37250. }
  37251. }
  37252. // sides
  37253. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37254. // Colors
  37255. var colors = null;
  37256. if (customColors) {
  37257. colors = new Float32Array(customColors.length * 4);
  37258. for (var c = 0; c < customColors.length; c++) {
  37259. colors[c * 4] = customColors[c].r;
  37260. colors[c * 4 + 1] = customColors[c].g;
  37261. colors[c * 4 + 2] = customColors[c].b;
  37262. colors[c * 4 + 3] = customColors[c].a;
  37263. }
  37264. }
  37265. // Result
  37266. var vertexData = new VertexData();
  37267. var positions32 = new Float32Array(positions);
  37268. var normals32 = new Float32Array(normals);
  37269. var uvs32 = new Float32Array(uvs);
  37270. vertexData.indices = indices;
  37271. vertexData.positions = positions32;
  37272. vertexData.normals = normals32;
  37273. vertexData.uvs = uvs32;
  37274. if (colors) {
  37275. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37276. }
  37277. if (closePath) {
  37278. vertexData._idx = idx;
  37279. }
  37280. return vertexData;
  37281. };
  37282. /**
  37283. * Creates the VertexData for a box
  37284. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37285. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37286. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37287. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37288. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37289. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37290. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37291. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37292. * * 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)
  37293. * * 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)
  37294. * @returns the VertexData of the box
  37295. */
  37296. VertexData.CreateBox = function (options) {
  37297. var normalsSource = [
  37298. new BABYLON.Vector3(0, 0, 1),
  37299. new BABYLON.Vector3(0, 0, -1),
  37300. new BABYLON.Vector3(1, 0, 0),
  37301. new BABYLON.Vector3(-1, 0, 0),
  37302. new BABYLON.Vector3(0, 1, 0),
  37303. new BABYLON.Vector3(0, -1, 0)
  37304. ];
  37305. var indices = [];
  37306. var positions = [];
  37307. var normals = [];
  37308. var uvs = [];
  37309. var width = options.width || options.size || 1;
  37310. var height = options.height || options.size || 1;
  37311. var depth = options.depth || options.size || 1;
  37312. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37313. var faceUV = options.faceUV || new Array(6);
  37314. var faceColors = options.faceColors;
  37315. var colors = [];
  37316. // default face colors and UV if undefined
  37317. for (var f = 0; f < 6; f++) {
  37318. if (faceUV[f] === undefined) {
  37319. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37320. }
  37321. if (faceColors && faceColors[f] === undefined) {
  37322. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37323. }
  37324. }
  37325. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37326. // Create each face in turn.
  37327. for (var index = 0; index < normalsSource.length; index++) {
  37328. var normal = normalsSource[index];
  37329. // Get two vectors perpendicular to the face normal and to each other.
  37330. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37331. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37332. // Six indices (two triangles) per face.
  37333. var verticesLength = positions.length / 3;
  37334. indices.push(verticesLength);
  37335. indices.push(verticesLength + 1);
  37336. indices.push(verticesLength + 2);
  37337. indices.push(verticesLength);
  37338. indices.push(verticesLength + 2);
  37339. indices.push(verticesLength + 3);
  37340. // Four vertices per face.
  37341. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37342. positions.push(vertex.x, vertex.y, vertex.z);
  37343. normals.push(normal.x, normal.y, normal.z);
  37344. uvs.push(faceUV[index].z, faceUV[index].w);
  37345. if (faceColors) {
  37346. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37347. }
  37348. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37349. positions.push(vertex.x, vertex.y, vertex.z);
  37350. normals.push(normal.x, normal.y, normal.z);
  37351. uvs.push(faceUV[index].x, faceUV[index].w);
  37352. if (faceColors) {
  37353. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37354. }
  37355. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37356. positions.push(vertex.x, vertex.y, vertex.z);
  37357. normals.push(normal.x, normal.y, normal.z);
  37358. uvs.push(faceUV[index].x, faceUV[index].y);
  37359. if (faceColors) {
  37360. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37361. }
  37362. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37363. positions.push(vertex.x, vertex.y, vertex.z);
  37364. normals.push(normal.x, normal.y, normal.z);
  37365. uvs.push(faceUV[index].z, faceUV[index].y);
  37366. if (faceColors) {
  37367. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37368. }
  37369. }
  37370. // sides
  37371. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37372. // Result
  37373. var vertexData = new VertexData();
  37374. vertexData.indices = indices;
  37375. vertexData.positions = positions;
  37376. vertexData.normals = normals;
  37377. vertexData.uvs = uvs;
  37378. if (faceColors) {
  37379. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37380. vertexData.colors = totalColors;
  37381. }
  37382. return vertexData;
  37383. };
  37384. /**
  37385. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37386. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37387. * * segments sets the number of horizontal strips optional, default 32
  37388. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37389. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37390. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37391. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37392. * * 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
  37393. * * 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
  37394. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37395. * * 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)
  37396. * * 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)
  37397. * @returns the VertexData of the ellipsoid
  37398. */
  37399. VertexData.CreateSphere = function (options) {
  37400. var segments = options.segments || 32;
  37401. var diameterX = options.diameterX || options.diameter || 1;
  37402. var diameterY = options.diameterY || options.diameter || 1;
  37403. var diameterZ = options.diameterZ || options.diameter || 1;
  37404. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37405. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37406. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37407. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37408. var totalZRotationSteps = 2 + segments;
  37409. var totalYRotationSteps = 2 * totalZRotationSteps;
  37410. var indices = [];
  37411. var positions = [];
  37412. var normals = [];
  37413. var uvs = [];
  37414. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37415. var normalizedZ = zRotationStep / totalZRotationSteps;
  37416. var angleZ = normalizedZ * Math.PI * slice;
  37417. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37418. var normalizedY = yRotationStep / totalYRotationSteps;
  37419. var angleY = normalizedY * Math.PI * 2 * arc;
  37420. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37421. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37422. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37423. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37424. var vertex = complete.multiply(radius);
  37425. var normal = complete.divide(radius).normalize();
  37426. positions.push(vertex.x, vertex.y, vertex.z);
  37427. normals.push(normal.x, normal.y, normal.z);
  37428. uvs.push(normalizedY, normalizedZ);
  37429. }
  37430. if (zRotationStep > 0) {
  37431. var verticesCount = positions.length / 3;
  37432. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37433. indices.push((firstIndex));
  37434. indices.push((firstIndex + 1));
  37435. indices.push(firstIndex + totalYRotationSteps + 1);
  37436. indices.push((firstIndex + totalYRotationSteps + 1));
  37437. indices.push((firstIndex + 1));
  37438. indices.push((firstIndex + totalYRotationSteps + 2));
  37439. }
  37440. }
  37441. }
  37442. // Sides
  37443. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37444. // Result
  37445. var vertexData = new VertexData();
  37446. vertexData.indices = indices;
  37447. vertexData.positions = positions;
  37448. vertexData.normals = normals;
  37449. vertexData.uvs = uvs;
  37450. return vertexData;
  37451. };
  37452. /**
  37453. * Creates the VertexData for a cylinder, cone or prism
  37454. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37455. * * height sets the height (y direction) of the cylinder, optional, default 2
  37456. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37457. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37458. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37459. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37460. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37461. * * 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
  37462. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37463. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37464. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37465. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37466. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37467. * * 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)
  37468. * * 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)
  37469. * @returns the VertexData of the cylinder, cone or prism
  37470. */
  37471. VertexData.CreateCylinder = function (options) {
  37472. var height = options.height || 2;
  37473. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37474. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37475. var tessellation = options.tessellation || 24;
  37476. var subdivisions = options.subdivisions || 1;
  37477. var hasRings = options.hasRings ? true : false;
  37478. var enclose = options.enclose ? true : false;
  37479. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37480. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37481. var faceUV = options.faceUV || new Array(3);
  37482. var faceColors = options.faceColors;
  37483. // default face colors and UV if undefined
  37484. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37485. var ringNb = (hasRings) ? subdivisions : 1;
  37486. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37487. var f;
  37488. for (f = 0; f < surfaceNb; f++) {
  37489. if (faceColors && faceColors[f] === undefined) {
  37490. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37491. }
  37492. }
  37493. for (f = 0; f < surfaceNb; f++) {
  37494. if (faceUV && faceUV[f] === undefined) {
  37495. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37496. }
  37497. }
  37498. var indices = new Array();
  37499. var positions = new Array();
  37500. var normals = new Array();
  37501. var uvs = new Array();
  37502. var colors = new Array();
  37503. var angle_step = Math.PI * 2 * arc / tessellation;
  37504. var angle;
  37505. var h;
  37506. var radius;
  37507. var tan = (diameterBottom - diameterTop) / 2 / height;
  37508. var ringVertex = BABYLON.Vector3.Zero();
  37509. var ringNormal = BABYLON.Vector3.Zero();
  37510. var ringFirstVertex = BABYLON.Vector3.Zero();
  37511. var ringFirstNormal = BABYLON.Vector3.Zero();
  37512. var quadNormal = BABYLON.Vector3.Zero();
  37513. var Y = BABYLON.Axis.Y;
  37514. // positions, normals, uvs
  37515. var i;
  37516. var j;
  37517. var r;
  37518. var ringIdx = 1;
  37519. var s = 1; // surface index
  37520. var cs = 0;
  37521. var v = 0;
  37522. for (i = 0; i <= subdivisions; i++) {
  37523. h = i / subdivisions;
  37524. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37525. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37526. for (r = 0; r < ringIdx; r++) {
  37527. if (hasRings) {
  37528. s += r;
  37529. }
  37530. if (enclose) {
  37531. s += 2 * r;
  37532. }
  37533. for (j = 0; j <= tessellation; j++) {
  37534. angle = j * angle_step;
  37535. // position
  37536. ringVertex.x = Math.cos(-angle) * radius;
  37537. ringVertex.y = -height / 2 + h * height;
  37538. ringVertex.z = Math.sin(-angle) * radius;
  37539. // normal
  37540. if (diameterTop === 0 && i === subdivisions) {
  37541. // if no top cap, reuse former normals
  37542. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37543. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37544. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37545. }
  37546. else {
  37547. ringNormal.x = ringVertex.x;
  37548. ringNormal.z = ringVertex.z;
  37549. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37550. ringNormal.normalize();
  37551. }
  37552. // keep first ring vertex values for enclose
  37553. if (j === 0) {
  37554. ringFirstVertex.copyFrom(ringVertex);
  37555. ringFirstNormal.copyFrom(ringNormal);
  37556. }
  37557. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37558. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37559. if (hasRings) {
  37560. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37561. }
  37562. else {
  37563. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37564. }
  37565. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37566. if (faceColors) {
  37567. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37568. }
  37569. }
  37570. // if enclose, add four vertices and their dedicated normals
  37571. if (arc !== 1 && enclose) {
  37572. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37573. positions.push(0, ringVertex.y, 0);
  37574. positions.push(0, ringVertex.y, 0);
  37575. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37576. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37577. quadNormal.normalize();
  37578. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37579. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37580. quadNormal.normalize();
  37581. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37582. if (hasRings) {
  37583. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37584. }
  37585. else {
  37586. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37587. }
  37588. uvs.push(faceUV[s + 1].x, v);
  37589. uvs.push(faceUV[s + 1].z, v);
  37590. if (hasRings) {
  37591. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37592. }
  37593. else {
  37594. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37595. }
  37596. uvs.push(faceUV[s + 2].x, v);
  37597. uvs.push(faceUV[s + 2].z, v);
  37598. if (faceColors) {
  37599. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37600. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37601. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37602. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37603. }
  37604. }
  37605. if (cs !== s) {
  37606. cs = s;
  37607. }
  37608. }
  37609. }
  37610. // indices
  37611. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37612. var s;
  37613. i = 0;
  37614. for (s = 0; s < subdivisions; s++) {
  37615. var i0 = 0;
  37616. var i1 = 0;
  37617. var i2 = 0;
  37618. var i3 = 0;
  37619. for (j = 0; j < tessellation; j++) {
  37620. i0 = i * (e + 1) + j;
  37621. i1 = (i + 1) * (e + 1) + j;
  37622. i2 = i * (e + 1) + (j + 1);
  37623. i3 = (i + 1) * (e + 1) + (j + 1);
  37624. indices.push(i0, i1, i2);
  37625. indices.push(i3, i2, i1);
  37626. }
  37627. if (arc !== 1 && enclose) { // if enclose, add two quads
  37628. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37629. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37630. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37631. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37632. }
  37633. i = (hasRings) ? (i + 2) : (i + 1);
  37634. }
  37635. // Caps
  37636. var createCylinderCap = function (isTop) {
  37637. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37638. if (radius === 0) {
  37639. return;
  37640. }
  37641. // Cap positions, normals & uvs
  37642. var angle;
  37643. var circleVector;
  37644. var i;
  37645. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37646. var c = null;
  37647. if (faceColors) {
  37648. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37649. }
  37650. // cap center
  37651. var vbase = positions.length / 3;
  37652. var offset = isTop ? height / 2 : -height / 2;
  37653. var center = new BABYLON.Vector3(0, offset, 0);
  37654. positions.push(center.x, center.y, center.z);
  37655. normals.push(0, isTop ? 1 : -1, 0);
  37656. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37657. if (c) {
  37658. colors.push(c.r, c.g, c.b, c.a);
  37659. }
  37660. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37661. for (i = 0; i <= tessellation; i++) {
  37662. angle = Math.PI * 2 * i * arc / tessellation;
  37663. var cos = Math.cos(-angle);
  37664. var sin = Math.sin(-angle);
  37665. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37666. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37667. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37668. normals.push(0, isTop ? 1 : -1, 0);
  37669. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37670. if (c) {
  37671. colors.push(c.r, c.g, c.b, c.a);
  37672. }
  37673. }
  37674. // Cap indices
  37675. for (i = 0; i < tessellation; i++) {
  37676. if (!isTop) {
  37677. indices.push(vbase);
  37678. indices.push(vbase + (i + 1));
  37679. indices.push(vbase + (i + 2));
  37680. }
  37681. else {
  37682. indices.push(vbase);
  37683. indices.push(vbase + (i + 2));
  37684. indices.push(vbase + (i + 1));
  37685. }
  37686. }
  37687. };
  37688. // add caps to geometry
  37689. createCylinderCap(false);
  37690. createCylinderCap(true);
  37691. // Sides
  37692. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37693. var vertexData = new VertexData();
  37694. vertexData.indices = indices;
  37695. vertexData.positions = positions;
  37696. vertexData.normals = normals;
  37697. vertexData.uvs = uvs;
  37698. if (faceColors) {
  37699. vertexData.colors = colors;
  37700. }
  37701. return vertexData;
  37702. };
  37703. /**
  37704. * Creates the VertexData for a torus
  37705. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37706. * * diameter the diameter of the torus, optional default 1
  37707. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37708. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37709. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37710. * * 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)
  37711. * * 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)
  37712. * @returns the VertexData of the torus
  37713. */
  37714. VertexData.CreateTorus = function (options) {
  37715. var indices = [];
  37716. var positions = [];
  37717. var normals = [];
  37718. var uvs = [];
  37719. var diameter = options.diameter || 1;
  37720. var thickness = options.thickness || 0.5;
  37721. var tessellation = options.tessellation || 16;
  37722. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37723. var stride = tessellation + 1;
  37724. for (var i = 0; i <= tessellation; i++) {
  37725. var u = i / tessellation;
  37726. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37727. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37728. for (var j = 0; j <= tessellation; j++) {
  37729. var v = 1 - j / tessellation;
  37730. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37731. var dx = Math.cos(innerAngle);
  37732. var dy = Math.sin(innerAngle);
  37733. // Create a vertex.
  37734. var normal = new BABYLON.Vector3(dx, dy, 0);
  37735. var position = normal.scale(thickness / 2);
  37736. var textureCoordinate = new BABYLON.Vector2(u, v);
  37737. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37738. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37739. positions.push(position.x, position.y, position.z);
  37740. normals.push(normal.x, normal.y, normal.z);
  37741. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37742. // And create indices for two triangles.
  37743. var nextI = (i + 1) % stride;
  37744. var nextJ = (j + 1) % stride;
  37745. indices.push(i * stride + j);
  37746. indices.push(i * stride + nextJ);
  37747. indices.push(nextI * stride + j);
  37748. indices.push(i * stride + nextJ);
  37749. indices.push(nextI * stride + nextJ);
  37750. indices.push(nextI * stride + j);
  37751. }
  37752. }
  37753. // Sides
  37754. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37755. // Result
  37756. var vertexData = new VertexData();
  37757. vertexData.indices = indices;
  37758. vertexData.positions = positions;
  37759. vertexData.normals = normals;
  37760. vertexData.uvs = uvs;
  37761. return vertexData;
  37762. };
  37763. /**
  37764. * Creates the VertexData of the LineSystem
  37765. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37766. * - lines an array of lines, each line being an array of successive Vector3
  37767. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37768. * @returns the VertexData of the LineSystem
  37769. */
  37770. VertexData.CreateLineSystem = function (options) {
  37771. var indices = [];
  37772. var positions = [];
  37773. var lines = options.lines;
  37774. var colors = options.colors;
  37775. var vertexColors = [];
  37776. var idx = 0;
  37777. for (var l = 0; l < lines.length; l++) {
  37778. var points = lines[l];
  37779. for (var index = 0; index < points.length; index++) {
  37780. positions.push(points[index].x, points[index].y, points[index].z);
  37781. if (colors) {
  37782. var color = colors[l];
  37783. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37784. }
  37785. if (index > 0) {
  37786. indices.push(idx - 1);
  37787. indices.push(idx);
  37788. }
  37789. idx++;
  37790. }
  37791. }
  37792. var vertexData = new VertexData();
  37793. vertexData.indices = indices;
  37794. vertexData.positions = positions;
  37795. if (colors) {
  37796. vertexData.colors = vertexColors;
  37797. }
  37798. return vertexData;
  37799. };
  37800. /**
  37801. * Create the VertexData for a DashedLines
  37802. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37803. * - points an array successive Vector3
  37804. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37805. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37806. * - dashNb the intended total number of dashes, optional, default 200
  37807. * @returns the VertexData for the DashedLines
  37808. */
  37809. VertexData.CreateDashedLines = function (options) {
  37810. var dashSize = options.dashSize || 3;
  37811. var gapSize = options.gapSize || 1;
  37812. var dashNb = options.dashNb || 200;
  37813. var points = options.points;
  37814. var positions = new Array();
  37815. var indices = new Array();
  37816. var curvect = BABYLON.Vector3.Zero();
  37817. var lg = 0;
  37818. var nb = 0;
  37819. var shft = 0;
  37820. var dashshft = 0;
  37821. var curshft = 0;
  37822. var idx = 0;
  37823. var i = 0;
  37824. for (i = 0; i < points.length - 1; i++) {
  37825. points[i + 1].subtractToRef(points[i], curvect);
  37826. lg += curvect.length();
  37827. }
  37828. shft = lg / dashNb;
  37829. dashshft = dashSize * shft / (dashSize + gapSize);
  37830. for (i = 0; i < points.length - 1; i++) {
  37831. points[i + 1].subtractToRef(points[i], curvect);
  37832. nb = Math.floor(curvect.length() / shft);
  37833. curvect.normalize();
  37834. for (var j = 0; j < nb; j++) {
  37835. curshft = shft * j;
  37836. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37837. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37838. indices.push(idx, idx + 1);
  37839. idx += 2;
  37840. }
  37841. }
  37842. // Result
  37843. var vertexData = new VertexData();
  37844. vertexData.positions = positions;
  37845. vertexData.indices = indices;
  37846. return vertexData;
  37847. };
  37848. /**
  37849. * Creates the VertexData for a Ground
  37850. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37851. * - width the width (x direction) of the ground, optional, default 1
  37852. * - height the height (z direction) of the ground, optional, default 1
  37853. * - subdivisions the number of subdivisions per side, optional, default 1
  37854. * @returns the VertexData of the Ground
  37855. */
  37856. VertexData.CreateGround = function (options) {
  37857. var indices = [];
  37858. var positions = [];
  37859. var normals = [];
  37860. var uvs = [];
  37861. var row, col;
  37862. var width = options.width || 1;
  37863. var height = options.height || 1;
  37864. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37865. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37866. for (row = 0; row <= subdivisionsY; row++) {
  37867. for (col = 0; col <= subdivisionsX; col++) {
  37868. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37869. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37870. positions.push(position.x, position.y, position.z);
  37871. normals.push(normal.x, normal.y, normal.z);
  37872. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37873. }
  37874. }
  37875. for (row = 0; row < subdivisionsY; row++) {
  37876. for (col = 0; col < subdivisionsX; col++) {
  37877. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37878. indices.push(col + 1 + row * (subdivisionsX + 1));
  37879. indices.push(col + row * (subdivisionsX + 1));
  37880. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37881. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37882. indices.push(col + row * (subdivisionsX + 1));
  37883. }
  37884. }
  37885. // Result
  37886. var vertexData = new VertexData();
  37887. vertexData.indices = indices;
  37888. vertexData.positions = positions;
  37889. vertexData.normals = normals;
  37890. vertexData.uvs = uvs;
  37891. return vertexData;
  37892. };
  37893. /**
  37894. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37895. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37896. * * xmin the ground minimum X coordinate, optional, default -1
  37897. * * zmin the ground minimum Z coordinate, optional, default -1
  37898. * * xmax the ground maximum X coordinate, optional, default 1
  37899. * * zmax the ground maximum Z coordinate, optional, default 1
  37900. * * 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}
  37901. * * 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}
  37902. * @returns the VertexData of the TiledGround
  37903. */
  37904. VertexData.CreateTiledGround = function (options) {
  37905. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37906. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37907. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37908. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37909. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37910. var precision = options.precision || { w: 1, h: 1 };
  37911. var indices = new Array();
  37912. var positions = new Array();
  37913. var normals = new Array();
  37914. var uvs = new Array();
  37915. var row, col, tileRow, tileCol;
  37916. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37917. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37918. precision.w = (precision.w < 1) ? 1 : precision.w;
  37919. precision.h = (precision.h < 1) ? 1 : precision.h;
  37920. var tileSize = {
  37921. 'w': (xmax - xmin) / subdivisions.w,
  37922. 'h': (zmax - zmin) / subdivisions.h
  37923. };
  37924. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37925. // Indices
  37926. var base = positions.length / 3;
  37927. var rowLength = precision.w + 1;
  37928. for (row = 0; row < precision.h; row++) {
  37929. for (col = 0; col < precision.w; col++) {
  37930. var square = [
  37931. base + col + row * rowLength,
  37932. base + (col + 1) + row * rowLength,
  37933. base + (col + 1) + (row + 1) * rowLength,
  37934. base + col + (row + 1) * rowLength
  37935. ];
  37936. indices.push(square[1]);
  37937. indices.push(square[2]);
  37938. indices.push(square[3]);
  37939. indices.push(square[0]);
  37940. indices.push(square[1]);
  37941. indices.push(square[3]);
  37942. }
  37943. }
  37944. // Position, normals and uvs
  37945. var position = BABYLON.Vector3.Zero();
  37946. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37947. for (row = 0; row <= precision.h; row++) {
  37948. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37949. for (col = 0; col <= precision.w; col++) {
  37950. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37951. position.y = 0;
  37952. positions.push(position.x, position.y, position.z);
  37953. normals.push(normal.x, normal.y, normal.z);
  37954. uvs.push(col / precision.w, row / precision.h);
  37955. }
  37956. }
  37957. }
  37958. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37959. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37960. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37961. }
  37962. }
  37963. // Result
  37964. var vertexData = new VertexData();
  37965. vertexData.indices = indices;
  37966. vertexData.positions = positions;
  37967. vertexData.normals = normals;
  37968. vertexData.uvs = uvs;
  37969. return vertexData;
  37970. };
  37971. /**
  37972. * Creates the VertexData of the Ground designed from a heightmap
  37973. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37974. * * width the width (x direction) of the ground
  37975. * * height the height (z direction) of the ground
  37976. * * subdivisions the number of subdivisions per side
  37977. * * minHeight the minimum altitude on the ground, optional, default 0
  37978. * * maxHeight the maximum altitude on the ground, optional default 1
  37979. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37980. * * buffer the array holding the image color data
  37981. * * bufferWidth the width of image
  37982. * * bufferHeight the height of image
  37983. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37984. * @returns the VertexData of the Ground designed from a heightmap
  37985. */
  37986. VertexData.CreateGroundFromHeightMap = function (options) {
  37987. var indices = [];
  37988. var positions = [];
  37989. var normals = [];
  37990. var uvs = [];
  37991. var row, col;
  37992. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37993. var alphaFilter = options.alphaFilter || 0.0;
  37994. // Vertices
  37995. for (row = 0; row <= options.subdivisions; row++) {
  37996. for (col = 0; col <= options.subdivisions; col++) {
  37997. 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));
  37998. // Compute height
  37999. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38000. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38001. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38002. var r = options.buffer[pos] / 255.0;
  38003. var g = options.buffer[pos + 1] / 255.0;
  38004. var b = options.buffer[pos + 2] / 255.0;
  38005. var a = options.buffer[pos + 3] / 255.0;
  38006. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38007. // If our alpha channel is not within our filter then we will assign a 'special' height
  38008. // Then when building the indices, we will ignore any vertex that is using the special height
  38009. if (a >= alphaFilter)
  38010. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38011. else {
  38012. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  38013. }
  38014. // Add vertex
  38015. positions.push(position.x, position.y, position.z);
  38016. normals.push(0, 0, 0);
  38017. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38018. }
  38019. }
  38020. // Indices
  38021. for (row = 0; row < options.subdivisions; row++) {
  38022. for (col = 0; col < options.subdivisions; col++) {
  38023. // Calculate Indices
  38024. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  38025. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  38026. var idx3 = (col + row * (options.subdivisions + 1));
  38027. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  38028. // Check that all indices are visible (based on our special height)
  38029. // Only display the vertex if all Indices are visible
  38030. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  38031. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  38032. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  38033. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  38034. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  38035. indices.push(idx1);
  38036. indices.push(idx2);
  38037. indices.push(idx3);
  38038. }
  38039. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  38040. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  38041. indices.push(idx4);
  38042. indices.push(idx1);
  38043. indices.push(idx3);
  38044. }
  38045. }
  38046. }
  38047. // Normals
  38048. VertexData.ComputeNormals(positions, indices, normals);
  38049. // Result
  38050. var vertexData = new VertexData();
  38051. vertexData.indices = indices;
  38052. vertexData.positions = positions;
  38053. vertexData.normals = normals;
  38054. vertexData.uvs = uvs;
  38055. return vertexData;
  38056. };
  38057. /**
  38058. * Creates the VertexData for a Plane
  38059. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38060. * * size sets the width and height of the plane to the value of size, optional default 1
  38061. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38062. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38063. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38064. * * 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)
  38065. * * 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)
  38066. * @returns the VertexData of the box
  38067. */
  38068. VertexData.CreatePlane = function (options) {
  38069. var indices = [];
  38070. var positions = [];
  38071. var normals = [];
  38072. var uvs = [];
  38073. var width = options.width || options.size || 1;
  38074. var height = options.height || options.size || 1;
  38075. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38076. // Vertices
  38077. var halfWidth = width / 2.0;
  38078. var halfHeight = height / 2.0;
  38079. positions.push(-halfWidth, -halfHeight, 0);
  38080. normals.push(0, 0, -1.0);
  38081. uvs.push(0.0, 0.0);
  38082. positions.push(halfWidth, -halfHeight, 0);
  38083. normals.push(0, 0, -1.0);
  38084. uvs.push(1.0, 0.0);
  38085. positions.push(halfWidth, halfHeight, 0);
  38086. normals.push(0, 0, -1.0);
  38087. uvs.push(1.0, 1.0);
  38088. positions.push(-halfWidth, halfHeight, 0);
  38089. normals.push(0, 0, -1.0);
  38090. uvs.push(0.0, 1.0);
  38091. // Indices
  38092. indices.push(0);
  38093. indices.push(1);
  38094. indices.push(2);
  38095. indices.push(0);
  38096. indices.push(2);
  38097. indices.push(3);
  38098. // Sides
  38099. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38100. // Result
  38101. var vertexData = new VertexData();
  38102. vertexData.indices = indices;
  38103. vertexData.positions = positions;
  38104. vertexData.normals = normals;
  38105. vertexData.uvs = uvs;
  38106. return vertexData;
  38107. };
  38108. /**
  38109. * Creates the VertexData of the Disc or regular Polygon
  38110. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38111. * * radius the radius of the disc, optional default 0.5
  38112. * * tessellation the number of polygon sides, optional, default 64
  38113. * * 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
  38114. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38115. * * 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)
  38116. * * 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)
  38117. * @returns the VertexData of the box
  38118. */
  38119. VertexData.CreateDisc = function (options) {
  38120. var positions = new Array();
  38121. var indices = new Array();
  38122. var normals = new Array();
  38123. var uvs = new Array();
  38124. var radius = options.radius || 0.5;
  38125. var tessellation = options.tessellation || 64;
  38126. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38127. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38128. // positions and uvs
  38129. positions.push(0, 0, 0); // disc center first
  38130. uvs.push(0.5, 0.5);
  38131. var theta = Math.PI * 2 * arc;
  38132. var step = theta / tessellation;
  38133. for (var a = 0; a < theta; a += step) {
  38134. var x = Math.cos(a);
  38135. var y = Math.sin(a);
  38136. var u = (x + 1) / 2;
  38137. var v = (1 - y) / 2;
  38138. positions.push(radius * x, radius * y, 0);
  38139. uvs.push(u, v);
  38140. }
  38141. if (arc === 1) {
  38142. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38143. uvs.push(uvs[2], uvs[3]);
  38144. }
  38145. //indices
  38146. var vertexNb = positions.length / 3;
  38147. for (var i = 1; i < vertexNb - 1; i++) {
  38148. indices.push(i + 1, 0, i);
  38149. }
  38150. // result
  38151. VertexData.ComputeNormals(positions, indices, normals);
  38152. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38153. var vertexData = new VertexData();
  38154. vertexData.indices = indices;
  38155. vertexData.positions = positions;
  38156. vertexData.normals = normals;
  38157. vertexData.uvs = uvs;
  38158. return vertexData;
  38159. };
  38160. /**
  38161. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38162. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38163. * @param polygon a mesh built from polygonTriangulation.build()
  38164. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38165. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38166. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38167. * @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)
  38168. * @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)
  38169. * @returns the VertexData of the Polygon
  38170. */
  38171. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38172. var faceUV = fUV || new Array(3);
  38173. var faceColors = fColors;
  38174. var colors = [];
  38175. // default face colors and UV if undefined
  38176. for (var f = 0; f < 3; f++) {
  38177. if (faceUV[f] === undefined) {
  38178. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38179. }
  38180. if (faceColors && faceColors[f] === undefined) {
  38181. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38182. }
  38183. }
  38184. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38185. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38186. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38187. var indices = polygon.getIndices();
  38188. // set face colours and textures
  38189. var idx = 0;
  38190. var face = 0;
  38191. for (var index = 0; index < normals.length; index += 3) {
  38192. //Edge Face no. 1
  38193. if (Math.abs(normals[index + 1]) < 0.001) {
  38194. face = 1;
  38195. }
  38196. //Top Face no. 0
  38197. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38198. face = 0;
  38199. }
  38200. //Bottom Face no. 2
  38201. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38202. face = 2;
  38203. }
  38204. idx = index / 3;
  38205. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38206. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38207. if (faceColors) {
  38208. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38209. }
  38210. }
  38211. // sides
  38212. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38213. // Result
  38214. var vertexData = new VertexData();
  38215. vertexData.indices = indices;
  38216. vertexData.positions = positions;
  38217. vertexData.normals = normals;
  38218. vertexData.uvs = uvs;
  38219. if (faceColors) {
  38220. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38221. vertexData.colors = totalColors;
  38222. }
  38223. return vertexData;
  38224. };
  38225. /**
  38226. * Creates the VertexData of the IcoSphere
  38227. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38228. * * radius the radius of the IcoSphere, optional default 1
  38229. * * radiusX allows stretching in the x direction, optional, default radius
  38230. * * radiusY allows stretching in the y direction, optional, default radius
  38231. * * radiusZ allows stretching in the z direction, optional, default radius
  38232. * * flat when true creates a flat shaded mesh, optional, default true
  38233. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38234. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38235. * * 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)
  38236. * * 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)
  38237. * @returns the VertexData of the IcoSphere
  38238. */
  38239. VertexData.CreateIcoSphere = function (options) {
  38240. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38241. var radius = options.radius || 1;
  38242. var flat = (options.flat === undefined) ? true : options.flat;
  38243. var subdivisions = options.subdivisions || 4;
  38244. var radiusX = options.radiusX || radius;
  38245. var radiusY = options.radiusY || radius;
  38246. var radiusZ = options.radiusZ || radius;
  38247. var t = (1 + Math.sqrt(5)) / 2;
  38248. // 12 vertex x,y,z
  38249. var ico_vertices = [
  38250. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38251. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38252. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38253. ];
  38254. // index of 3 vertex makes a face of icopshere
  38255. var ico_indices = [
  38256. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38257. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38258. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38259. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38260. ];
  38261. // vertex for uv have aliased position, not for UV
  38262. var vertices_unalias_id = [
  38263. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38264. // vertex alias
  38265. 0,
  38266. 2,
  38267. 3,
  38268. 3,
  38269. 3,
  38270. 4,
  38271. 7,
  38272. 8,
  38273. 9,
  38274. 9,
  38275. 10,
  38276. 11 // 23: B + 12
  38277. ];
  38278. // uv as integer step (not pixels !)
  38279. var ico_vertexuv = [
  38280. 5, 1, 3, 1, 6, 4, 0, 0,
  38281. 5, 3, 4, 2, 2, 2, 4, 0,
  38282. 2, 0, 1, 1, 6, 0, 6, 2,
  38283. // vertex alias (for same vertex on different faces)
  38284. 0, 4,
  38285. 3, 3,
  38286. 4, 4,
  38287. 3, 1,
  38288. 4, 2,
  38289. 4, 4,
  38290. 0, 2,
  38291. 1, 1,
  38292. 2, 2,
  38293. 3, 3,
  38294. 1, 3,
  38295. 2, 4 // 23: B + 12
  38296. ];
  38297. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38298. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38299. // First island of uv mapping
  38300. // v = 4h 3+ 2
  38301. // v = 3h 9+ 4
  38302. // v = 2h 9+ 5 B
  38303. // v = 1h 9 1 0
  38304. // v = 0h 3 8 7 A
  38305. // u = 0 1 2 3 4 5 6 *a
  38306. // Second island of uv mapping
  38307. // v = 4h 0+ B+ 4+
  38308. // v = 3h A+ 2+
  38309. // v = 2h 7+ 6 3+
  38310. // v = 1h 8+ 3+
  38311. // v = 0h
  38312. // u = 0 1 2 3 4 5 6 *a
  38313. // Face layout on texture UV mapping
  38314. // ============
  38315. // \ 4 /\ 16 / ======
  38316. // \ / \ / /\ 11 /
  38317. // \/ 7 \/ / \ /
  38318. // ======= / 10 \/
  38319. // /\ 17 /\ =======
  38320. // / \ / \ \ 15 /\
  38321. // / 8 \/ 12 \ \ / \
  38322. // ============ \/ 6 \
  38323. // \ 18 /\ ============
  38324. // \ / \ \ 5 /\ 0 /
  38325. // \/ 13 \ \ / \ /
  38326. // ======= \/ 1 \/
  38327. // =============
  38328. // /\ 19 /\ 2 /\
  38329. // / \ / \ / \
  38330. // / 14 \/ 9 \/ 3 \
  38331. // ===================
  38332. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38333. var ustep = 138 / 1024;
  38334. var vstep = 239 / 1024;
  38335. var uoffset = 60 / 1024;
  38336. var voffset = 26 / 1024;
  38337. // Second island should have margin, not to touch the first island
  38338. // avoid any borderline artefact in pixel rounding
  38339. var island_u_offset = -40 / 1024;
  38340. var island_v_offset = +20 / 1024;
  38341. // face is either island 0 or 1 :
  38342. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38343. var island = [
  38344. 0, 0, 0, 0, 1,
  38345. 0, 0, 1, 1, 0,
  38346. 0, 0, 1, 1, 0,
  38347. 0, 1, 1, 1, 0 // 15 - 19
  38348. ];
  38349. var indices = new Array();
  38350. var positions = new Array();
  38351. var normals = new Array();
  38352. var uvs = new Array();
  38353. var current_indice = 0;
  38354. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38355. var face_vertex_pos = new Array(3);
  38356. var face_vertex_uv = new Array(3);
  38357. var v012;
  38358. for (v012 = 0; v012 < 3; v012++) {
  38359. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38360. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38361. }
  38362. // create all with normals
  38363. for (var face = 0; face < 20; face++) {
  38364. // 3 vertex per face
  38365. for (v012 = 0; v012 < 3; v012++) {
  38366. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38367. var v_id = ico_indices[3 * face + v012];
  38368. // vertex have 3D position (x,y,z)
  38369. 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]);
  38370. // Normalize to get normal, then scale to radius
  38371. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38372. // uv Coordinates from vertex ID
  38373. 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);
  38374. }
  38375. // Subdivide the face (interpolate pos, norm, uv)
  38376. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38377. // - norm is linear interpolation of vertex corner normal
  38378. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38379. // - uv is linear interpolation
  38380. //
  38381. // Topology is as below for sub-divide by 2
  38382. // vertex shown as v0,v1,v2
  38383. // interp index is i1 to progress in range [v0,v1[
  38384. // interp index is i2 to progress in range [v0,v2[
  38385. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38386. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38387. //
  38388. //
  38389. // i2 v2
  38390. // ^ ^
  38391. // / / \
  38392. // / / \
  38393. // / / \
  38394. // / / (0,1) \
  38395. // / #---------\
  38396. // / / \ (0,0)'/ \
  38397. // / / \ / \
  38398. // / / \ / \
  38399. // / / (0,0) \ / (1,0) \
  38400. // / #---------#---------\
  38401. // v0 v1
  38402. //
  38403. // --------------------> i1
  38404. //
  38405. // interp of (i1,i2):
  38406. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38407. // along i1 : lerp(x0,x1, i1/(S-i2))
  38408. //
  38409. // centroid of triangle is needed to get help normal computation
  38410. // (c1,c2) are used for centroid location
  38411. var interp_vertex = function (i1, i2, c1, c2) {
  38412. // vertex is interpolated from
  38413. // - face_vertex_pos[0..2]
  38414. // - face_vertex_uv[0..2]
  38415. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38416. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38417. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38418. pos_interp.normalize();
  38419. var vertex_normal;
  38420. if (flat) {
  38421. // in flat mode, recalculate normal as face centroid normal
  38422. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38423. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38424. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38425. }
  38426. else {
  38427. // in smooth mode, recalculate normal from each single vertex position
  38428. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38429. }
  38430. // Vertex normal need correction due to X,Y,Z radius scaling
  38431. vertex_normal.x /= radiusX;
  38432. vertex_normal.y /= radiusY;
  38433. vertex_normal.z /= radiusZ;
  38434. vertex_normal.normalize();
  38435. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38436. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38437. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38438. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38439. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38440. uvs.push(uv_interp.x, uv_interp.y);
  38441. // push each vertex has member of a face
  38442. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38443. indices.push(current_indice);
  38444. current_indice++;
  38445. };
  38446. for (var i2 = 0; i2 < subdivisions; i2++) {
  38447. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38448. // face : (i1,i2) for /\ :
  38449. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38450. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38451. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38452. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38453. if (i1 + i2 + 1 < subdivisions) {
  38454. // face : (i1,i2)' for \/ :
  38455. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38456. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38457. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38458. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38459. }
  38460. }
  38461. }
  38462. }
  38463. // Sides
  38464. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38465. // Result
  38466. var vertexData = new VertexData();
  38467. vertexData.indices = indices;
  38468. vertexData.positions = positions;
  38469. vertexData.normals = normals;
  38470. vertexData.uvs = uvs;
  38471. return vertexData;
  38472. };
  38473. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38474. /**
  38475. * Creates the VertexData for a Polyhedron
  38476. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38477. * * type provided types are:
  38478. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38479. * * 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)
  38480. * * size the size of the IcoSphere, optional default 1
  38481. * * sizeX allows stretching in the x direction, optional, default size
  38482. * * sizeY allows stretching in the y direction, optional, default size
  38483. * * sizeZ allows stretching in the z direction, optional, default size
  38484. * * 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
  38485. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38486. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38487. * * flat when true creates a flat shaded mesh, optional, default true
  38488. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38489. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38490. * * 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)
  38491. * * 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)
  38492. * @returns the VertexData of the Polyhedron
  38493. */
  38494. VertexData.CreatePolyhedron = function (options) {
  38495. // provided polyhedron types :
  38496. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38497. // 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)
  38498. var polyhedra = [];
  38499. 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]] };
  38500. 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]] };
  38501. polyhedra[2] = {
  38502. 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]],
  38503. 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]]
  38504. };
  38505. polyhedra[3] = {
  38506. 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]],
  38507. 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]]
  38508. };
  38509. polyhedra[4] = {
  38510. 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]],
  38511. 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]]
  38512. };
  38513. 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]] };
  38514. 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]] };
  38515. 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]] };
  38516. 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]] };
  38517. 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]] };
  38518. 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]] };
  38519. 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]] };
  38520. 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]] };
  38521. 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]] };
  38522. polyhedra[14] = {
  38523. 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]],
  38524. 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]]
  38525. };
  38526. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38527. var size = options.size;
  38528. var sizeX = options.sizeX || size || 1;
  38529. var sizeY = options.sizeY || size || 1;
  38530. var sizeZ = options.sizeZ || size || 1;
  38531. var data = options.custom || polyhedra[type];
  38532. var nbfaces = data.face.length;
  38533. var faceUV = options.faceUV || new Array(nbfaces);
  38534. var faceColors = options.faceColors;
  38535. var flat = (options.flat === undefined) ? true : options.flat;
  38536. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38537. var positions = new Array();
  38538. var indices = new Array();
  38539. var normals = new Array();
  38540. var uvs = new Array();
  38541. var colors = new Array();
  38542. var index = 0;
  38543. var faceIdx = 0; // face cursor in the array "indexes"
  38544. var indexes = new Array();
  38545. var i = 0;
  38546. var f = 0;
  38547. var u, v, ang, x, y, tmp;
  38548. // default face colors and UV if undefined
  38549. if (flat) {
  38550. for (f = 0; f < nbfaces; f++) {
  38551. if (faceColors && faceColors[f] === undefined) {
  38552. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38553. }
  38554. if (faceUV && faceUV[f] === undefined) {
  38555. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38556. }
  38557. }
  38558. }
  38559. if (!flat) {
  38560. for (i = 0; i < data.vertex.length; i++) {
  38561. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38562. uvs.push(0, 0);
  38563. }
  38564. for (f = 0; f < nbfaces; f++) {
  38565. for (i = 0; i < data.face[f].length - 2; i++) {
  38566. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38567. }
  38568. }
  38569. }
  38570. else {
  38571. for (f = 0; f < nbfaces; f++) {
  38572. var fl = data.face[f].length; // number of vertices of the current face
  38573. ang = 2 * Math.PI / fl;
  38574. x = 0.5 * Math.tan(ang / 2);
  38575. y = 0.5;
  38576. // positions, uvs, colors
  38577. for (i = 0; i < fl; i++) {
  38578. // positions
  38579. 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);
  38580. indexes.push(index);
  38581. index++;
  38582. // uvs
  38583. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38584. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38585. uvs.push(u, v);
  38586. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38587. y = x * Math.sin(ang) + y * Math.cos(ang);
  38588. x = tmp;
  38589. // colors
  38590. if (faceColors) {
  38591. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38592. }
  38593. }
  38594. // indices from indexes
  38595. for (i = 0; i < fl - 2; i++) {
  38596. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38597. }
  38598. faceIdx += fl;
  38599. }
  38600. }
  38601. VertexData.ComputeNormals(positions, indices, normals);
  38602. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38603. var vertexData = new VertexData();
  38604. vertexData.positions = positions;
  38605. vertexData.indices = indices;
  38606. vertexData.normals = normals;
  38607. vertexData.uvs = uvs;
  38608. if (faceColors && flat) {
  38609. vertexData.colors = colors;
  38610. }
  38611. return vertexData;
  38612. };
  38613. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38614. /**
  38615. * Creates the VertexData for a TorusKnot
  38616. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38617. * * radius the radius of the torus knot, optional, default 2
  38618. * * tube the thickness of the tube, optional, default 0.5
  38619. * * radialSegments the number of sides on each tube segments, optional, default 32
  38620. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38621. * * p the number of windings around the z axis, optional, default 2
  38622. * * q the number of windings around the x axis, optional, default 3
  38623. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38624. * * 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)
  38625. * * 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)
  38626. * @returns the VertexData of the Torus Knot
  38627. */
  38628. VertexData.CreateTorusKnot = function (options) {
  38629. var indices = new Array();
  38630. var positions = new Array();
  38631. var normals = new Array();
  38632. var uvs = new Array();
  38633. var radius = options.radius || 2;
  38634. var tube = options.tube || 0.5;
  38635. var radialSegments = options.radialSegments || 32;
  38636. var tubularSegments = options.tubularSegments || 32;
  38637. var p = options.p || 2;
  38638. var q = options.q || 3;
  38639. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38640. // Helper
  38641. var getPos = function (angle) {
  38642. var cu = Math.cos(angle);
  38643. var su = Math.sin(angle);
  38644. var quOverP = q / p * angle;
  38645. var cs = Math.cos(quOverP);
  38646. var tx = radius * (2 + cs) * 0.5 * cu;
  38647. var ty = radius * (2 + cs) * su * 0.5;
  38648. var tz = radius * Math.sin(quOverP) * 0.5;
  38649. return new BABYLON.Vector3(tx, ty, tz);
  38650. };
  38651. // Vertices
  38652. var i;
  38653. var j;
  38654. for (i = 0; i <= radialSegments; i++) {
  38655. var modI = i % radialSegments;
  38656. var u = modI / radialSegments * 2 * p * Math.PI;
  38657. var p1 = getPos(u);
  38658. var p2 = getPos(u + 0.01);
  38659. var tang = p2.subtract(p1);
  38660. var n = p2.add(p1);
  38661. var bitan = BABYLON.Vector3.Cross(tang, n);
  38662. n = BABYLON.Vector3.Cross(bitan, tang);
  38663. bitan.normalize();
  38664. n.normalize();
  38665. for (j = 0; j < tubularSegments; j++) {
  38666. var modJ = j % tubularSegments;
  38667. var v = modJ / tubularSegments * 2 * Math.PI;
  38668. var cx = -tube * Math.cos(v);
  38669. var cy = tube * Math.sin(v);
  38670. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38671. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38672. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38673. uvs.push(i / radialSegments);
  38674. uvs.push(j / tubularSegments);
  38675. }
  38676. }
  38677. for (i = 0; i < radialSegments; i++) {
  38678. for (j = 0; j < tubularSegments; j++) {
  38679. var jNext = (j + 1) % tubularSegments;
  38680. var a = i * tubularSegments + j;
  38681. var b = (i + 1) * tubularSegments + j;
  38682. var c = (i + 1) * tubularSegments + jNext;
  38683. var d = i * tubularSegments + jNext;
  38684. indices.push(d);
  38685. indices.push(b);
  38686. indices.push(a);
  38687. indices.push(d);
  38688. indices.push(c);
  38689. indices.push(b);
  38690. }
  38691. }
  38692. // Normals
  38693. VertexData.ComputeNormals(positions, indices, normals);
  38694. // Sides
  38695. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38696. // Result
  38697. var vertexData = new VertexData();
  38698. vertexData.indices = indices;
  38699. vertexData.positions = positions;
  38700. vertexData.normals = normals;
  38701. vertexData.uvs = uvs;
  38702. return vertexData;
  38703. };
  38704. // Tools
  38705. /**
  38706. * Compute normals for given positions and indices
  38707. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38708. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38709. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38710. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38711. * * facetNormals : optional array of facet normals (vector3)
  38712. * * facetPositions : optional array of facet positions (vector3)
  38713. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38714. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38715. * * bInfo : optional bounding info, required for facetPartitioning computation
  38716. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38717. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38718. * * useRightHandedSystem: optional boolean to for right handed system computation
  38719. * * depthSort : optional boolean to enable the facet depth sort computation
  38720. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38721. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38722. */
  38723. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38724. // temporary scalar variables
  38725. var index = 0; // facet index
  38726. var p1p2x = 0.0; // p1p2 vector x coordinate
  38727. var p1p2y = 0.0; // p1p2 vector y coordinate
  38728. var p1p2z = 0.0; // p1p2 vector z coordinate
  38729. var p3p2x = 0.0; // p3p2 vector x coordinate
  38730. var p3p2y = 0.0; // p3p2 vector y coordinate
  38731. var p3p2z = 0.0; // p3p2 vector z coordinate
  38732. var faceNormalx = 0.0; // facet normal x coordinate
  38733. var faceNormaly = 0.0; // facet normal y coordinate
  38734. var faceNormalz = 0.0; // facet normal z coordinate
  38735. var length = 0.0; // facet normal length before normalization
  38736. var v1x = 0; // vector1 x index in the positions array
  38737. var v1y = 0; // vector1 y index in the positions array
  38738. var v1z = 0; // vector1 z index in the positions array
  38739. var v2x = 0; // vector2 x index in the positions array
  38740. var v2y = 0; // vector2 y index in the positions array
  38741. var v2z = 0; // vector2 z index in the positions array
  38742. var v3x = 0; // vector3 x index in the positions array
  38743. var v3y = 0; // vector3 y index in the positions array
  38744. var v3z = 0; // vector3 z index in the positions array
  38745. var computeFacetNormals = false;
  38746. var computeFacetPositions = false;
  38747. var computeFacetPartitioning = false;
  38748. var computeDepthSort = false;
  38749. var faceNormalSign = 1;
  38750. var ratio = 0;
  38751. var distanceTo = null;
  38752. if (options) {
  38753. computeFacetNormals = (options.facetNormals) ? true : false;
  38754. computeFacetPositions = (options.facetPositions) ? true : false;
  38755. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38756. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38757. ratio = options.ratio || 0;
  38758. computeDepthSort = (options.depthSort) ? true : false;
  38759. distanceTo = (options.distanceTo);
  38760. if (computeDepthSort) {
  38761. if (distanceTo === undefined) {
  38762. distanceTo = BABYLON.Vector3.Zero();
  38763. }
  38764. var depthSortedFacets = options.depthSortedFacets;
  38765. }
  38766. }
  38767. // facetPartitioning reinit if needed
  38768. var xSubRatio = 0;
  38769. var ySubRatio = 0;
  38770. var zSubRatio = 0;
  38771. var subSq = 0;
  38772. if (computeFacetPartitioning && options && options.bbSize) {
  38773. var ox = 0; // X partitioning index for facet position
  38774. var oy = 0; // Y partinioning index for facet position
  38775. var oz = 0; // Z partinioning index for facet position
  38776. var b1x = 0; // X partitioning index for facet v1 vertex
  38777. var b1y = 0; // Y partitioning index for facet v1 vertex
  38778. var b1z = 0; // z partitioning index for facet v1 vertex
  38779. var b2x = 0; // X partitioning index for facet v2 vertex
  38780. var b2y = 0; // Y partitioning index for facet v2 vertex
  38781. var b2z = 0; // Z partitioning index for facet v2 vertex
  38782. var b3x = 0; // X partitioning index for facet v3 vertex
  38783. var b3y = 0; // Y partitioning index for facet v3 vertex
  38784. var b3z = 0; // Z partitioning index for facet v3 vertex
  38785. var block_idx_o = 0; // facet barycenter block index
  38786. var block_idx_v1 = 0; // v1 vertex block index
  38787. var block_idx_v2 = 0; // v2 vertex block index
  38788. var block_idx_v3 = 0; // v3 vertex block index
  38789. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38790. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38791. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38792. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38793. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38794. subSq = options.subDiv.max * options.subDiv.max;
  38795. options.facetPartitioning.length = 0;
  38796. }
  38797. // reset the normals
  38798. for (index = 0; index < positions.length; index++) {
  38799. normals[index] = 0.0;
  38800. }
  38801. // Loop : 1 indice triplet = 1 facet
  38802. var nbFaces = (indices.length / 3) | 0;
  38803. for (index = 0; index < nbFaces; index++) {
  38804. // get the indexes of the coordinates of each vertex of the facet
  38805. v1x = indices[index * 3] * 3;
  38806. v1y = v1x + 1;
  38807. v1z = v1x + 2;
  38808. v2x = indices[index * 3 + 1] * 3;
  38809. v2y = v2x + 1;
  38810. v2z = v2x + 2;
  38811. v3x = indices[index * 3 + 2] * 3;
  38812. v3y = v3x + 1;
  38813. v3z = v3x + 2;
  38814. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38815. p1p2y = positions[v1y] - positions[v2y];
  38816. p1p2z = positions[v1z] - positions[v2z];
  38817. p3p2x = positions[v3x] - positions[v2x];
  38818. p3p2y = positions[v3y] - positions[v2y];
  38819. p3p2z = positions[v3z] - positions[v2z];
  38820. // compute the face normal with the cross product
  38821. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38822. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38823. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38824. // normalize this normal and store it in the array facetData
  38825. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38826. length = (length === 0) ? 1.0 : length;
  38827. faceNormalx /= length;
  38828. faceNormaly /= length;
  38829. faceNormalz /= length;
  38830. if (computeFacetNormals && options) {
  38831. options.facetNormals[index].x = faceNormalx;
  38832. options.facetNormals[index].y = faceNormaly;
  38833. options.facetNormals[index].z = faceNormalz;
  38834. }
  38835. if (computeFacetPositions && options) {
  38836. // compute and the facet barycenter coordinates in the array facetPositions
  38837. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38838. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38839. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38840. }
  38841. if (computeFacetPartitioning && options) {
  38842. // store the facet indexes in arrays in the main facetPartitioning array :
  38843. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38844. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38845. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38846. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38847. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38848. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38849. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38850. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38851. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38852. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38853. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38854. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38855. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38856. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38857. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38858. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38859. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38860. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38861. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38862. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38863. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38864. // push each facet index in each block containing the vertex
  38865. options.facetPartitioning[block_idx_v1].push(index);
  38866. if (block_idx_v2 != block_idx_v1) {
  38867. options.facetPartitioning[block_idx_v2].push(index);
  38868. }
  38869. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38870. options.facetPartitioning[block_idx_v3].push(index);
  38871. }
  38872. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38873. options.facetPartitioning[block_idx_o].push(index);
  38874. }
  38875. }
  38876. if (computeDepthSort && options && options.facetPositions) {
  38877. var dsf = depthSortedFacets[index];
  38878. dsf.ind = index * 3;
  38879. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38880. }
  38881. // compute the normals anyway
  38882. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38883. normals[v1y] += faceNormaly;
  38884. normals[v1z] += faceNormalz;
  38885. normals[v2x] += faceNormalx;
  38886. normals[v2y] += faceNormaly;
  38887. normals[v2z] += faceNormalz;
  38888. normals[v3x] += faceNormalx;
  38889. normals[v3y] += faceNormaly;
  38890. normals[v3z] += faceNormalz;
  38891. }
  38892. // last normalization of each normal
  38893. for (index = 0; index < normals.length / 3; index++) {
  38894. faceNormalx = normals[index * 3];
  38895. faceNormaly = normals[index * 3 + 1];
  38896. faceNormalz = normals[index * 3 + 2];
  38897. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38898. length = (length === 0) ? 1.0 : length;
  38899. faceNormalx /= length;
  38900. faceNormaly /= length;
  38901. faceNormalz /= length;
  38902. normals[index * 3] = faceNormalx;
  38903. normals[index * 3 + 1] = faceNormaly;
  38904. normals[index * 3 + 2] = faceNormalz;
  38905. }
  38906. };
  38907. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38908. var li = indices.length;
  38909. var ln = normals.length;
  38910. var i;
  38911. var n;
  38912. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38913. switch (sideOrientation) {
  38914. case BABYLON.Mesh.FRONTSIDE:
  38915. // nothing changed
  38916. break;
  38917. case BABYLON.Mesh.BACKSIDE:
  38918. var tmp;
  38919. // indices
  38920. for (i = 0; i < li; i += 3) {
  38921. tmp = indices[i];
  38922. indices[i] = indices[i + 2];
  38923. indices[i + 2] = tmp;
  38924. }
  38925. // normals
  38926. for (n = 0; n < ln; n++) {
  38927. normals[n] = -normals[n];
  38928. }
  38929. break;
  38930. case BABYLON.Mesh.DOUBLESIDE:
  38931. // positions
  38932. var lp = positions.length;
  38933. var l = lp / 3;
  38934. for (var p = 0; p < lp; p++) {
  38935. positions[lp + p] = positions[p];
  38936. }
  38937. // indices
  38938. for (i = 0; i < li; i += 3) {
  38939. indices[i + li] = indices[i + 2] + l;
  38940. indices[i + 1 + li] = indices[i + 1] + l;
  38941. indices[i + 2 + li] = indices[i] + l;
  38942. }
  38943. // normals
  38944. for (n = 0; n < ln; n++) {
  38945. normals[ln + n] = -normals[n];
  38946. }
  38947. // uvs
  38948. var lu = uvs.length;
  38949. var u = 0;
  38950. for (u = 0; u < lu; u++) {
  38951. uvs[u + lu] = uvs[u];
  38952. }
  38953. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38954. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38955. u = 0;
  38956. for (i = 0; i < lu / 2; i++) {
  38957. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38958. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38959. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38960. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38961. u += 2;
  38962. }
  38963. break;
  38964. }
  38965. };
  38966. /**
  38967. * Applies VertexData created from the imported parameters to the geometry
  38968. * @param parsedVertexData the parsed data from an imported file
  38969. * @param geometry the geometry to apply the VertexData to
  38970. */
  38971. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38972. var vertexData = new VertexData();
  38973. // positions
  38974. var positions = parsedVertexData.positions;
  38975. if (positions) {
  38976. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38977. }
  38978. // normals
  38979. var normals = parsedVertexData.normals;
  38980. if (normals) {
  38981. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38982. }
  38983. // tangents
  38984. var tangents = parsedVertexData.tangents;
  38985. if (tangents) {
  38986. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38987. }
  38988. // uvs
  38989. var uvs = parsedVertexData.uvs;
  38990. if (uvs) {
  38991. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38992. }
  38993. // uv2s
  38994. var uv2s = parsedVertexData.uv2s;
  38995. if (uv2s) {
  38996. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38997. }
  38998. // uv3s
  38999. var uv3s = parsedVertexData.uv3s;
  39000. if (uv3s) {
  39001. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39002. }
  39003. // uv4s
  39004. var uv4s = parsedVertexData.uv4s;
  39005. if (uv4s) {
  39006. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39007. }
  39008. // uv5s
  39009. var uv5s = parsedVertexData.uv5s;
  39010. if (uv5s) {
  39011. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39012. }
  39013. // uv6s
  39014. var uv6s = parsedVertexData.uv6s;
  39015. if (uv6s) {
  39016. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39017. }
  39018. // colors
  39019. var colors = parsedVertexData.colors;
  39020. if (colors) {
  39021. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39022. }
  39023. // matricesIndices
  39024. var matricesIndices = parsedVertexData.matricesIndices;
  39025. if (matricesIndices) {
  39026. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39027. }
  39028. // matricesWeights
  39029. var matricesWeights = parsedVertexData.matricesWeights;
  39030. if (matricesWeights) {
  39031. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39032. }
  39033. // indices
  39034. var indices = parsedVertexData.indices;
  39035. if (indices) {
  39036. vertexData.indices = indices;
  39037. }
  39038. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39039. };
  39040. return VertexData;
  39041. }());
  39042. BABYLON.VertexData = VertexData;
  39043. })(BABYLON || (BABYLON = {}));
  39044. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39045. var BABYLON;
  39046. (function (BABYLON) {
  39047. /**
  39048. * Class used to store geometry data (vertex buffers + index buffer)
  39049. */
  39050. var Geometry = /** @class */ (function () {
  39051. /**
  39052. * Creates a new geometry
  39053. * @param id defines the unique ID
  39054. * @param scene defines the hosting scene
  39055. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39056. * @param updatable defines if geometry must be updatable (false by default)
  39057. * @param mesh defines the mesh that will be associated with the geometry
  39058. */
  39059. function Geometry(id, scene, vertexData, updatable, mesh) {
  39060. if (updatable === void 0) { updatable = false; }
  39061. if (mesh === void 0) { mesh = null; }
  39062. /**
  39063. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39064. */
  39065. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39066. this._totalVertices = 0;
  39067. this._isDisposed = false;
  39068. this._indexBufferIsUpdatable = false;
  39069. this.id = id;
  39070. this._engine = scene.getEngine();
  39071. this._meshes = [];
  39072. this._scene = scene;
  39073. //Init vertex buffer cache
  39074. this._vertexBuffers = {};
  39075. this._indices = [];
  39076. this._updatable = updatable;
  39077. // vertexData
  39078. if (vertexData) {
  39079. this.setAllVerticesData(vertexData, updatable);
  39080. }
  39081. else {
  39082. this._totalVertices = 0;
  39083. this._indices = [];
  39084. }
  39085. if (this._engine.getCaps().vertexArrayObject) {
  39086. this._vertexArrayObjects = {};
  39087. }
  39088. // applyToMesh
  39089. if (mesh) {
  39090. if (mesh.getClassName() === "LinesMesh") {
  39091. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39092. this._updateExtend();
  39093. }
  39094. this.applyToMesh(mesh);
  39095. mesh.computeWorldMatrix(true);
  39096. }
  39097. }
  39098. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39099. /**
  39100. * 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
  39101. */
  39102. get: function () {
  39103. return this._boundingBias;
  39104. },
  39105. /**
  39106. * 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
  39107. */
  39108. set: function (value) {
  39109. if (this._boundingBias && this._boundingBias.equals(value)) {
  39110. return;
  39111. }
  39112. this._boundingBias = value.clone();
  39113. this._updateBoundingInfo(true, null);
  39114. },
  39115. enumerable: true,
  39116. configurable: true
  39117. });
  39118. /**
  39119. * Static function used to attach a new empty geometry to a mesh
  39120. * @param mesh defines the mesh to attach the geometry to
  39121. * @returns the new {BABYLON.Geometry}
  39122. */
  39123. Geometry.CreateGeometryForMesh = function (mesh) {
  39124. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39125. geometry.applyToMesh(mesh);
  39126. return geometry;
  39127. };
  39128. Object.defineProperty(Geometry.prototype, "extend", {
  39129. /**
  39130. * Gets the current extend of the geometry
  39131. */
  39132. get: function () {
  39133. return this._extend;
  39134. },
  39135. enumerable: true,
  39136. configurable: true
  39137. });
  39138. /**
  39139. * Gets the hosting scene
  39140. * @returns the hosting {BABYLON.Scene}
  39141. */
  39142. Geometry.prototype.getScene = function () {
  39143. return this._scene;
  39144. };
  39145. /**
  39146. * Gets the hosting engine
  39147. * @returns the hosting {BABYLON.Engine}
  39148. */
  39149. Geometry.prototype.getEngine = function () {
  39150. return this._engine;
  39151. };
  39152. /**
  39153. * Defines if the geometry is ready to use
  39154. * @returns true if the geometry is ready to be used
  39155. */
  39156. Geometry.prototype.isReady = function () {
  39157. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39158. };
  39159. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39160. /**
  39161. * Gets a value indicating that the geometry should not be serialized
  39162. */
  39163. get: function () {
  39164. for (var index = 0; index < this._meshes.length; index++) {
  39165. if (!this._meshes[index].doNotSerialize) {
  39166. return false;
  39167. }
  39168. }
  39169. return true;
  39170. },
  39171. enumerable: true,
  39172. configurable: true
  39173. });
  39174. /** @hidden */
  39175. Geometry.prototype._rebuild = function () {
  39176. if (this._vertexArrayObjects) {
  39177. this._vertexArrayObjects = {};
  39178. }
  39179. // Index buffer
  39180. if (this._meshes.length !== 0 && this._indices) {
  39181. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39182. }
  39183. // Vertex buffers
  39184. for (var key in this._vertexBuffers) {
  39185. var vertexBuffer = this._vertexBuffers[key];
  39186. vertexBuffer._rebuild();
  39187. }
  39188. };
  39189. /**
  39190. * Affects all geometry data in one call
  39191. * @param vertexData defines the geometry data
  39192. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39193. */
  39194. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39195. vertexData.applyToGeometry(this, updatable);
  39196. this.notifyUpdate();
  39197. };
  39198. /**
  39199. * Set specific vertex data
  39200. * @param kind defines the data kind (Position, normal, etc...)
  39201. * @param data defines the vertex data to use
  39202. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39203. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39204. */
  39205. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39206. if (updatable === void 0) { updatable = false; }
  39207. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39208. this.setVerticesBuffer(buffer);
  39209. };
  39210. /**
  39211. * Removes a specific vertex data
  39212. * @param kind defines the data kind (Position, normal, etc...)
  39213. */
  39214. Geometry.prototype.removeVerticesData = function (kind) {
  39215. if (this._vertexBuffers[kind]) {
  39216. this._vertexBuffers[kind].dispose();
  39217. delete this._vertexBuffers[kind];
  39218. }
  39219. };
  39220. /**
  39221. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39222. * @param buffer defines the vertex buffer to use
  39223. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39224. */
  39225. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39226. if (totalVertices === void 0) { totalVertices = null; }
  39227. var kind = buffer.getKind();
  39228. if (this._vertexBuffers[kind]) {
  39229. this._vertexBuffers[kind].dispose();
  39230. }
  39231. this._vertexBuffers[kind] = buffer;
  39232. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39233. var data = buffer.getData();
  39234. if (totalVertices != null) {
  39235. this._totalVertices = totalVertices;
  39236. }
  39237. else {
  39238. if (data != null) {
  39239. this._totalVertices = data.length / (buffer.byteStride / 4);
  39240. }
  39241. }
  39242. this._updateExtend(data);
  39243. this._resetPointsArrayCache();
  39244. var meshes = this._meshes;
  39245. var numOfMeshes = meshes.length;
  39246. for (var index = 0; index < numOfMeshes; index++) {
  39247. var mesh = meshes[index];
  39248. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39249. mesh._createGlobalSubMesh(false);
  39250. mesh.computeWorldMatrix(true);
  39251. }
  39252. }
  39253. this.notifyUpdate(kind);
  39254. if (this._vertexArrayObjects) {
  39255. this._disposeVertexArrayObjects();
  39256. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39257. }
  39258. };
  39259. /**
  39260. * Update a specific vertex buffer
  39261. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39262. * It will do nothing if the buffer is not updatable
  39263. * @param kind defines the data kind (Position, normal, etc...)
  39264. * @param data defines the data to use
  39265. * @param offset defines the offset in the target buffer where to store the data
  39266. * @param useBytes set to true if the offset is in bytes
  39267. */
  39268. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39269. if (useBytes === void 0) { useBytes = false; }
  39270. var vertexBuffer = this.getVertexBuffer(kind);
  39271. if (!vertexBuffer) {
  39272. return;
  39273. }
  39274. vertexBuffer.updateDirectly(data, offset, useBytes);
  39275. this.notifyUpdate(kind);
  39276. };
  39277. /**
  39278. * Update a specific vertex buffer
  39279. * This function will create a new buffer if the current one is not updatable
  39280. * @param kind defines the data kind (Position, normal, etc...)
  39281. * @param data defines the data to use
  39282. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39283. */
  39284. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39285. if (updateExtends === void 0) { updateExtends = false; }
  39286. var vertexBuffer = this.getVertexBuffer(kind);
  39287. if (!vertexBuffer) {
  39288. return;
  39289. }
  39290. vertexBuffer.update(data);
  39291. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39292. this._updateBoundingInfo(updateExtends, data);
  39293. }
  39294. this.notifyUpdate(kind);
  39295. };
  39296. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39297. if (updateExtends) {
  39298. this._updateExtend(data);
  39299. }
  39300. var meshes = this._meshes;
  39301. var numOfMeshes = meshes.length;
  39302. this._resetPointsArrayCache();
  39303. for (var index = 0; index < numOfMeshes; index++) {
  39304. var mesh = meshes[index];
  39305. if (updateExtends) {
  39306. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39307. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39308. var subMesh = mesh.subMeshes[subIndex];
  39309. subMesh.refreshBoundingInfo();
  39310. }
  39311. }
  39312. }
  39313. };
  39314. /** @hidden */
  39315. Geometry.prototype._bind = function (effect, indexToBind) {
  39316. if (!effect) {
  39317. return;
  39318. }
  39319. if (indexToBind === undefined) {
  39320. indexToBind = this._indexBuffer;
  39321. }
  39322. var vbs = this.getVertexBuffers();
  39323. if (!vbs) {
  39324. return;
  39325. }
  39326. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39327. this._engine.bindBuffers(vbs, indexToBind, effect);
  39328. return;
  39329. }
  39330. // Using VAO
  39331. if (!this._vertexArrayObjects[effect.key]) {
  39332. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39333. }
  39334. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39335. };
  39336. /**
  39337. * Gets total number of vertices
  39338. * @returns the total number of vertices
  39339. */
  39340. Geometry.prototype.getTotalVertices = function () {
  39341. if (!this.isReady()) {
  39342. return 0;
  39343. }
  39344. return this._totalVertices;
  39345. };
  39346. /**
  39347. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39348. * @param kind defines the data kind (Position, normal, etc...)
  39349. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39350. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39351. * @returns a float array containing vertex data
  39352. */
  39353. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39354. var vertexBuffer = this.getVertexBuffer(kind);
  39355. if (!vertexBuffer) {
  39356. return null;
  39357. }
  39358. var data = vertexBuffer.getData();
  39359. if (!data) {
  39360. return null;
  39361. }
  39362. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39363. var count = this._totalVertices * vertexBuffer.getSize();
  39364. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39365. var copy_1 = new Array(count);
  39366. vertexBuffer.forEach(count, function (value, index) {
  39367. copy_1[index] = value;
  39368. });
  39369. return copy_1;
  39370. }
  39371. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39372. if (data instanceof Array) {
  39373. var offset = vertexBuffer.byteOffset / 4;
  39374. return BABYLON.Tools.Slice(data, offset, offset + count);
  39375. }
  39376. else if (data instanceof ArrayBuffer) {
  39377. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39378. }
  39379. else {
  39380. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39381. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39382. var result = new Float32Array(count);
  39383. var source = new Float32Array(data.buffer, offset, count);
  39384. result.set(source);
  39385. return result;
  39386. }
  39387. return new Float32Array(data.buffer, offset, count);
  39388. }
  39389. }
  39390. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39391. return BABYLON.Tools.Slice(data);
  39392. }
  39393. return data;
  39394. };
  39395. /**
  39396. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39397. * @param kind defines the data kind (Position, normal, etc...)
  39398. * @returns true if the vertex buffer with the specified kind is updatable
  39399. */
  39400. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39401. var vb = this._vertexBuffers[kind];
  39402. if (!vb) {
  39403. return false;
  39404. }
  39405. return vb.isUpdatable();
  39406. };
  39407. /**
  39408. * Gets a specific vertex buffer
  39409. * @param kind defines the data kind (Position, normal, etc...)
  39410. * @returns a {BABYLON.VertexBuffer}
  39411. */
  39412. Geometry.prototype.getVertexBuffer = function (kind) {
  39413. if (!this.isReady()) {
  39414. return null;
  39415. }
  39416. return this._vertexBuffers[kind];
  39417. };
  39418. /**
  39419. * Returns all vertex buffers
  39420. * @return an object holding all vertex buffers indexed by kind
  39421. */
  39422. Geometry.prototype.getVertexBuffers = function () {
  39423. if (!this.isReady()) {
  39424. return null;
  39425. }
  39426. return this._vertexBuffers;
  39427. };
  39428. /**
  39429. * Gets a boolean indicating if specific vertex buffer is present
  39430. * @param kind defines the data kind (Position, normal, etc...)
  39431. * @returns true if data is present
  39432. */
  39433. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39434. if (!this._vertexBuffers) {
  39435. if (this._delayInfo) {
  39436. return this._delayInfo.indexOf(kind) !== -1;
  39437. }
  39438. return false;
  39439. }
  39440. return this._vertexBuffers[kind] !== undefined;
  39441. };
  39442. /**
  39443. * Gets a list of all attached data kinds (Position, normal, etc...)
  39444. * @returns a list of string containing all kinds
  39445. */
  39446. Geometry.prototype.getVerticesDataKinds = function () {
  39447. var result = [];
  39448. var kind;
  39449. if (!this._vertexBuffers && this._delayInfo) {
  39450. for (kind in this._delayInfo) {
  39451. result.push(kind);
  39452. }
  39453. }
  39454. else {
  39455. for (kind in this._vertexBuffers) {
  39456. result.push(kind);
  39457. }
  39458. }
  39459. return result;
  39460. };
  39461. /**
  39462. * Update index buffer
  39463. * @param indices defines the indices to store in the index buffer
  39464. * @param offset defines the offset in the target buffer where to store the data
  39465. */
  39466. Geometry.prototype.updateIndices = function (indices, offset) {
  39467. if (!this._indexBuffer) {
  39468. return;
  39469. }
  39470. if (!this._indexBufferIsUpdatable) {
  39471. this.setIndices(indices, null, true);
  39472. }
  39473. else {
  39474. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39475. }
  39476. };
  39477. /**
  39478. * Creates a new index buffer
  39479. * @param indices defines the indices to store in the index buffer
  39480. * @param totalVertices defines the total number of vertices (could be null)
  39481. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39482. */
  39483. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39484. if (totalVertices === void 0) { totalVertices = null; }
  39485. if (updatable === void 0) { updatable = false; }
  39486. if (this._indexBuffer) {
  39487. this._engine._releaseBuffer(this._indexBuffer);
  39488. }
  39489. this._disposeVertexArrayObjects();
  39490. this._indices = indices;
  39491. this._indexBufferIsUpdatable = updatable;
  39492. if (this._meshes.length !== 0 && this._indices) {
  39493. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39494. }
  39495. if (totalVertices != undefined) { // including null and undefined
  39496. this._totalVertices = totalVertices;
  39497. }
  39498. var meshes = this._meshes;
  39499. var numOfMeshes = meshes.length;
  39500. for (var index = 0; index < numOfMeshes; index++) {
  39501. meshes[index]._createGlobalSubMesh(true);
  39502. }
  39503. this.notifyUpdate();
  39504. };
  39505. /**
  39506. * Return the total number of indices
  39507. * @returns the total number of indices
  39508. */
  39509. Geometry.prototype.getTotalIndices = function () {
  39510. if (!this.isReady()) {
  39511. return 0;
  39512. }
  39513. return this._indices.length;
  39514. };
  39515. /**
  39516. * Gets the index buffer array
  39517. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39518. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39519. * @returns the index buffer array
  39520. */
  39521. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39522. if (!this.isReady()) {
  39523. return null;
  39524. }
  39525. var orig = this._indices;
  39526. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39527. return orig;
  39528. }
  39529. else {
  39530. var len = orig.length;
  39531. var copy = [];
  39532. for (var i = 0; i < len; i++) {
  39533. copy.push(orig[i]);
  39534. }
  39535. return copy;
  39536. }
  39537. };
  39538. /**
  39539. * Gets the index buffer
  39540. * @return the index buffer
  39541. */
  39542. Geometry.prototype.getIndexBuffer = function () {
  39543. if (!this.isReady()) {
  39544. return null;
  39545. }
  39546. return this._indexBuffer;
  39547. };
  39548. /** @hidden */
  39549. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39550. if (effect === void 0) { effect = null; }
  39551. if (!effect || !this._vertexArrayObjects) {
  39552. return;
  39553. }
  39554. if (this._vertexArrayObjects[effect.key]) {
  39555. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39556. delete this._vertexArrayObjects[effect.key];
  39557. }
  39558. };
  39559. /**
  39560. * Release the associated resources for a specific mesh
  39561. * @param mesh defines the source mesh
  39562. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39563. */
  39564. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39565. var meshes = this._meshes;
  39566. var index = meshes.indexOf(mesh);
  39567. if (index === -1) {
  39568. return;
  39569. }
  39570. meshes.splice(index, 1);
  39571. mesh._geometry = null;
  39572. if (meshes.length === 0 && shouldDispose) {
  39573. this.dispose();
  39574. }
  39575. };
  39576. /**
  39577. * Apply current geometry to a given mesh
  39578. * @param mesh defines the mesh to apply geometry to
  39579. */
  39580. Geometry.prototype.applyToMesh = function (mesh) {
  39581. if (mesh._geometry === this) {
  39582. return;
  39583. }
  39584. var previousGeometry = mesh._geometry;
  39585. if (previousGeometry) {
  39586. previousGeometry.releaseForMesh(mesh);
  39587. }
  39588. var meshes = this._meshes;
  39589. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39590. mesh._geometry = this;
  39591. this._scene.pushGeometry(this);
  39592. meshes.push(mesh);
  39593. if (this.isReady()) {
  39594. this._applyToMesh(mesh);
  39595. }
  39596. else {
  39597. mesh._boundingInfo = this._boundingInfo;
  39598. }
  39599. };
  39600. Geometry.prototype._updateExtend = function (data) {
  39601. if (data === void 0) { data = null; }
  39602. if (!data) {
  39603. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39604. }
  39605. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39606. };
  39607. Geometry.prototype._applyToMesh = function (mesh) {
  39608. var numOfMeshes = this._meshes.length;
  39609. // vertexBuffers
  39610. for (var kind in this._vertexBuffers) {
  39611. if (numOfMeshes === 1) {
  39612. this._vertexBuffers[kind].create();
  39613. }
  39614. var buffer = this._vertexBuffers[kind].getBuffer();
  39615. if (buffer)
  39616. buffer.references = numOfMeshes;
  39617. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39618. if (!this._extend) {
  39619. this._updateExtend();
  39620. }
  39621. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39622. mesh._createGlobalSubMesh(false);
  39623. //bounding info was just created again, world matrix should be applied again.
  39624. mesh._updateBoundingInfo();
  39625. }
  39626. }
  39627. // indexBuffer
  39628. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39629. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39630. }
  39631. if (this._indexBuffer) {
  39632. this._indexBuffer.references = numOfMeshes;
  39633. }
  39634. };
  39635. Geometry.prototype.notifyUpdate = function (kind) {
  39636. if (this.onGeometryUpdated) {
  39637. this.onGeometryUpdated(this, kind);
  39638. }
  39639. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39640. var mesh = _a[_i];
  39641. mesh._markSubMeshesAsAttributesDirty();
  39642. }
  39643. };
  39644. /**
  39645. * Load the geometry if it was flagged as delay loaded
  39646. * @param scene defines the hosting scene
  39647. * @param onLoaded defines a callback called when the geometry is loaded
  39648. */
  39649. Geometry.prototype.load = function (scene, onLoaded) {
  39650. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39651. return;
  39652. }
  39653. if (this.isReady()) {
  39654. if (onLoaded) {
  39655. onLoaded();
  39656. }
  39657. return;
  39658. }
  39659. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39660. this._queueLoad(scene, onLoaded);
  39661. };
  39662. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39663. var _this = this;
  39664. if (!this.delayLoadingFile) {
  39665. return;
  39666. }
  39667. scene._addPendingData(this);
  39668. scene._loadFile(this.delayLoadingFile, function (data) {
  39669. if (!_this._delayLoadingFunction) {
  39670. return;
  39671. }
  39672. _this._delayLoadingFunction(JSON.parse(data), _this);
  39673. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39674. _this._delayInfo = [];
  39675. scene._removePendingData(_this);
  39676. var meshes = _this._meshes;
  39677. var numOfMeshes = meshes.length;
  39678. for (var index = 0; index < numOfMeshes; index++) {
  39679. _this._applyToMesh(meshes[index]);
  39680. }
  39681. if (onLoaded) {
  39682. onLoaded();
  39683. }
  39684. }, undefined, true);
  39685. };
  39686. /**
  39687. * Invert the geometry to move from a right handed system to a left handed one.
  39688. */
  39689. Geometry.prototype.toLeftHanded = function () {
  39690. // Flip faces
  39691. var tIndices = this.getIndices(false);
  39692. if (tIndices != null && tIndices.length > 0) {
  39693. for (var i = 0; i < tIndices.length; i += 3) {
  39694. var tTemp = tIndices[i + 0];
  39695. tIndices[i + 0] = tIndices[i + 2];
  39696. tIndices[i + 2] = tTemp;
  39697. }
  39698. this.setIndices(tIndices);
  39699. }
  39700. // Negate position.z
  39701. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39702. if (tPositions != null && tPositions.length > 0) {
  39703. for (var i = 0; i < tPositions.length; i += 3) {
  39704. tPositions[i + 2] = -tPositions[i + 2];
  39705. }
  39706. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39707. }
  39708. // Negate normal.z
  39709. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39710. if (tNormals != null && tNormals.length > 0) {
  39711. for (var i = 0; i < tNormals.length; i += 3) {
  39712. tNormals[i + 2] = -tNormals[i + 2];
  39713. }
  39714. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39715. }
  39716. };
  39717. // Cache
  39718. /** @hidden */
  39719. Geometry.prototype._resetPointsArrayCache = function () {
  39720. this._positions = null;
  39721. };
  39722. /** @hidden */
  39723. Geometry.prototype._generatePointsArray = function () {
  39724. if (this._positions)
  39725. return true;
  39726. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39727. if (!data || data.length === 0) {
  39728. return false;
  39729. }
  39730. this._positions = [];
  39731. for (var index = 0; index < data.length; index += 3) {
  39732. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39733. }
  39734. return true;
  39735. };
  39736. /**
  39737. * Gets a value indicating if the geometry is disposed
  39738. * @returns true if the geometry was disposed
  39739. */
  39740. Geometry.prototype.isDisposed = function () {
  39741. return this._isDisposed;
  39742. };
  39743. Geometry.prototype._disposeVertexArrayObjects = function () {
  39744. if (this._vertexArrayObjects) {
  39745. for (var kind in this._vertexArrayObjects) {
  39746. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39747. }
  39748. this._vertexArrayObjects = {};
  39749. }
  39750. };
  39751. /**
  39752. * Free all associated resources
  39753. */
  39754. Geometry.prototype.dispose = function () {
  39755. var meshes = this._meshes;
  39756. var numOfMeshes = meshes.length;
  39757. var index;
  39758. for (index = 0; index < numOfMeshes; index++) {
  39759. this.releaseForMesh(meshes[index]);
  39760. }
  39761. this._meshes = [];
  39762. this._disposeVertexArrayObjects();
  39763. for (var kind in this._vertexBuffers) {
  39764. this._vertexBuffers[kind].dispose();
  39765. }
  39766. this._vertexBuffers = {};
  39767. this._totalVertices = 0;
  39768. if (this._indexBuffer) {
  39769. this._engine._releaseBuffer(this._indexBuffer);
  39770. }
  39771. this._indexBuffer = null;
  39772. this._indices = [];
  39773. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39774. this.delayLoadingFile = null;
  39775. this._delayLoadingFunction = null;
  39776. this._delayInfo = [];
  39777. this._boundingInfo = null;
  39778. this._scene.removeGeometry(this);
  39779. this._isDisposed = true;
  39780. };
  39781. /**
  39782. * Clone the current geometry into a new geometry
  39783. * @param id defines the unique ID of the new geometry
  39784. * @returns a new geometry object
  39785. */
  39786. Geometry.prototype.copy = function (id) {
  39787. var vertexData = new BABYLON.VertexData();
  39788. vertexData.indices = [];
  39789. var indices = this.getIndices();
  39790. if (indices) {
  39791. for (var index = 0; index < indices.length; index++) {
  39792. vertexData.indices.push(indices[index]);
  39793. }
  39794. }
  39795. var updatable = false;
  39796. var stopChecking = false;
  39797. var kind;
  39798. for (kind in this._vertexBuffers) {
  39799. // using slice() to make a copy of the array and not just reference it
  39800. var data = this.getVerticesData(kind);
  39801. if (data instanceof Float32Array) {
  39802. vertexData.set(new Float32Array(data), kind);
  39803. }
  39804. else {
  39805. vertexData.set(data.slice(0), kind);
  39806. }
  39807. if (!stopChecking) {
  39808. var vb = this.getVertexBuffer(kind);
  39809. if (vb) {
  39810. updatable = vb.isUpdatable();
  39811. stopChecking = !updatable;
  39812. }
  39813. }
  39814. }
  39815. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39816. geometry.delayLoadState = this.delayLoadState;
  39817. geometry.delayLoadingFile = this.delayLoadingFile;
  39818. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39819. for (kind in this._delayInfo) {
  39820. geometry._delayInfo = geometry._delayInfo || [];
  39821. geometry._delayInfo.push(kind);
  39822. }
  39823. // Bounding info
  39824. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39825. return geometry;
  39826. };
  39827. /**
  39828. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39829. * @return a JSON representation of the current geometry data (without the vertices data)
  39830. */
  39831. Geometry.prototype.serialize = function () {
  39832. var serializationObject = {};
  39833. serializationObject.id = this.id;
  39834. serializationObject.updatable = this._updatable;
  39835. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39836. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39837. }
  39838. return serializationObject;
  39839. };
  39840. Geometry.prototype.toNumberArray = function (origin) {
  39841. if (Array.isArray(origin)) {
  39842. return origin;
  39843. }
  39844. else {
  39845. return Array.prototype.slice.call(origin);
  39846. }
  39847. };
  39848. /**
  39849. * Serialize all vertices data into a JSON oject
  39850. * @returns a JSON representation of the current geometry data
  39851. */
  39852. Geometry.prototype.serializeVerticeData = function () {
  39853. var serializationObject = this.serialize();
  39854. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39855. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39856. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39857. serializationObject.positions._updatable = true;
  39858. }
  39859. }
  39860. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39861. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39862. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39863. serializationObject.normals._updatable = true;
  39864. }
  39865. }
  39866. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39867. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39868. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39869. serializationObject.tangets._updatable = true;
  39870. }
  39871. }
  39872. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39873. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39874. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39875. serializationObject.uvs._updatable = true;
  39876. }
  39877. }
  39878. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39879. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39880. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39881. serializationObject.uv2s._updatable = true;
  39882. }
  39883. }
  39884. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39885. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39886. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39887. serializationObject.uv3s._updatable = true;
  39888. }
  39889. }
  39890. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39891. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39892. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39893. serializationObject.uv4s._updatable = true;
  39894. }
  39895. }
  39896. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39897. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39898. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39899. serializationObject.uv5s._updatable = true;
  39900. }
  39901. }
  39902. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39903. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39904. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39905. serializationObject.uv6s._updatable = true;
  39906. }
  39907. }
  39908. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39909. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39910. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39911. serializationObject.colors._updatable = true;
  39912. }
  39913. }
  39914. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39915. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39916. serializationObject.matricesIndices._isExpanded = true;
  39917. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39918. serializationObject.matricesIndices._updatable = true;
  39919. }
  39920. }
  39921. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39922. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39923. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39924. serializationObject.matricesWeights._updatable = true;
  39925. }
  39926. }
  39927. serializationObject.indices = this.toNumberArray(this.getIndices());
  39928. return serializationObject;
  39929. };
  39930. // Statics
  39931. /**
  39932. * Extracts a clone of a mesh geometry
  39933. * @param mesh defines the source mesh
  39934. * @param id defines the unique ID of the new geometry object
  39935. * @returns the new geometry object
  39936. */
  39937. Geometry.ExtractFromMesh = function (mesh, id) {
  39938. var geometry = mesh._geometry;
  39939. if (!geometry) {
  39940. return null;
  39941. }
  39942. return geometry.copy(id);
  39943. };
  39944. /**
  39945. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39946. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39947. * Be aware Math.random() could cause collisions, but:
  39948. * "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"
  39949. * @returns a string containing a new GUID
  39950. */
  39951. Geometry.RandomId = function () {
  39952. return BABYLON.Tools.RandomId();
  39953. };
  39954. /** @hidden */
  39955. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39956. var scene = mesh.getScene();
  39957. // Geometry
  39958. var geometryId = parsedGeometry.geometryId;
  39959. if (geometryId) {
  39960. var geometry = scene.getGeometryByID(geometryId);
  39961. if (geometry) {
  39962. geometry.applyToMesh(mesh);
  39963. }
  39964. }
  39965. else if (parsedGeometry instanceof ArrayBuffer) {
  39966. var binaryInfo = mesh._binaryInfo;
  39967. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39968. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39969. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39970. }
  39971. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39972. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39973. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39974. }
  39975. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39976. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39977. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39978. }
  39979. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39980. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39981. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39982. }
  39983. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39984. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39985. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39986. }
  39987. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39988. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39989. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39990. }
  39991. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39992. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39993. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39994. }
  39995. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39996. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39997. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39998. }
  39999. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40000. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40001. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40002. }
  40003. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40004. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40005. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40006. }
  40007. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40008. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40009. var floatIndices = [];
  40010. for (var i = 0; i < matricesIndicesData.length; i++) {
  40011. var index = matricesIndicesData[i];
  40012. floatIndices.push(index & 0x000000FF);
  40013. floatIndices.push((index & 0x0000FF00) >> 8);
  40014. floatIndices.push((index & 0x00FF0000) >> 16);
  40015. floatIndices.push(index >> 24);
  40016. }
  40017. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40018. }
  40019. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40020. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40021. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40022. }
  40023. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40024. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40025. mesh.setIndices(indicesData, null);
  40026. }
  40027. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40028. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40029. mesh.subMeshes = [];
  40030. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40031. var materialIndex = subMeshesData[(i * 5) + 0];
  40032. var verticesStart = subMeshesData[(i * 5) + 1];
  40033. var verticesCount = subMeshesData[(i * 5) + 2];
  40034. var indexStart = subMeshesData[(i * 5) + 3];
  40035. var indexCount = subMeshesData[(i * 5) + 4];
  40036. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40037. }
  40038. }
  40039. }
  40040. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40041. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40042. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40043. if (parsedGeometry.tangents) {
  40044. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40045. }
  40046. if (parsedGeometry.uvs) {
  40047. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40048. }
  40049. if (parsedGeometry.uvs2) {
  40050. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40051. }
  40052. if (parsedGeometry.uvs3) {
  40053. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40054. }
  40055. if (parsedGeometry.uvs4) {
  40056. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40057. }
  40058. if (parsedGeometry.uvs5) {
  40059. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40060. }
  40061. if (parsedGeometry.uvs6) {
  40062. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40063. }
  40064. if (parsedGeometry.colors) {
  40065. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40066. }
  40067. if (parsedGeometry.matricesIndices) {
  40068. if (!parsedGeometry.matricesIndices._isExpanded) {
  40069. var floatIndices = [];
  40070. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40071. var matricesIndex = parsedGeometry.matricesIndices[i];
  40072. floatIndices.push(matricesIndex & 0x000000FF);
  40073. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40074. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40075. floatIndices.push(matricesIndex >> 24);
  40076. }
  40077. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40078. }
  40079. else {
  40080. delete parsedGeometry.matricesIndices._isExpanded;
  40081. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40082. }
  40083. }
  40084. if (parsedGeometry.matricesIndicesExtra) {
  40085. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40086. var floatIndices = [];
  40087. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40088. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40089. floatIndices.push(matricesIndex & 0x000000FF);
  40090. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40091. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40092. floatIndices.push(matricesIndex >> 24);
  40093. }
  40094. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40095. }
  40096. else {
  40097. delete parsedGeometry.matricesIndices._isExpanded;
  40098. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40099. }
  40100. }
  40101. if (parsedGeometry.matricesWeights) {
  40102. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40103. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40104. }
  40105. if (parsedGeometry.matricesWeightsExtra) {
  40106. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40107. }
  40108. mesh.setIndices(parsedGeometry.indices, null);
  40109. }
  40110. // SubMeshes
  40111. if (parsedGeometry.subMeshes) {
  40112. mesh.subMeshes = [];
  40113. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40114. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40115. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40116. }
  40117. }
  40118. // Flat shading
  40119. if (mesh._shouldGenerateFlatShading) {
  40120. mesh.convertToFlatShadedMesh();
  40121. delete mesh._shouldGenerateFlatShading;
  40122. }
  40123. // Update
  40124. mesh.computeWorldMatrix(true);
  40125. scene.onMeshImportedObservable.notifyObservers(mesh);
  40126. };
  40127. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40128. var epsilon = 1e-3;
  40129. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40130. return;
  40131. }
  40132. var noInfluenceBoneIndex = 0.0;
  40133. if (parsedGeometry.skeletonId > -1) {
  40134. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40135. if (!skeleton) {
  40136. return;
  40137. }
  40138. noInfluenceBoneIndex = skeleton.bones.length;
  40139. }
  40140. else {
  40141. return;
  40142. }
  40143. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40144. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40145. var matricesWeights = parsedGeometry.matricesWeights;
  40146. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40147. var influencers = parsedGeometry.numBoneInfluencer;
  40148. var size = matricesWeights.length;
  40149. for (var i = 0; i < size; i += 4) {
  40150. var weight = 0.0;
  40151. var firstZeroWeight = -1;
  40152. for (var j = 0; j < 4; j++) {
  40153. var w = matricesWeights[i + j];
  40154. weight += w;
  40155. if (w < epsilon && firstZeroWeight < 0) {
  40156. firstZeroWeight = j;
  40157. }
  40158. }
  40159. if (matricesWeightsExtra) {
  40160. for (var j = 0; j < 4; j++) {
  40161. var w = matricesWeightsExtra[i + j];
  40162. weight += w;
  40163. if (w < epsilon && firstZeroWeight < 0) {
  40164. firstZeroWeight = j + 4;
  40165. }
  40166. }
  40167. }
  40168. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40169. firstZeroWeight = influencers - 1;
  40170. }
  40171. if (weight > epsilon) {
  40172. var mweight = 1.0 / weight;
  40173. for (var j = 0; j < 4; j++) {
  40174. matricesWeights[i + j] *= mweight;
  40175. }
  40176. if (matricesWeightsExtra) {
  40177. for (var j = 0; j < 4; j++) {
  40178. matricesWeightsExtra[i + j] *= mweight;
  40179. }
  40180. }
  40181. }
  40182. else {
  40183. if (firstZeroWeight >= 4) {
  40184. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40185. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40186. }
  40187. else {
  40188. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40189. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40190. }
  40191. }
  40192. }
  40193. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40194. if (parsedGeometry.matricesWeightsExtra) {
  40195. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40196. }
  40197. };
  40198. /**
  40199. * Create a new geometry from persisted data (Using .babylon file format)
  40200. * @param parsedVertexData defines the persisted data
  40201. * @param scene defines the hosting scene
  40202. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40203. * @returns the new geometry object
  40204. */
  40205. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40206. if (scene.getGeometryByID(parsedVertexData.id)) {
  40207. return null; // null since geometry could be something else than a box...
  40208. }
  40209. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40210. if (BABYLON.Tags) {
  40211. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40212. }
  40213. if (parsedVertexData.delayLoadingFile) {
  40214. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40215. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40216. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40217. geometry._delayInfo = [];
  40218. if (parsedVertexData.hasUVs) {
  40219. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40220. }
  40221. if (parsedVertexData.hasUVs2) {
  40222. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40223. }
  40224. if (parsedVertexData.hasUVs3) {
  40225. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40226. }
  40227. if (parsedVertexData.hasUVs4) {
  40228. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40229. }
  40230. if (parsedVertexData.hasUVs5) {
  40231. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40232. }
  40233. if (parsedVertexData.hasUVs6) {
  40234. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40235. }
  40236. if (parsedVertexData.hasColors) {
  40237. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40238. }
  40239. if (parsedVertexData.hasMatricesIndices) {
  40240. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40241. }
  40242. if (parsedVertexData.hasMatricesWeights) {
  40243. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40244. }
  40245. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40246. }
  40247. else {
  40248. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40249. }
  40250. scene.pushGeometry(geometry, true);
  40251. return geometry;
  40252. };
  40253. return Geometry;
  40254. }());
  40255. BABYLON.Geometry = Geometry;
  40256. // Primitives
  40257. /// Abstract class
  40258. /**
  40259. * Abstract class used to provide common services for all typed geometries
  40260. * @hidden
  40261. */
  40262. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40263. __extends(_PrimitiveGeometry, _super);
  40264. /**
  40265. * Creates a new typed geometry
  40266. * @param id defines the unique ID of the geometry
  40267. * @param scene defines the hosting scene
  40268. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40269. * @param mesh defines the hosting mesh (can be null)
  40270. */
  40271. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40272. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40273. if (mesh === void 0) { mesh = null; }
  40274. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40275. _this._canBeRegenerated = _canBeRegenerated;
  40276. _this._beingRegenerated = true;
  40277. _this.regenerate();
  40278. _this._beingRegenerated = false;
  40279. return _this;
  40280. }
  40281. /**
  40282. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40283. * @returns true if the geometry can be regenerated
  40284. */
  40285. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40286. return this._canBeRegenerated;
  40287. };
  40288. /**
  40289. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40290. */
  40291. _PrimitiveGeometry.prototype.regenerate = function () {
  40292. if (!this._canBeRegenerated) {
  40293. return;
  40294. }
  40295. this._beingRegenerated = true;
  40296. this.setAllVerticesData(this._regenerateVertexData(), false);
  40297. this._beingRegenerated = false;
  40298. };
  40299. /**
  40300. * Clone the geometry
  40301. * @param id defines the unique ID of the new geometry
  40302. * @returns the new geometry
  40303. */
  40304. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40305. return _super.prototype.copy.call(this, id);
  40306. };
  40307. // overrides
  40308. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40309. if (!this._beingRegenerated) {
  40310. return;
  40311. }
  40312. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40313. };
  40314. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40315. if (!this._beingRegenerated) {
  40316. return;
  40317. }
  40318. _super.prototype.setVerticesData.call(this, kind, data, false);
  40319. };
  40320. // to override
  40321. /** @hidden */
  40322. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40323. throw new Error("Abstract method");
  40324. };
  40325. _PrimitiveGeometry.prototype.copy = function (id) {
  40326. throw new Error("Must be overriden in sub-classes.");
  40327. };
  40328. _PrimitiveGeometry.prototype.serialize = function () {
  40329. var serializationObject = _super.prototype.serialize.call(this);
  40330. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40331. return serializationObject;
  40332. };
  40333. return _PrimitiveGeometry;
  40334. }(Geometry));
  40335. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40336. /**
  40337. * Creates a ribbon geometry
  40338. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40339. */
  40340. var RibbonGeometry = /** @class */ (function (_super) {
  40341. __extends(RibbonGeometry, _super);
  40342. /**
  40343. * Creates a ribbon geometry
  40344. * @param id defines the unique ID of the geometry
  40345. * @param scene defines the hosting scene
  40346. * @param pathArray defines the array of paths to use
  40347. * @param closeArray defines if the last path and the first path must be joined
  40348. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40349. * @param offset defines the offset between points
  40350. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40351. * @param mesh defines the hosting mesh (can be null)
  40352. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40353. */
  40354. function RibbonGeometry(id, scene,
  40355. /**
  40356. * Defines the array of paths to use
  40357. */
  40358. pathArray,
  40359. /**
  40360. * Defines if the last and first points of each path in your pathArray must be joined
  40361. */
  40362. closeArray,
  40363. /**
  40364. * Defines if the last and first points of each path in your pathArray must be joined
  40365. */
  40366. closePath,
  40367. /**
  40368. * Defines the offset between points
  40369. */
  40370. offset, canBeRegenerated, mesh,
  40371. /**
  40372. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40373. */
  40374. side) {
  40375. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40376. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40377. _this.pathArray = pathArray;
  40378. _this.closeArray = closeArray;
  40379. _this.closePath = closePath;
  40380. _this.offset = offset;
  40381. _this.side = side;
  40382. return _this;
  40383. }
  40384. /** @hidden */
  40385. RibbonGeometry.prototype._regenerateVertexData = function () {
  40386. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40387. };
  40388. RibbonGeometry.prototype.copy = function (id) {
  40389. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40390. };
  40391. return RibbonGeometry;
  40392. }(_PrimitiveGeometry));
  40393. BABYLON.RibbonGeometry = RibbonGeometry;
  40394. /**
  40395. * Creates a box geometry
  40396. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40397. */
  40398. var BoxGeometry = /** @class */ (function (_super) {
  40399. __extends(BoxGeometry, _super);
  40400. /**
  40401. * Creates a box geometry
  40402. * @param id defines the unique ID of the geometry
  40403. * @param scene defines the hosting scene
  40404. * @param size defines the zise of the box (width, height and depth are the same)
  40405. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40406. * @param mesh defines the hosting mesh (can be null)
  40407. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40408. */
  40409. function BoxGeometry(id, scene,
  40410. /**
  40411. * Defines the zise of the box (width, height and depth are the same)
  40412. */
  40413. size, canBeRegenerated, mesh,
  40414. /**
  40415. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40416. */
  40417. side) {
  40418. if (mesh === void 0) { mesh = null; }
  40419. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40420. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40421. _this.size = size;
  40422. _this.side = side;
  40423. return _this;
  40424. }
  40425. /** @hidden */
  40426. BoxGeometry.prototype._regenerateVertexData = function () {
  40427. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40428. };
  40429. BoxGeometry.prototype.copy = function (id) {
  40430. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40431. };
  40432. BoxGeometry.prototype.serialize = function () {
  40433. var serializationObject = _super.prototype.serialize.call(this);
  40434. serializationObject.size = this.size;
  40435. return serializationObject;
  40436. };
  40437. BoxGeometry.Parse = function (parsedBox, scene) {
  40438. if (scene.getGeometryByID(parsedBox.id)) {
  40439. return null; // null since geometry could be something else than a box...
  40440. }
  40441. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40442. if (BABYLON.Tags) {
  40443. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40444. }
  40445. scene.pushGeometry(box, true);
  40446. return box;
  40447. };
  40448. return BoxGeometry;
  40449. }(_PrimitiveGeometry));
  40450. BABYLON.BoxGeometry = BoxGeometry;
  40451. /**
  40452. * Creates a sphere geometry
  40453. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40454. */
  40455. var SphereGeometry = /** @class */ (function (_super) {
  40456. __extends(SphereGeometry, _super);
  40457. /**
  40458. * Create a new sphere geometry
  40459. * @param id defines the unique ID of the geometry
  40460. * @param scene defines the hosting scene
  40461. * @param segments defines the number of segments to use to create the sphere
  40462. * @param diameter defines the diameter of the sphere
  40463. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40464. * @param mesh defines the hosting mesh (can be null)
  40465. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40466. */
  40467. function SphereGeometry(id, scene,
  40468. /**
  40469. * Defines the number of segments to use to create the sphere
  40470. */
  40471. segments,
  40472. /**
  40473. * Defines the diameter of the sphere
  40474. */
  40475. diameter, canBeRegenerated, mesh,
  40476. /**
  40477. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40478. */
  40479. side) {
  40480. if (mesh === void 0) { mesh = null; }
  40481. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40482. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40483. _this.segments = segments;
  40484. _this.diameter = diameter;
  40485. _this.side = side;
  40486. return _this;
  40487. }
  40488. /** @hidden */
  40489. SphereGeometry.prototype._regenerateVertexData = function () {
  40490. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40491. };
  40492. SphereGeometry.prototype.copy = function (id) {
  40493. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40494. };
  40495. SphereGeometry.prototype.serialize = function () {
  40496. var serializationObject = _super.prototype.serialize.call(this);
  40497. serializationObject.segments = this.segments;
  40498. serializationObject.diameter = this.diameter;
  40499. return serializationObject;
  40500. };
  40501. SphereGeometry.Parse = function (parsedSphere, scene) {
  40502. if (scene.getGeometryByID(parsedSphere.id)) {
  40503. return null; // null since geometry could be something else than a sphere...
  40504. }
  40505. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40506. if (BABYLON.Tags) {
  40507. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40508. }
  40509. scene.pushGeometry(sphere, true);
  40510. return sphere;
  40511. };
  40512. return SphereGeometry;
  40513. }(_PrimitiveGeometry));
  40514. BABYLON.SphereGeometry = SphereGeometry;
  40515. /**
  40516. * Creates a disc geometry
  40517. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40518. */
  40519. var DiscGeometry = /** @class */ (function (_super) {
  40520. __extends(DiscGeometry, _super);
  40521. /**
  40522. * Creates a new disc geometry
  40523. * @param id defines the unique ID of the geometry
  40524. * @param scene defines the hosting scene
  40525. * @param radius defines the radius of the disc
  40526. * @param tessellation defines the tesselation factor to apply to the disc
  40527. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40528. * @param mesh defines the hosting mesh (can be null)
  40529. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40530. */
  40531. function DiscGeometry(id, scene,
  40532. /**
  40533. * Defines the radius of the disc
  40534. */
  40535. radius,
  40536. /**
  40537. * Defines the tesselation factor to apply to the disc
  40538. */
  40539. tessellation, canBeRegenerated, mesh,
  40540. /**
  40541. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40542. */
  40543. side) {
  40544. if (mesh === void 0) { mesh = null; }
  40545. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40546. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40547. _this.radius = radius;
  40548. _this.tessellation = tessellation;
  40549. _this.side = side;
  40550. return _this;
  40551. }
  40552. /** @hidden */
  40553. DiscGeometry.prototype._regenerateVertexData = function () {
  40554. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40555. };
  40556. DiscGeometry.prototype.copy = function (id) {
  40557. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40558. };
  40559. return DiscGeometry;
  40560. }(_PrimitiveGeometry));
  40561. BABYLON.DiscGeometry = DiscGeometry;
  40562. /**
  40563. * Creates a new cylinder geometry
  40564. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40565. */
  40566. var CylinderGeometry = /** @class */ (function (_super) {
  40567. __extends(CylinderGeometry, _super);
  40568. /**
  40569. * Creates a new cylinder geometry
  40570. * @param id defines the unique ID of the geometry
  40571. * @param scene defines the hosting scene
  40572. * @param height defines the height of the cylinder
  40573. * @param diameterTop defines the diameter of the cylinder's top cap
  40574. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40575. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40576. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40577. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40578. * @param mesh defines the hosting mesh (can be null)
  40579. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40580. */
  40581. function CylinderGeometry(id, scene,
  40582. /**
  40583. * Defines the height of the cylinder
  40584. */
  40585. height,
  40586. /**
  40587. * Defines the diameter of the cylinder's top cap
  40588. */
  40589. diameterTop,
  40590. /**
  40591. * Defines the diameter of the cylinder's bottom cap
  40592. */
  40593. diameterBottom,
  40594. /**
  40595. * Defines the tessellation factor to apply to the cylinder
  40596. */
  40597. tessellation,
  40598. /**
  40599. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40600. */
  40601. subdivisions, canBeRegenerated, mesh,
  40602. /**
  40603. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40604. */
  40605. side) {
  40606. if (subdivisions === void 0) { subdivisions = 1; }
  40607. if (mesh === void 0) { mesh = null; }
  40608. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40609. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40610. _this.height = height;
  40611. _this.diameterTop = diameterTop;
  40612. _this.diameterBottom = diameterBottom;
  40613. _this.tessellation = tessellation;
  40614. _this.subdivisions = subdivisions;
  40615. _this.side = side;
  40616. return _this;
  40617. }
  40618. /** @hidden */
  40619. CylinderGeometry.prototype._regenerateVertexData = function () {
  40620. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40621. };
  40622. CylinderGeometry.prototype.copy = function (id) {
  40623. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40624. };
  40625. CylinderGeometry.prototype.serialize = function () {
  40626. var serializationObject = _super.prototype.serialize.call(this);
  40627. serializationObject.height = this.height;
  40628. serializationObject.diameterTop = this.diameterTop;
  40629. serializationObject.diameterBottom = this.diameterBottom;
  40630. serializationObject.tessellation = this.tessellation;
  40631. return serializationObject;
  40632. };
  40633. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40634. if (scene.getGeometryByID(parsedCylinder.id)) {
  40635. return null; // null since geometry could be something else than a cylinder...
  40636. }
  40637. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40638. if (BABYLON.Tags) {
  40639. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40640. }
  40641. scene.pushGeometry(cylinder, true);
  40642. return cylinder;
  40643. };
  40644. return CylinderGeometry;
  40645. }(_PrimitiveGeometry));
  40646. BABYLON.CylinderGeometry = CylinderGeometry;
  40647. /**
  40648. * Creates a new torus geometry
  40649. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40650. */
  40651. var TorusGeometry = /** @class */ (function (_super) {
  40652. __extends(TorusGeometry, _super);
  40653. /**
  40654. * Creates a new torus geometry
  40655. * @param id defines the unique ID of the geometry
  40656. * @param scene defines the hosting scene
  40657. * @param diameter defines the diameter of the torus
  40658. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40659. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40660. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40661. * @param mesh defines the hosting mesh (can be null)
  40662. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40663. */
  40664. function TorusGeometry(id, scene,
  40665. /**
  40666. * Defines the diameter of the torus
  40667. */
  40668. diameter,
  40669. /**
  40670. * Defines the thickness of the torus (ie. internal diameter)
  40671. */
  40672. thickness,
  40673. /**
  40674. * Defines the tesselation factor to apply to the torus
  40675. */
  40676. tessellation, canBeRegenerated, mesh,
  40677. /**
  40678. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40679. */
  40680. side) {
  40681. if (mesh === void 0) { mesh = null; }
  40682. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40683. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40684. _this.diameter = diameter;
  40685. _this.thickness = thickness;
  40686. _this.tessellation = tessellation;
  40687. _this.side = side;
  40688. return _this;
  40689. }
  40690. /** @hidden */
  40691. TorusGeometry.prototype._regenerateVertexData = function () {
  40692. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40693. };
  40694. TorusGeometry.prototype.copy = function (id) {
  40695. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40696. };
  40697. TorusGeometry.prototype.serialize = function () {
  40698. var serializationObject = _super.prototype.serialize.call(this);
  40699. serializationObject.diameter = this.diameter;
  40700. serializationObject.thickness = this.thickness;
  40701. serializationObject.tessellation = this.tessellation;
  40702. return serializationObject;
  40703. };
  40704. TorusGeometry.Parse = function (parsedTorus, scene) {
  40705. if (scene.getGeometryByID(parsedTorus.id)) {
  40706. return null; // null since geometry could be something else than a torus...
  40707. }
  40708. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40709. if (BABYLON.Tags) {
  40710. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40711. }
  40712. scene.pushGeometry(torus, true);
  40713. return torus;
  40714. };
  40715. return TorusGeometry;
  40716. }(_PrimitiveGeometry));
  40717. BABYLON.TorusGeometry = TorusGeometry;
  40718. /**
  40719. * Creates a new ground geometry
  40720. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40721. */
  40722. var GroundGeometry = /** @class */ (function (_super) {
  40723. __extends(GroundGeometry, _super);
  40724. /**
  40725. * Creates a new ground geometry
  40726. * @param id defines the unique ID of the geometry
  40727. * @param scene defines the hosting scene
  40728. * @param width defines the width of the ground
  40729. * @param height defines the height of the ground
  40730. * @param subdivisions defines the subdivisions to apply to the ground
  40731. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40732. * @param mesh defines the hosting mesh (can be null)
  40733. */
  40734. function GroundGeometry(id, scene,
  40735. /**
  40736. * Defines the width of the ground
  40737. */
  40738. width,
  40739. /**
  40740. * Defines the height of the ground
  40741. */
  40742. height,
  40743. /**
  40744. * Defines the subdivisions to apply to the ground
  40745. */
  40746. subdivisions, canBeRegenerated, mesh) {
  40747. if (mesh === void 0) { mesh = null; }
  40748. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40749. _this.width = width;
  40750. _this.height = height;
  40751. _this.subdivisions = subdivisions;
  40752. return _this;
  40753. }
  40754. /** @hidden */
  40755. GroundGeometry.prototype._regenerateVertexData = function () {
  40756. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40757. };
  40758. GroundGeometry.prototype.copy = function (id) {
  40759. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40760. };
  40761. GroundGeometry.prototype.serialize = function () {
  40762. var serializationObject = _super.prototype.serialize.call(this);
  40763. serializationObject.width = this.width;
  40764. serializationObject.height = this.height;
  40765. serializationObject.subdivisions = this.subdivisions;
  40766. return serializationObject;
  40767. };
  40768. GroundGeometry.Parse = function (parsedGround, scene) {
  40769. if (scene.getGeometryByID(parsedGround.id)) {
  40770. return null; // null since geometry could be something else than a ground...
  40771. }
  40772. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40773. if (BABYLON.Tags) {
  40774. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40775. }
  40776. scene.pushGeometry(ground, true);
  40777. return ground;
  40778. };
  40779. return GroundGeometry;
  40780. }(_PrimitiveGeometry));
  40781. BABYLON.GroundGeometry = GroundGeometry;
  40782. /**
  40783. * Creates a tiled ground geometry
  40784. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40785. */
  40786. var TiledGroundGeometry = /** @class */ (function (_super) {
  40787. __extends(TiledGroundGeometry, _super);
  40788. /**
  40789. * Creates a tiled ground geometry
  40790. * @param id defines the unique ID of the geometry
  40791. * @param scene defines the hosting scene
  40792. * @param xmin defines the minimum value on X axis
  40793. * @param zmin defines the minimum value on Z axis
  40794. * @param xmax defines the maximum value on X axis
  40795. * @param zmax defines the maximum value on Z axis
  40796. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40797. * @param precision defines the precision to use when computing the tiles
  40798. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40799. * @param mesh defines the hosting mesh (can be null)
  40800. */
  40801. function TiledGroundGeometry(id, scene,
  40802. /**
  40803. * Defines the minimum value on X axis
  40804. */
  40805. xmin,
  40806. /**
  40807. * Defines the minimum value on Z axis
  40808. */
  40809. zmin,
  40810. /**
  40811. * Defines the maximum value on X axis
  40812. */
  40813. xmax,
  40814. /**
  40815. * Defines the maximum value on Z axis
  40816. */
  40817. zmax,
  40818. /**
  40819. * Defines the subdivisions to apply to the ground
  40820. */
  40821. subdivisions,
  40822. /**
  40823. * Defines the precision to use when computing the tiles
  40824. */
  40825. precision, canBeRegenerated, mesh) {
  40826. if (mesh === void 0) { mesh = null; }
  40827. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40828. _this.xmin = xmin;
  40829. _this.zmin = zmin;
  40830. _this.xmax = xmax;
  40831. _this.zmax = zmax;
  40832. _this.subdivisions = subdivisions;
  40833. _this.precision = precision;
  40834. return _this;
  40835. }
  40836. /** @hidden */
  40837. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40838. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40839. };
  40840. TiledGroundGeometry.prototype.copy = function (id) {
  40841. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40842. };
  40843. return TiledGroundGeometry;
  40844. }(_PrimitiveGeometry));
  40845. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40846. /**
  40847. * Creates a plane geometry
  40848. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40849. */
  40850. var PlaneGeometry = /** @class */ (function (_super) {
  40851. __extends(PlaneGeometry, _super);
  40852. /**
  40853. * Creates a plane geometry
  40854. * @param id defines the unique ID of the geometry
  40855. * @param scene defines the hosting scene
  40856. * @param size defines the size of the plane (width === height)
  40857. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40858. * @param mesh defines the hosting mesh (can be null)
  40859. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40860. */
  40861. function PlaneGeometry(id, scene,
  40862. /**
  40863. * Defines the size of the plane (width === height)
  40864. */
  40865. size, canBeRegenerated, mesh,
  40866. /**
  40867. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40868. */
  40869. side) {
  40870. if (mesh === void 0) { mesh = null; }
  40871. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40872. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40873. _this.size = size;
  40874. _this.side = side;
  40875. return _this;
  40876. }
  40877. /** @hidden */
  40878. PlaneGeometry.prototype._regenerateVertexData = function () {
  40879. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40880. };
  40881. PlaneGeometry.prototype.copy = function (id) {
  40882. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40883. };
  40884. PlaneGeometry.prototype.serialize = function () {
  40885. var serializationObject = _super.prototype.serialize.call(this);
  40886. serializationObject.size = this.size;
  40887. return serializationObject;
  40888. };
  40889. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40890. if (scene.getGeometryByID(parsedPlane.id)) {
  40891. return null; // null since geometry could be something else than a ground...
  40892. }
  40893. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40894. if (BABYLON.Tags) {
  40895. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40896. }
  40897. scene.pushGeometry(plane, true);
  40898. return plane;
  40899. };
  40900. return PlaneGeometry;
  40901. }(_PrimitiveGeometry));
  40902. BABYLON.PlaneGeometry = PlaneGeometry;
  40903. /**
  40904. * Creates a torus knot geometry
  40905. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40906. */
  40907. var TorusKnotGeometry = /** @class */ (function (_super) {
  40908. __extends(TorusKnotGeometry, _super);
  40909. /**
  40910. * Creates a torus knot geometry
  40911. * @param id defines the unique ID of the geometry
  40912. * @param scene defines the hosting scene
  40913. * @param radius defines the radius of the torus knot
  40914. * @param tube defines the thickness of the torus knot tube
  40915. * @param radialSegments defines the number of radial segments
  40916. * @param tubularSegments defines the number of tubular segments
  40917. * @param p defines the first number of windings
  40918. * @param q defines the second number of windings
  40919. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40920. * @param mesh defines the hosting mesh (can be null)
  40921. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40922. */
  40923. function TorusKnotGeometry(id, scene,
  40924. /**
  40925. * Defines the radius of the torus knot
  40926. */
  40927. radius,
  40928. /**
  40929. * Defines the thickness of the torus knot tube
  40930. */
  40931. tube,
  40932. /**
  40933. * Defines the number of radial segments
  40934. */
  40935. radialSegments,
  40936. /**
  40937. * Defines the number of tubular segments
  40938. */
  40939. tubularSegments,
  40940. /**
  40941. * Defines the first number of windings
  40942. */
  40943. p,
  40944. /**
  40945. * Defines the second number of windings
  40946. */
  40947. q, canBeRegenerated, mesh,
  40948. /**
  40949. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40950. */
  40951. side) {
  40952. if (mesh === void 0) { mesh = null; }
  40953. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40954. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40955. _this.radius = radius;
  40956. _this.tube = tube;
  40957. _this.radialSegments = radialSegments;
  40958. _this.tubularSegments = tubularSegments;
  40959. _this.p = p;
  40960. _this.q = q;
  40961. _this.side = side;
  40962. return _this;
  40963. }
  40964. /** @hidden */
  40965. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40966. 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 });
  40967. };
  40968. TorusKnotGeometry.prototype.copy = function (id) {
  40969. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40970. };
  40971. TorusKnotGeometry.prototype.serialize = function () {
  40972. var serializationObject = _super.prototype.serialize.call(this);
  40973. serializationObject.radius = this.radius;
  40974. serializationObject.tube = this.tube;
  40975. serializationObject.radialSegments = this.radialSegments;
  40976. serializationObject.tubularSegments = this.tubularSegments;
  40977. serializationObject.p = this.p;
  40978. serializationObject.q = this.q;
  40979. return serializationObject;
  40980. };
  40981. ;
  40982. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40983. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40984. return null; // null since geometry could be something else than a ground...
  40985. }
  40986. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40987. if (BABYLON.Tags) {
  40988. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40989. }
  40990. scene.pushGeometry(torusKnot, true);
  40991. return torusKnot;
  40992. };
  40993. return TorusKnotGeometry;
  40994. }(_PrimitiveGeometry));
  40995. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40996. //}
  40997. })(BABYLON || (BABYLON = {}));
  40998. //# sourceMappingURL=babylon.geometry.js.map
  40999. var BABYLON;
  41000. (function (BABYLON) {
  41001. /**
  41002. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41003. */
  41004. var PerformanceMonitor = /** @class */ (function () {
  41005. /**
  41006. * constructor
  41007. * @param frameSampleSize The number of samples required to saturate the sliding window
  41008. */
  41009. function PerformanceMonitor(frameSampleSize) {
  41010. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41011. this._enabled = true;
  41012. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41013. }
  41014. /**
  41015. * Samples current frame
  41016. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41017. */
  41018. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41019. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41020. if (!this._enabled)
  41021. return;
  41022. if (this._lastFrameTimeMs != null) {
  41023. var dt = timeMs - this._lastFrameTimeMs;
  41024. this._rollingFrameTime.add(dt);
  41025. }
  41026. this._lastFrameTimeMs = timeMs;
  41027. };
  41028. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41029. /**
  41030. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41031. */
  41032. get: function () {
  41033. return this._rollingFrameTime.average;
  41034. },
  41035. enumerable: true,
  41036. configurable: true
  41037. });
  41038. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41039. /**
  41040. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41041. */
  41042. get: function () {
  41043. return this._rollingFrameTime.variance;
  41044. },
  41045. enumerable: true,
  41046. configurable: true
  41047. });
  41048. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41049. /**
  41050. * Returns the frame time of the most recent frame
  41051. */
  41052. get: function () {
  41053. return this._rollingFrameTime.history(0);
  41054. },
  41055. enumerable: true,
  41056. configurable: true
  41057. });
  41058. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41059. /**
  41060. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41061. */
  41062. get: function () {
  41063. return 1000.0 / this._rollingFrameTime.average;
  41064. },
  41065. enumerable: true,
  41066. configurable: true
  41067. });
  41068. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41069. /**
  41070. * Returns the average framerate in frames per second using the most recent frame time
  41071. */
  41072. get: function () {
  41073. var history = this._rollingFrameTime.history(0);
  41074. if (history === 0) {
  41075. return 0;
  41076. }
  41077. return 1000.0 / history;
  41078. },
  41079. enumerable: true,
  41080. configurable: true
  41081. });
  41082. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41083. /**
  41084. * Returns true if enough samples have been taken to completely fill the sliding window
  41085. */
  41086. get: function () {
  41087. return this._rollingFrameTime.isSaturated();
  41088. },
  41089. enumerable: true,
  41090. configurable: true
  41091. });
  41092. /**
  41093. * Enables contributions to the sliding window sample set
  41094. */
  41095. PerformanceMonitor.prototype.enable = function () {
  41096. this._enabled = true;
  41097. };
  41098. /**
  41099. * Disables contributions to the sliding window sample set
  41100. * Samples will not be interpolated over the disabled period
  41101. */
  41102. PerformanceMonitor.prototype.disable = function () {
  41103. this._enabled = false;
  41104. //clear last sample to avoid interpolating over the disabled period when next enabled
  41105. this._lastFrameTimeMs = null;
  41106. };
  41107. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41108. /**
  41109. * Returns true if sampling is enabled
  41110. */
  41111. get: function () {
  41112. return this._enabled;
  41113. },
  41114. enumerable: true,
  41115. configurable: true
  41116. });
  41117. /**
  41118. * Resets performance monitor
  41119. */
  41120. PerformanceMonitor.prototype.reset = function () {
  41121. //clear last sample to avoid interpolating over the disabled period when next enabled
  41122. this._lastFrameTimeMs = null;
  41123. //wipe record
  41124. this._rollingFrameTime.reset();
  41125. };
  41126. return PerformanceMonitor;
  41127. }());
  41128. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41129. /**
  41130. * RollingAverage
  41131. *
  41132. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41133. */
  41134. var RollingAverage = /** @class */ (function () {
  41135. /**
  41136. * constructor
  41137. * @param length The number of samples required to saturate the sliding window
  41138. */
  41139. function RollingAverage(length) {
  41140. this._samples = new Array(length);
  41141. this.reset();
  41142. }
  41143. /**
  41144. * Adds a sample to the sample set
  41145. * @param v The sample value
  41146. */
  41147. RollingAverage.prototype.add = function (v) {
  41148. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41149. var delta;
  41150. //we need to check if we've already wrapped round
  41151. if (this.isSaturated()) {
  41152. //remove bottom of stack from mean
  41153. var bottomValue = this._samples[this._pos];
  41154. delta = bottomValue - this.average;
  41155. this.average -= delta / (this._sampleCount - 1);
  41156. this._m2 -= delta * (bottomValue - this.average);
  41157. }
  41158. else {
  41159. this._sampleCount++;
  41160. }
  41161. //add new value to mean
  41162. delta = v - this.average;
  41163. this.average += delta / (this._sampleCount);
  41164. this._m2 += delta * (v - this.average);
  41165. //set the new variance
  41166. this.variance = this._m2 / (this._sampleCount - 1);
  41167. this._samples[this._pos] = v;
  41168. this._pos++;
  41169. this._pos %= this._samples.length; //positive wrap around
  41170. };
  41171. /**
  41172. * Returns previously added values or null if outside of history or outside the sliding window domain
  41173. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41174. * @return Value previously recorded with add() or null if outside of range
  41175. */
  41176. RollingAverage.prototype.history = function (i) {
  41177. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41178. return 0;
  41179. }
  41180. var i0 = this._wrapPosition(this._pos - 1.0);
  41181. return this._samples[this._wrapPosition(i0 - i)];
  41182. };
  41183. /**
  41184. * Returns true if enough samples have been taken to completely fill the sliding window
  41185. * @return true if sample-set saturated
  41186. */
  41187. RollingAverage.prototype.isSaturated = function () {
  41188. return this._sampleCount >= this._samples.length;
  41189. };
  41190. /**
  41191. * Resets the rolling average (equivalent to 0 samples taken so far)
  41192. */
  41193. RollingAverage.prototype.reset = function () {
  41194. this.average = 0;
  41195. this.variance = 0;
  41196. this._sampleCount = 0;
  41197. this._pos = 0;
  41198. this._m2 = 0;
  41199. };
  41200. /**
  41201. * Wraps a value around the sample range boundaries
  41202. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41203. * @return Wrapped position in sample range
  41204. */
  41205. RollingAverage.prototype._wrapPosition = function (i) {
  41206. var max = this._samples.length;
  41207. return ((i % max) + max) % max;
  41208. };
  41209. return RollingAverage;
  41210. }());
  41211. BABYLON.RollingAverage = RollingAverage;
  41212. })(BABYLON || (BABYLON = {}));
  41213. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41214. var BABYLON;
  41215. (function (BABYLON) {
  41216. /**
  41217. * "Static Class" containing the most commonly used helper while dealing with material for
  41218. * rendering purpose.
  41219. *
  41220. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41221. *
  41222. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41223. */
  41224. var MaterialHelper = /** @class */ (function () {
  41225. function MaterialHelper() {
  41226. }
  41227. /**
  41228. * Bind the current view position to an effect.
  41229. * @param effect The effect to be bound
  41230. * @param scene The scene the eyes position is used from
  41231. */
  41232. MaterialHelper.BindEyePosition = function (effect, scene) {
  41233. if (scene._forcedViewPosition) {
  41234. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41235. return;
  41236. }
  41237. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41238. };
  41239. /**
  41240. * Helps preparing the defines values about the UVs in used in the effect.
  41241. * UVs are shared as much as we can accross chanels in the shaders.
  41242. * @param texture The texture we are preparing the UVs for
  41243. * @param defines The defines to update
  41244. * @param key The chanel key "diffuse", "specular"... used in the shader
  41245. */
  41246. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41247. defines._needUVs = true;
  41248. defines[key] = true;
  41249. if (texture.getTextureMatrix().isIdentity(true)) {
  41250. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41251. if (texture.coordinatesIndex === 0) {
  41252. defines["MAINUV1"] = true;
  41253. }
  41254. else {
  41255. defines["MAINUV2"] = true;
  41256. }
  41257. }
  41258. else {
  41259. defines[key + "DIRECTUV"] = 0;
  41260. }
  41261. };
  41262. /**
  41263. * Binds a texture matrix value to its corrsponding uniform
  41264. * @param texture The texture to bind the matrix for
  41265. * @param uniformBuffer The uniform buffer receivin the data
  41266. * @param key The chanel key "diffuse", "specular"... used in the shader
  41267. */
  41268. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41269. var matrix = texture.getTextureMatrix();
  41270. if (!matrix.isIdentity(true)) {
  41271. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41272. }
  41273. };
  41274. /**
  41275. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41276. * @param mesh defines the current mesh
  41277. * @param scene defines the current scene
  41278. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41279. * @param pointsCloud defines if point cloud rendering has to be turned on
  41280. * @param fogEnabled defines if fog has to be turned on
  41281. * @param alphaTest defines if alpha testing has to be turned on
  41282. * @param defines defines the current list of defines
  41283. */
  41284. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41285. if (defines._areMiscDirty) {
  41286. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41287. defines["POINTSIZE"] = pointsCloud;
  41288. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41289. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41290. defines["ALPHATEST"] = alphaTest;
  41291. }
  41292. };
  41293. /**
  41294. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41295. * @param scene defines the current scene
  41296. * @param engine defines the current engine
  41297. * @param defines specifies the list of active defines
  41298. * @param useInstances defines if instances have to be turned on
  41299. * @param useClipPlane defines if clip plane have to be turned on
  41300. */
  41301. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41302. if (useClipPlane === void 0) { useClipPlane = null; }
  41303. var changed = false;
  41304. var useClipPlane1 = false;
  41305. var useClipPlane2 = false;
  41306. var useClipPlane3 = false;
  41307. var useClipPlane4 = false;
  41308. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41309. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41310. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41311. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41312. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41313. defines["CLIPPLANE"] = useClipPlane1;
  41314. changed = true;
  41315. }
  41316. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41317. defines["CLIPPLANE2"] = useClipPlane2;
  41318. changed = true;
  41319. }
  41320. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41321. defines["CLIPPLANE3"] = useClipPlane3;
  41322. changed = true;
  41323. }
  41324. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41325. defines["CLIPPLANE4"] = useClipPlane4;
  41326. changed = true;
  41327. }
  41328. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41329. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41330. changed = true;
  41331. }
  41332. if (defines["INSTANCES"] !== useInstances) {
  41333. defines["INSTANCES"] = useInstances;
  41334. changed = true;
  41335. }
  41336. if (changed) {
  41337. defines.markAsUnprocessed();
  41338. }
  41339. };
  41340. /**
  41341. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41342. * @param mesh The mesh containing the geometry data we will draw
  41343. * @param defines The defines to update
  41344. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41345. * @param useBones Precise whether bones should be used or not (override mesh info)
  41346. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41347. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41348. * @returns false if defines are considered not dirty and have not been checked
  41349. */
  41350. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41351. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41352. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41353. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41354. return false;
  41355. }
  41356. defines._normals = defines._needNormals;
  41357. defines._uvs = defines._needUVs;
  41358. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41359. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41360. defines["TANGENT"] = true;
  41361. }
  41362. if (defines._needUVs) {
  41363. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41364. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41365. }
  41366. else {
  41367. defines["UV1"] = false;
  41368. defines["UV2"] = false;
  41369. }
  41370. if (useVertexColor) {
  41371. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41372. defines["VERTEXCOLOR"] = hasVertexColors;
  41373. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41374. }
  41375. if (useBones) {
  41376. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41377. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41378. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41379. }
  41380. else {
  41381. defines["NUM_BONE_INFLUENCERS"] = 0;
  41382. defines["BonesPerMesh"] = 0;
  41383. }
  41384. }
  41385. if (useMorphTargets) {
  41386. var manager = mesh.morphTargetManager;
  41387. if (manager) {
  41388. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41389. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41390. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41391. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41392. }
  41393. else {
  41394. defines["MORPHTARGETS_TANGENT"] = false;
  41395. defines["MORPHTARGETS_NORMAL"] = false;
  41396. defines["MORPHTARGETS"] = false;
  41397. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41398. }
  41399. }
  41400. return true;
  41401. };
  41402. /**
  41403. * Prepares the defines related to the light information passed in parameter
  41404. * @param scene The scene we are intending to draw
  41405. * @param mesh The mesh the effect is compiling for
  41406. * @param defines The defines to update
  41407. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41408. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41409. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41410. * @returns true if normals will be required for the rest of the effect
  41411. */
  41412. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41413. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41414. if (disableLighting === void 0) { disableLighting = false; }
  41415. if (!defines._areLightsDirty) {
  41416. return defines._needNormals;
  41417. }
  41418. var lightIndex = 0;
  41419. var needNormals = false;
  41420. var needRebuild = false;
  41421. var lightmapMode = false;
  41422. var shadowEnabled = false;
  41423. var specularEnabled = false;
  41424. if (scene.lightsEnabled && !disableLighting) {
  41425. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41426. var light = _a[_i];
  41427. needNormals = true;
  41428. if (defines["LIGHT" + lightIndex] === undefined) {
  41429. needRebuild = true;
  41430. }
  41431. defines["LIGHT" + lightIndex] = true;
  41432. defines["SPOTLIGHT" + lightIndex] = false;
  41433. defines["HEMILIGHT" + lightIndex] = false;
  41434. defines["POINTLIGHT" + lightIndex] = false;
  41435. defines["DIRLIGHT" + lightIndex] = false;
  41436. light.prepareLightSpecificDefines(defines, lightIndex);
  41437. // FallOff.
  41438. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41439. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41440. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41441. switch (light.falloffType) {
  41442. case BABYLON.Light.FALLOFF_GLTF:
  41443. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41444. break;
  41445. case BABYLON.Light.FALLOFF_PHYSICAL:
  41446. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41447. break;
  41448. case BABYLON.Light.FALLOFF_STANDARD:
  41449. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41450. break;
  41451. }
  41452. // Specular
  41453. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41454. specularEnabled = true;
  41455. }
  41456. // Shadows
  41457. defines["SHADOW" + lightIndex] = false;
  41458. defines["SHADOWPCF" + lightIndex] = false;
  41459. defines["SHADOWPCSS" + lightIndex] = false;
  41460. defines["SHADOWPOISSON" + lightIndex] = false;
  41461. defines["SHADOWESM" + lightIndex] = false;
  41462. defines["SHADOWCUBE" + lightIndex] = false;
  41463. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41464. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41465. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41466. var shadowGenerator = light.getShadowGenerator();
  41467. if (shadowGenerator) {
  41468. var shadowMap = shadowGenerator.getShadowMap();
  41469. if (shadowMap) {
  41470. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41471. shadowEnabled = true;
  41472. shadowGenerator.prepareDefines(defines, lightIndex);
  41473. }
  41474. }
  41475. }
  41476. }
  41477. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41478. lightmapMode = true;
  41479. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41480. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41481. }
  41482. else {
  41483. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41484. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41485. }
  41486. lightIndex++;
  41487. if (lightIndex === maxSimultaneousLights)
  41488. break;
  41489. }
  41490. }
  41491. defines["SPECULARTERM"] = specularEnabled;
  41492. defines["SHADOWS"] = shadowEnabled;
  41493. // Resetting all other lights if any
  41494. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41495. if (defines["LIGHT" + index] !== undefined) {
  41496. defines["LIGHT" + index] = false;
  41497. defines["HEMILIGHT" + lightIndex] = false;
  41498. defines["POINTLIGHT" + lightIndex] = false;
  41499. defines["DIRLIGHT" + lightIndex] = false;
  41500. defines["SPOTLIGHT" + lightIndex] = false;
  41501. defines["SHADOW" + lightIndex] = false;
  41502. }
  41503. }
  41504. var caps = scene.getEngine().getCaps();
  41505. if (defines["SHADOWFLOAT"] === undefined) {
  41506. needRebuild = true;
  41507. }
  41508. defines["SHADOWFLOAT"] = shadowEnabled &&
  41509. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41510. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41511. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41512. if (needRebuild) {
  41513. defines.rebuild();
  41514. }
  41515. return needNormals;
  41516. };
  41517. /**
  41518. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41519. * that won t be acctive due to defines being turned off.
  41520. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41521. * @param samplersList The samplers list
  41522. * @param defines The defines helping in the list generation
  41523. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41524. */
  41525. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41526. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41527. var uniformsList;
  41528. var uniformBuffersList = null;
  41529. if (uniformsListOrOptions.uniformsNames) {
  41530. var options = uniformsListOrOptions;
  41531. uniformsList = options.uniformsNames;
  41532. uniformBuffersList = options.uniformBuffersNames;
  41533. samplersList = options.samplers;
  41534. defines = options.defines;
  41535. maxSimultaneousLights = options.maxSimultaneousLights;
  41536. }
  41537. else {
  41538. uniformsList = uniformsListOrOptions;
  41539. if (!samplersList) {
  41540. samplersList = [];
  41541. }
  41542. }
  41543. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41544. if (!defines["LIGHT" + lightIndex]) {
  41545. break;
  41546. }
  41547. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41548. if (uniformBuffersList) {
  41549. uniformBuffersList.push("Light" + lightIndex);
  41550. }
  41551. samplersList.push("shadowSampler" + lightIndex);
  41552. samplersList.push("depthSampler" + lightIndex);
  41553. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41554. samplersList.push("projectionLightSampler" + lightIndex);
  41555. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41556. }
  41557. }
  41558. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41559. uniformsList.push("morphTargetInfluences");
  41560. }
  41561. };
  41562. /**
  41563. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41564. * @param defines The defines to update while falling back
  41565. * @param fallbacks The authorized effect fallbacks
  41566. * @param maxSimultaneousLights The maximum number of lights allowed
  41567. * @param rank the current rank of the Effect
  41568. * @returns The newly affected rank
  41569. */
  41570. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41571. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41572. if (rank === void 0) { rank = 0; }
  41573. var lightFallbackRank = 0;
  41574. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41575. if (!defines["LIGHT" + lightIndex]) {
  41576. break;
  41577. }
  41578. if (lightIndex > 0) {
  41579. lightFallbackRank = rank + lightIndex;
  41580. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41581. }
  41582. if (!defines["SHADOWS"]) {
  41583. if (defines["SHADOW" + lightIndex]) {
  41584. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41585. }
  41586. if (defines["SHADOWPCF" + lightIndex]) {
  41587. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41588. }
  41589. if (defines["SHADOWPCSS" + lightIndex]) {
  41590. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41591. }
  41592. if (defines["SHADOWPOISSON" + lightIndex]) {
  41593. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41594. }
  41595. if (defines["SHADOWESM" + lightIndex]) {
  41596. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41597. }
  41598. }
  41599. }
  41600. return lightFallbackRank++;
  41601. };
  41602. /**
  41603. * Prepares the list of attributes required for morph targets according to the effect defines.
  41604. * @param attribs The current list of supported attribs
  41605. * @param mesh The mesh to prepare the morph targets attributes for
  41606. * @param defines The current Defines of the effect
  41607. */
  41608. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41609. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41610. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41611. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41612. var manager = mesh.morphTargetManager;
  41613. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41614. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41615. for (var index = 0; index < influencers; index++) {
  41616. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41617. if (normal) {
  41618. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41619. }
  41620. if (tangent) {
  41621. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41622. }
  41623. if (attribs.length > maxAttributesCount) {
  41624. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41625. }
  41626. }
  41627. }
  41628. };
  41629. /**
  41630. * Prepares the list of attributes required for bones according to the effect defines.
  41631. * @param attribs The current list of supported attribs
  41632. * @param mesh The mesh to prepare the bones attributes for
  41633. * @param defines The current Defines of the effect
  41634. * @param fallbacks The current efffect fallback strategy
  41635. */
  41636. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41637. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41638. fallbacks.addCPUSkinningFallback(0, mesh);
  41639. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41640. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41641. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41642. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41643. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41644. }
  41645. }
  41646. };
  41647. /**
  41648. * Prepares the list of attributes required for instances according to the effect defines.
  41649. * @param attribs The current list of supported attribs
  41650. * @param defines The current Defines of the effect
  41651. */
  41652. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41653. if (defines["INSTANCES"]) {
  41654. attribs.push("world0");
  41655. attribs.push("world1");
  41656. attribs.push("world2");
  41657. attribs.push("world3");
  41658. }
  41659. };
  41660. /**
  41661. * Binds the light shadow information to the effect for the given mesh.
  41662. * @param light The light containing the generator
  41663. * @param scene The scene the lights belongs to
  41664. * @param mesh The mesh we are binding the information to render
  41665. * @param lightIndex The light index in the effect used to render the mesh
  41666. * @param effect The effect we are binding the data to
  41667. */
  41668. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41669. if (light.shadowEnabled && mesh.receiveShadows) {
  41670. var shadowGenerator = light.getShadowGenerator();
  41671. if (shadowGenerator) {
  41672. shadowGenerator.bindShadowLight(lightIndex, effect);
  41673. }
  41674. }
  41675. };
  41676. /**
  41677. * Binds the light information to the effect.
  41678. * @param light The light containing the generator
  41679. * @param effect The effect we are binding the data to
  41680. * @param lightIndex The light index in the effect used to render
  41681. */
  41682. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41683. light.transferToEffect(effect, lightIndex + "");
  41684. };
  41685. /**
  41686. * Binds the lights information from the scene to the effect for the given mesh.
  41687. * @param scene The scene the lights belongs to
  41688. * @param mesh The mesh we are binding the information to render
  41689. * @param effect The effect we are binding the data to
  41690. * @param defines The generated defines for the effect
  41691. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41692. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41693. */
  41694. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41695. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41696. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41697. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41698. for (var i = 0; i < len; i++) {
  41699. var light = mesh._lightSources[i];
  41700. var iAsString = i.toString();
  41701. var scaledIntensity = light.getScaledIntensity();
  41702. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41703. MaterialHelper.BindLightProperties(light, effect, i);
  41704. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41705. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41706. if (defines["SPECULARTERM"]) {
  41707. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41708. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41709. }
  41710. // Shadows
  41711. if (scene.shadowsEnabled) {
  41712. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41713. }
  41714. light._uniformBuffer.update();
  41715. }
  41716. };
  41717. /**
  41718. * Binds the fog information from the scene to the effect for the given mesh.
  41719. * @param scene The scene the lights belongs to
  41720. * @param mesh The mesh we are binding the information to render
  41721. * @param effect The effect we are binding the data to
  41722. * @param linearSpace Defines if the fog effect is applied in linear space
  41723. */
  41724. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  41725. if (linearSpace === void 0) { linearSpace = false; }
  41726. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41727. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41728. // Convert fog color to linear space if used in a linear space computed shader.
  41729. if (linearSpace) {
  41730. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  41731. effect.setColor3("vFogColor", this._tempFogColor);
  41732. }
  41733. else {
  41734. effect.setColor3("vFogColor", scene.fogColor);
  41735. }
  41736. }
  41737. };
  41738. /**
  41739. * Binds the bones information from the mesh to the effect.
  41740. * @param mesh The mesh we are binding the information to render
  41741. * @param effect The effect we are binding the data to
  41742. */
  41743. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41744. if (!effect || !mesh) {
  41745. return;
  41746. }
  41747. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41748. mesh.computeBonesUsingShaders = false;
  41749. }
  41750. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41751. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41752. if (matrices) {
  41753. effect.setMatrices("mBones", matrices);
  41754. }
  41755. }
  41756. };
  41757. /**
  41758. * Binds the morph targets information from the mesh to the effect.
  41759. * @param abstractMesh The mesh we are binding the information to render
  41760. * @param effect The effect we are binding the data to
  41761. */
  41762. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41763. var manager = abstractMesh.morphTargetManager;
  41764. if (!abstractMesh || !manager) {
  41765. return;
  41766. }
  41767. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41768. };
  41769. /**
  41770. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41771. * @param defines The generated defines used in the effect
  41772. * @param effect The effect we are binding the data to
  41773. * @param scene The scene we are willing to render with logarithmic scale for
  41774. */
  41775. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41776. if (defines["LOGARITHMICDEPTH"]) {
  41777. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41778. }
  41779. };
  41780. /**
  41781. * Binds the clip plane information from the scene to the effect.
  41782. * @param scene The scene the clip plane information are extracted from
  41783. * @param effect The effect we are binding the data to
  41784. */
  41785. MaterialHelper.BindClipPlane = function (effect, scene) {
  41786. if (scene.clipPlane) {
  41787. var clipPlane = scene.clipPlane;
  41788. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41789. }
  41790. if (scene.clipPlane2) {
  41791. var clipPlane = scene.clipPlane2;
  41792. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41793. }
  41794. if (scene.clipPlane3) {
  41795. var clipPlane = scene.clipPlane3;
  41796. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41797. }
  41798. if (scene.clipPlane4) {
  41799. var clipPlane = scene.clipPlane4;
  41800. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41801. }
  41802. };
  41803. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  41804. return MaterialHelper;
  41805. }());
  41806. BABYLON.MaterialHelper = MaterialHelper;
  41807. })(BABYLON || (BABYLON = {}));
  41808. //# sourceMappingURL=babylon.materialHelper.js.map
  41809. var BABYLON;
  41810. (function (BABYLON) {
  41811. var PushMaterial = /** @class */ (function (_super) {
  41812. __extends(PushMaterial, _super);
  41813. function PushMaterial(name, scene) {
  41814. var _this = _super.call(this, name, scene) || this;
  41815. _this._normalMatrix = new BABYLON.Matrix();
  41816. _this.storeEffectOnSubMeshes = true;
  41817. return _this;
  41818. }
  41819. PushMaterial.prototype.getEffect = function () {
  41820. return this._activeEffect;
  41821. };
  41822. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41823. if (!mesh) {
  41824. return false;
  41825. }
  41826. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41827. return true;
  41828. }
  41829. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41830. };
  41831. /**
  41832. * Binds the given world matrix to the active effect
  41833. *
  41834. * @param world the matrix to bind
  41835. */
  41836. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41837. this._activeEffect.setMatrix("world", world);
  41838. };
  41839. /**
  41840. * Binds the given normal matrix to the active effect
  41841. *
  41842. * @param normalMatrix the matrix to bind
  41843. */
  41844. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41845. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41846. };
  41847. PushMaterial.prototype.bind = function (world, mesh) {
  41848. if (!mesh) {
  41849. return;
  41850. }
  41851. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41852. };
  41853. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41854. if (effect === void 0) { effect = null; }
  41855. _super.prototype._afterBind.call(this, mesh);
  41856. this.getScene()._cachedEffect = effect;
  41857. };
  41858. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41859. if (visibility === void 0) { visibility = 1; }
  41860. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41861. };
  41862. return PushMaterial;
  41863. }(BABYLON.Material));
  41864. BABYLON.PushMaterial = PushMaterial;
  41865. })(BABYLON || (BABYLON = {}));
  41866. //# sourceMappingURL=babylon.pushMaterial.js.map
  41867. var BABYLON;
  41868. (function (BABYLON) {
  41869. /** @hidden */
  41870. var StandardMaterialDefines = /** @class */ (function (_super) {
  41871. __extends(StandardMaterialDefines, _super);
  41872. function StandardMaterialDefines() {
  41873. var _this = _super.call(this) || this;
  41874. _this.MAINUV1 = false;
  41875. _this.MAINUV2 = false;
  41876. _this.DIFFUSE = false;
  41877. _this.DIFFUSEDIRECTUV = 0;
  41878. _this.AMBIENT = false;
  41879. _this.AMBIENTDIRECTUV = 0;
  41880. _this.OPACITY = false;
  41881. _this.OPACITYDIRECTUV = 0;
  41882. _this.OPACITYRGB = false;
  41883. _this.REFLECTION = false;
  41884. _this.EMISSIVE = false;
  41885. _this.EMISSIVEDIRECTUV = 0;
  41886. _this.SPECULAR = false;
  41887. _this.SPECULARDIRECTUV = 0;
  41888. _this.BUMP = false;
  41889. _this.BUMPDIRECTUV = 0;
  41890. _this.PARALLAX = false;
  41891. _this.PARALLAXOCCLUSION = false;
  41892. _this.SPECULAROVERALPHA = false;
  41893. _this.CLIPPLANE = false;
  41894. _this.CLIPPLANE2 = false;
  41895. _this.CLIPPLANE3 = false;
  41896. _this.CLIPPLANE4 = false;
  41897. _this.ALPHATEST = false;
  41898. _this.DEPTHPREPASS = false;
  41899. _this.ALPHAFROMDIFFUSE = false;
  41900. _this.POINTSIZE = false;
  41901. _this.FOG = false;
  41902. _this.SPECULARTERM = false;
  41903. _this.DIFFUSEFRESNEL = false;
  41904. _this.OPACITYFRESNEL = false;
  41905. _this.REFLECTIONFRESNEL = false;
  41906. _this.REFRACTIONFRESNEL = false;
  41907. _this.EMISSIVEFRESNEL = false;
  41908. _this.FRESNEL = false;
  41909. _this.NORMAL = false;
  41910. _this.UV1 = false;
  41911. _this.UV2 = false;
  41912. _this.VERTEXCOLOR = false;
  41913. _this.VERTEXALPHA = false;
  41914. _this.NUM_BONE_INFLUENCERS = 0;
  41915. _this.BonesPerMesh = 0;
  41916. _this.INSTANCES = false;
  41917. _this.GLOSSINESS = false;
  41918. _this.ROUGHNESS = false;
  41919. _this.EMISSIVEASILLUMINATION = false;
  41920. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41921. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41922. _this.LIGHTMAP = false;
  41923. _this.LIGHTMAPDIRECTUV = 0;
  41924. _this.OBJECTSPACE_NORMALMAP = false;
  41925. _this.USELIGHTMAPASSHADOWMAP = false;
  41926. _this.REFLECTIONMAP_3D = false;
  41927. _this.REFLECTIONMAP_SPHERICAL = false;
  41928. _this.REFLECTIONMAP_PLANAR = false;
  41929. _this.REFLECTIONMAP_CUBIC = false;
  41930. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41931. _this.REFLECTIONMAP_PROJECTION = false;
  41932. _this.REFLECTIONMAP_SKYBOX = false;
  41933. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41934. _this.REFLECTIONMAP_EXPLICIT = false;
  41935. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41936. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41937. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41938. _this.INVERTCUBICMAP = false;
  41939. _this.LOGARITHMICDEPTH = false;
  41940. _this.REFRACTION = false;
  41941. _this.REFRACTIONMAP_3D = false;
  41942. _this.REFLECTIONOVERALPHA = false;
  41943. _this.TWOSIDEDLIGHTING = false;
  41944. _this.SHADOWFLOAT = false;
  41945. _this.MORPHTARGETS = false;
  41946. _this.MORPHTARGETS_NORMAL = false;
  41947. _this.MORPHTARGETS_TANGENT = false;
  41948. _this.NUM_MORPH_INFLUENCERS = 0;
  41949. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41950. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41951. _this.IMAGEPROCESSING = false;
  41952. _this.VIGNETTE = false;
  41953. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41954. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41955. _this.TONEMAPPING = false;
  41956. _this.TONEMAPPING_ACES = false;
  41957. _this.CONTRAST = false;
  41958. _this.COLORCURVES = false;
  41959. _this.COLORGRADING = false;
  41960. _this.COLORGRADING3D = false;
  41961. _this.SAMPLER3DGREENDEPTH = false;
  41962. _this.SAMPLER3DBGRMAP = false;
  41963. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41964. /**
  41965. * If the reflection texture on this material is in linear color space
  41966. * @hidden
  41967. */
  41968. _this.IS_REFLECTION_LINEAR = false;
  41969. /**
  41970. * If the refraction texture on this material is in linear color space
  41971. * @hidden
  41972. */
  41973. _this.IS_REFRACTION_LINEAR = false;
  41974. _this.EXPOSURE = false;
  41975. _this.rebuild();
  41976. return _this;
  41977. }
  41978. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41979. var modes = [
  41980. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41981. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41982. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41983. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41984. ];
  41985. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41986. var mode = modes_1[_i];
  41987. this[mode] = (mode === modeToEnable);
  41988. }
  41989. };
  41990. return StandardMaterialDefines;
  41991. }(BABYLON.MaterialDefines));
  41992. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41993. var StandardMaterial = /** @class */ (function (_super) {
  41994. __extends(StandardMaterial, _super);
  41995. function StandardMaterial(name, scene) {
  41996. var _this = _super.call(this, name, scene) || this;
  41997. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41998. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41999. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42000. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42001. _this.specularPower = 64;
  42002. _this._useAlphaFromDiffuseTexture = false;
  42003. _this._useEmissiveAsIllumination = false;
  42004. _this._linkEmissiveWithDiffuse = false;
  42005. _this._useSpecularOverAlpha = false;
  42006. _this._useReflectionOverAlpha = false;
  42007. _this._disableLighting = false;
  42008. _this._useObjectSpaceNormalMap = false;
  42009. _this._useParallax = false;
  42010. _this._useParallaxOcclusion = false;
  42011. _this.parallaxScaleBias = 0.05;
  42012. _this._roughness = 0;
  42013. _this.indexOfRefraction = 0.98;
  42014. _this.invertRefractionY = true;
  42015. /**
  42016. * Defines the alpha limits in alpha test mode
  42017. */
  42018. _this.alphaCutOff = 0.4;
  42019. _this._useLightmapAsShadowmap = false;
  42020. _this._useReflectionFresnelFromSpecular = false;
  42021. _this._useGlossinessFromSpecularMapAlpha = false;
  42022. _this._maxSimultaneousLights = 4;
  42023. /**
  42024. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42025. */
  42026. _this._invertNormalMapX = false;
  42027. /**
  42028. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42029. */
  42030. _this._invertNormalMapY = false;
  42031. /**
  42032. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42033. */
  42034. _this._twoSidedLighting = false;
  42035. _this._renderTargets = new BABYLON.SmartArray(16);
  42036. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42037. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42038. // Setup the default processing configuration to the scene.
  42039. _this._attachImageProcessingConfiguration(null);
  42040. _this.getRenderTargetTextures = function () {
  42041. _this._renderTargets.reset();
  42042. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42043. _this._renderTargets.push(_this._reflectionTexture);
  42044. }
  42045. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42046. _this._renderTargets.push(_this._refractionTexture);
  42047. }
  42048. return _this._renderTargets;
  42049. };
  42050. return _this;
  42051. }
  42052. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42053. /**
  42054. * Gets the image processing configuration used either in this material.
  42055. */
  42056. get: function () {
  42057. return this._imageProcessingConfiguration;
  42058. },
  42059. /**
  42060. * Sets the Default image processing configuration used either in the this material.
  42061. *
  42062. * If sets to null, the scene one is in use.
  42063. */
  42064. set: function (value) {
  42065. this._attachImageProcessingConfiguration(value);
  42066. // Ensure the effect will be rebuilt.
  42067. this._markAllSubMeshesAsTexturesDirty();
  42068. },
  42069. enumerable: true,
  42070. configurable: true
  42071. });
  42072. /**
  42073. * Attaches a new image processing configuration to the Standard Material.
  42074. * @param configuration
  42075. */
  42076. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42077. var _this = this;
  42078. if (configuration === this._imageProcessingConfiguration) {
  42079. return;
  42080. }
  42081. // Detaches observer.
  42082. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42083. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42084. }
  42085. // Pick the scene configuration if needed.
  42086. if (!configuration) {
  42087. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42088. }
  42089. else {
  42090. this._imageProcessingConfiguration = configuration;
  42091. }
  42092. // Attaches observer.
  42093. if (this._imageProcessingConfiguration) {
  42094. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42095. _this._markAllSubMeshesAsImageProcessingDirty();
  42096. });
  42097. }
  42098. };
  42099. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42100. /**
  42101. * Gets wether the color curves effect is enabled.
  42102. */
  42103. get: function () {
  42104. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42105. },
  42106. /**
  42107. * Sets wether the color curves effect is enabled.
  42108. */
  42109. set: function (value) {
  42110. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42111. },
  42112. enumerable: true,
  42113. configurable: true
  42114. });
  42115. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42116. /**
  42117. * Gets wether the color grading effect is enabled.
  42118. */
  42119. get: function () {
  42120. return this.imageProcessingConfiguration.colorGradingEnabled;
  42121. },
  42122. /**
  42123. * Gets wether the color grading effect is enabled.
  42124. */
  42125. set: function (value) {
  42126. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42127. },
  42128. enumerable: true,
  42129. configurable: true
  42130. });
  42131. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42132. /**
  42133. * Gets wether tonemapping is enabled or not.
  42134. */
  42135. get: function () {
  42136. return this._imageProcessingConfiguration.toneMappingEnabled;
  42137. },
  42138. /**
  42139. * Sets wether tonemapping is enabled or not
  42140. */
  42141. set: function (value) {
  42142. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42143. },
  42144. enumerable: true,
  42145. configurable: true
  42146. });
  42147. ;
  42148. ;
  42149. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42150. /**
  42151. * The camera exposure used on this material.
  42152. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42153. * This corresponds to a photographic exposure.
  42154. */
  42155. get: function () {
  42156. return this._imageProcessingConfiguration.exposure;
  42157. },
  42158. /**
  42159. * The camera exposure used on this material.
  42160. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42161. * This corresponds to a photographic exposure.
  42162. */
  42163. set: function (value) {
  42164. this._imageProcessingConfiguration.exposure = value;
  42165. },
  42166. enumerable: true,
  42167. configurable: true
  42168. });
  42169. ;
  42170. ;
  42171. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42172. /**
  42173. * Gets The camera contrast used on this material.
  42174. */
  42175. get: function () {
  42176. return this._imageProcessingConfiguration.contrast;
  42177. },
  42178. /**
  42179. * Sets The camera contrast used on this material.
  42180. */
  42181. set: function (value) {
  42182. this._imageProcessingConfiguration.contrast = value;
  42183. },
  42184. enumerable: true,
  42185. configurable: true
  42186. });
  42187. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42188. /**
  42189. * Gets the Color Grading 2D Lookup Texture.
  42190. */
  42191. get: function () {
  42192. return this._imageProcessingConfiguration.colorGradingTexture;
  42193. },
  42194. /**
  42195. * Sets the Color Grading 2D Lookup Texture.
  42196. */
  42197. set: function (value) {
  42198. this._imageProcessingConfiguration.colorGradingTexture = value;
  42199. },
  42200. enumerable: true,
  42201. configurable: true
  42202. });
  42203. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42204. /**
  42205. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42206. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42207. * 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;
  42208. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42209. */
  42210. get: function () {
  42211. return this._imageProcessingConfiguration.colorCurves;
  42212. },
  42213. /**
  42214. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42215. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42216. * 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;
  42217. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42218. */
  42219. set: function (value) {
  42220. this._imageProcessingConfiguration.colorCurves = value;
  42221. },
  42222. enumerable: true,
  42223. configurable: true
  42224. });
  42225. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  42226. /**
  42227. * Gets a boolean indicating that current material needs to register RTT
  42228. */
  42229. get: function () {
  42230. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42231. return true;
  42232. }
  42233. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42234. return true;
  42235. }
  42236. return false;
  42237. },
  42238. enumerable: true,
  42239. configurable: true
  42240. });
  42241. StandardMaterial.prototype.getClassName = function () {
  42242. return "StandardMaterial";
  42243. };
  42244. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42245. get: function () {
  42246. return this._useLogarithmicDepth;
  42247. },
  42248. set: function (value) {
  42249. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42250. this._markAllSubMeshesAsMiscDirty();
  42251. },
  42252. enumerable: true,
  42253. configurable: true
  42254. });
  42255. StandardMaterial.prototype.needAlphaBlending = function () {
  42256. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42257. };
  42258. StandardMaterial.prototype.needAlphaTesting = function () {
  42259. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42260. };
  42261. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42262. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42263. };
  42264. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42265. return this._diffuseTexture;
  42266. };
  42267. /**
  42268. * Child classes can use it to update shaders
  42269. */
  42270. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42271. if (useInstances === void 0) { useInstances = false; }
  42272. if (subMesh.effect && this.isFrozen) {
  42273. if (this._wasPreviouslyReady) {
  42274. return true;
  42275. }
  42276. }
  42277. if (!subMesh._materialDefines) {
  42278. subMesh._materialDefines = new StandardMaterialDefines();
  42279. }
  42280. var scene = this.getScene();
  42281. var defines = subMesh._materialDefines;
  42282. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42283. if (defines._renderId === scene.getRenderId()) {
  42284. return true;
  42285. }
  42286. }
  42287. var engine = scene.getEngine();
  42288. // Lights
  42289. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42290. // Textures
  42291. if (defines._areTexturesDirty) {
  42292. defines._needUVs = false;
  42293. defines.MAINUV1 = false;
  42294. defines.MAINUV2 = false;
  42295. if (scene.texturesEnabled) {
  42296. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42297. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42298. return false;
  42299. }
  42300. else {
  42301. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42302. }
  42303. }
  42304. else {
  42305. defines.DIFFUSE = false;
  42306. }
  42307. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42308. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42309. return false;
  42310. }
  42311. else {
  42312. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42313. }
  42314. }
  42315. else {
  42316. defines.AMBIENT = false;
  42317. }
  42318. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42319. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42320. return false;
  42321. }
  42322. else {
  42323. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42324. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42325. }
  42326. }
  42327. else {
  42328. defines.OPACITY = false;
  42329. }
  42330. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42331. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42332. return false;
  42333. }
  42334. else {
  42335. defines._needNormals = true;
  42336. defines.REFLECTION = true;
  42337. defines.ROUGHNESS = (this._roughness > 0);
  42338. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42339. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42340. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42341. switch (this._reflectionTexture.coordinatesMode) {
  42342. case BABYLON.Texture.EXPLICIT_MODE:
  42343. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42344. break;
  42345. case BABYLON.Texture.PLANAR_MODE:
  42346. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42347. break;
  42348. case BABYLON.Texture.PROJECTION_MODE:
  42349. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42350. break;
  42351. case BABYLON.Texture.SKYBOX_MODE:
  42352. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42353. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42354. break;
  42355. case BABYLON.Texture.SPHERICAL_MODE:
  42356. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42357. break;
  42358. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42359. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42360. break;
  42361. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42362. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42363. break;
  42364. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42365. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42366. break;
  42367. case BABYLON.Texture.CUBIC_MODE:
  42368. case BABYLON.Texture.INVCUBIC_MODE:
  42369. default:
  42370. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42371. break;
  42372. }
  42373. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42374. }
  42375. }
  42376. else {
  42377. defines.REFLECTION = false;
  42378. }
  42379. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42380. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42381. return false;
  42382. }
  42383. else {
  42384. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42385. }
  42386. }
  42387. else {
  42388. defines.EMISSIVE = false;
  42389. }
  42390. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42391. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42392. return false;
  42393. }
  42394. else {
  42395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42396. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42397. }
  42398. }
  42399. else {
  42400. defines.LIGHTMAP = false;
  42401. }
  42402. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42403. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42404. return false;
  42405. }
  42406. else {
  42407. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42408. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42409. }
  42410. }
  42411. else {
  42412. defines.SPECULAR = false;
  42413. }
  42414. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42415. // Bump texure can not be not blocking.
  42416. if (!this._bumpTexture.isReady()) {
  42417. return false;
  42418. }
  42419. else {
  42420. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42421. defines.PARALLAX = this._useParallax;
  42422. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42423. }
  42424. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42425. }
  42426. else {
  42427. defines.BUMP = false;
  42428. }
  42429. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42430. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42431. return false;
  42432. }
  42433. else {
  42434. defines._needUVs = true;
  42435. defines.REFRACTION = true;
  42436. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42437. }
  42438. }
  42439. else {
  42440. defines.REFRACTION = false;
  42441. }
  42442. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42443. }
  42444. else {
  42445. defines.DIFFUSE = false;
  42446. defines.AMBIENT = false;
  42447. defines.OPACITY = false;
  42448. defines.REFLECTION = false;
  42449. defines.EMISSIVE = false;
  42450. defines.LIGHTMAP = false;
  42451. defines.BUMP = false;
  42452. defines.REFRACTION = false;
  42453. }
  42454. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42455. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42456. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42457. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42458. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42459. }
  42460. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42461. if (!this._imageProcessingConfiguration.isReady()) {
  42462. return false;
  42463. }
  42464. this._imageProcessingConfiguration.prepareDefines(defines);
  42465. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42466. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42467. }
  42468. if (defines._areFresnelDirty) {
  42469. if (StandardMaterial.FresnelEnabled) {
  42470. // Fresnel
  42471. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42472. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42473. this._reflectionFresnelParameters) {
  42474. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42475. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42476. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42477. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42478. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42479. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42480. defines._needNormals = true;
  42481. defines.FRESNEL = true;
  42482. }
  42483. }
  42484. else {
  42485. defines.FRESNEL = false;
  42486. }
  42487. }
  42488. // Misc.
  42489. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42490. // Attribs
  42491. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42492. // Values that need to be evaluated on every frame
  42493. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42494. // Get correct effect
  42495. if (defines.isDirty) {
  42496. defines.markAsProcessed();
  42497. scene.resetCachedMaterial();
  42498. // Fallbacks
  42499. var fallbacks = new BABYLON.EffectFallbacks();
  42500. if (defines.REFLECTION) {
  42501. fallbacks.addFallback(0, "REFLECTION");
  42502. }
  42503. if (defines.SPECULAR) {
  42504. fallbacks.addFallback(0, "SPECULAR");
  42505. }
  42506. if (defines.BUMP) {
  42507. fallbacks.addFallback(0, "BUMP");
  42508. }
  42509. if (defines.PARALLAX) {
  42510. fallbacks.addFallback(1, "PARALLAX");
  42511. }
  42512. if (defines.PARALLAXOCCLUSION) {
  42513. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42514. }
  42515. if (defines.SPECULAROVERALPHA) {
  42516. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42517. }
  42518. if (defines.FOG) {
  42519. fallbacks.addFallback(1, "FOG");
  42520. }
  42521. if (defines.POINTSIZE) {
  42522. fallbacks.addFallback(0, "POINTSIZE");
  42523. }
  42524. if (defines.LOGARITHMICDEPTH) {
  42525. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42526. }
  42527. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42528. if (defines.SPECULARTERM) {
  42529. fallbacks.addFallback(0, "SPECULARTERM");
  42530. }
  42531. if (defines.DIFFUSEFRESNEL) {
  42532. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42533. }
  42534. if (defines.OPACITYFRESNEL) {
  42535. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42536. }
  42537. if (defines.REFLECTIONFRESNEL) {
  42538. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42539. }
  42540. if (defines.EMISSIVEFRESNEL) {
  42541. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42542. }
  42543. if (defines.FRESNEL) {
  42544. fallbacks.addFallback(4, "FRESNEL");
  42545. }
  42546. //Attributes
  42547. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42548. if (defines.NORMAL) {
  42549. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42550. }
  42551. if (defines.UV1) {
  42552. attribs.push(BABYLON.VertexBuffer.UVKind);
  42553. }
  42554. if (defines.UV2) {
  42555. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42556. }
  42557. if (defines.VERTEXCOLOR) {
  42558. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42559. }
  42560. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42561. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42562. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42563. var shaderName = "default";
  42564. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42565. "vFogInfos", "vFogColor", "pointSize",
  42566. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42567. "mBones",
  42568. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42569. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42570. "vReflectionPosition", "vReflectionSize",
  42571. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42572. ];
  42573. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42574. var uniformBuffers = ["Material", "Scene"];
  42575. if (BABYLON.ImageProcessingConfiguration) {
  42576. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42577. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42578. }
  42579. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42580. uniformsNames: uniforms,
  42581. uniformBuffersNames: uniformBuffers,
  42582. samplers: samplers,
  42583. defines: defines,
  42584. maxSimultaneousLights: this._maxSimultaneousLights
  42585. });
  42586. if (this.customShaderNameResolve) {
  42587. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42588. }
  42589. var join = defines.toString();
  42590. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42591. attributes: attribs,
  42592. uniformsNames: uniforms,
  42593. uniformBuffersNames: uniformBuffers,
  42594. samplers: samplers,
  42595. defines: join,
  42596. fallbacks: fallbacks,
  42597. onCompiled: this.onCompiled,
  42598. onError: this.onError,
  42599. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42600. }, engine), defines);
  42601. this.buildUniformLayout();
  42602. }
  42603. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42604. return false;
  42605. }
  42606. defines._renderId = scene.getRenderId();
  42607. this._wasPreviouslyReady = true;
  42608. return true;
  42609. };
  42610. StandardMaterial.prototype.buildUniformLayout = function () {
  42611. // Order is important !
  42612. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42613. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42614. this._uniformBuffer.addUniform("opacityParts", 4);
  42615. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42616. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42617. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42618. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42619. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42620. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42621. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42622. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42623. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42624. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42625. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42626. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42627. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42628. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42629. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42630. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42631. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42632. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42633. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42634. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42635. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42636. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42637. this._uniformBuffer.addUniform("specularMatrix", 16);
  42638. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42639. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42640. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42641. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42642. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42643. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42644. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42645. this._uniformBuffer.addUniform("pointSize", 1);
  42646. this._uniformBuffer.create();
  42647. };
  42648. StandardMaterial.prototype.unbind = function () {
  42649. if (this._activeEffect) {
  42650. var needFlag = false;
  42651. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42652. this._activeEffect.setTexture("reflection2DSampler", null);
  42653. needFlag = true;
  42654. }
  42655. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42656. this._activeEffect.setTexture("refraction2DSampler", null);
  42657. needFlag = true;
  42658. }
  42659. if (needFlag) {
  42660. this._markAllSubMeshesAsTexturesDirty();
  42661. }
  42662. }
  42663. _super.prototype.unbind.call(this);
  42664. };
  42665. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42666. var scene = this.getScene();
  42667. var defines = subMesh._materialDefines;
  42668. if (!defines) {
  42669. return;
  42670. }
  42671. var effect = subMesh.effect;
  42672. if (!effect) {
  42673. return;
  42674. }
  42675. this._activeEffect = effect;
  42676. // Matrices
  42677. this.bindOnlyWorldMatrix(world);
  42678. // Normal Matrix
  42679. if (defines.OBJECTSPACE_NORMALMAP) {
  42680. world.toNormalMatrix(this._normalMatrix);
  42681. this.bindOnlyNormalMatrix(this._normalMatrix);
  42682. }
  42683. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42684. // Bones
  42685. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42686. if (mustRebind) {
  42687. this._uniformBuffer.bindToEffect(effect, "Material");
  42688. this.bindViewProjection(effect);
  42689. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42690. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42691. // Fresnel
  42692. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42693. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42694. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42695. }
  42696. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42697. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42698. }
  42699. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42700. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42701. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42702. }
  42703. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42704. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42705. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42706. }
  42707. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42708. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42709. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42710. }
  42711. }
  42712. // Textures
  42713. if (scene.texturesEnabled) {
  42714. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42715. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42716. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42717. if (this._diffuseTexture.hasAlpha) {
  42718. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42719. }
  42720. }
  42721. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42722. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42723. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42724. }
  42725. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42726. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42727. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42728. }
  42729. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42730. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42731. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42732. if (this._reflectionTexture.boundingBoxSize) {
  42733. var cubeTexture = this._reflectionTexture;
  42734. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42735. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42736. }
  42737. }
  42738. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42739. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42740. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42741. }
  42742. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42743. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42744. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42745. }
  42746. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42747. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42748. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42749. }
  42750. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42751. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42752. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42753. if (scene._mirroredCameraPosition) {
  42754. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42755. }
  42756. else {
  42757. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42758. }
  42759. }
  42760. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42761. var depth = 1.0;
  42762. if (!this._refractionTexture.isCube) {
  42763. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42764. if (this._refractionTexture.depth) {
  42765. depth = this._refractionTexture.depth;
  42766. }
  42767. }
  42768. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42769. }
  42770. }
  42771. // Point size
  42772. if (this.pointsCloud) {
  42773. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42774. }
  42775. if (defines.SPECULARTERM) {
  42776. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42777. }
  42778. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42779. // Diffuse
  42780. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42781. }
  42782. // Textures
  42783. if (scene.texturesEnabled) {
  42784. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42785. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42786. }
  42787. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42788. effect.setTexture("ambientSampler", this._ambientTexture);
  42789. }
  42790. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42791. effect.setTexture("opacitySampler", this._opacityTexture);
  42792. }
  42793. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42794. if (this._reflectionTexture.isCube) {
  42795. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42796. }
  42797. else {
  42798. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42799. }
  42800. }
  42801. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42802. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42803. }
  42804. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42805. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42806. }
  42807. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42808. effect.setTexture("specularSampler", this._specularTexture);
  42809. }
  42810. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42811. effect.setTexture("bumpSampler", this._bumpTexture);
  42812. }
  42813. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42814. var depth = 1.0;
  42815. if (this._refractionTexture.isCube) {
  42816. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42817. }
  42818. else {
  42819. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42820. }
  42821. }
  42822. }
  42823. // Clip plane
  42824. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42825. // Colors
  42826. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42827. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42828. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42829. }
  42830. if (mustRebind || !this.isFrozen) {
  42831. // Lights
  42832. if (scene.lightsEnabled && !this._disableLighting) {
  42833. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42834. }
  42835. // View
  42836. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42837. this.bindView(effect);
  42838. }
  42839. // Fog
  42840. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42841. // Morph targets
  42842. if (defines.NUM_MORPH_INFLUENCERS) {
  42843. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42844. }
  42845. // Log. depth
  42846. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42847. // image processing
  42848. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42849. this._imageProcessingConfiguration.bind(this._activeEffect);
  42850. }
  42851. }
  42852. this._uniformBuffer.update();
  42853. this._afterBind(mesh, this._activeEffect);
  42854. };
  42855. StandardMaterial.prototype.getAnimatables = function () {
  42856. var results = [];
  42857. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42858. results.push(this._diffuseTexture);
  42859. }
  42860. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42861. results.push(this._ambientTexture);
  42862. }
  42863. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42864. results.push(this._opacityTexture);
  42865. }
  42866. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42867. results.push(this._reflectionTexture);
  42868. }
  42869. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42870. results.push(this._emissiveTexture);
  42871. }
  42872. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42873. results.push(this._specularTexture);
  42874. }
  42875. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42876. results.push(this._bumpTexture);
  42877. }
  42878. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42879. results.push(this._lightmapTexture);
  42880. }
  42881. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42882. results.push(this._refractionTexture);
  42883. }
  42884. return results;
  42885. };
  42886. StandardMaterial.prototype.getActiveTextures = function () {
  42887. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42888. if (this._diffuseTexture) {
  42889. activeTextures.push(this._diffuseTexture);
  42890. }
  42891. if (this._ambientTexture) {
  42892. activeTextures.push(this._ambientTexture);
  42893. }
  42894. if (this._opacityTexture) {
  42895. activeTextures.push(this._opacityTexture);
  42896. }
  42897. if (this._reflectionTexture) {
  42898. activeTextures.push(this._reflectionTexture);
  42899. }
  42900. if (this._emissiveTexture) {
  42901. activeTextures.push(this._emissiveTexture);
  42902. }
  42903. if (this._specularTexture) {
  42904. activeTextures.push(this._specularTexture);
  42905. }
  42906. if (this._bumpTexture) {
  42907. activeTextures.push(this._bumpTexture);
  42908. }
  42909. if (this._lightmapTexture) {
  42910. activeTextures.push(this._lightmapTexture);
  42911. }
  42912. if (this._refractionTexture) {
  42913. activeTextures.push(this._refractionTexture);
  42914. }
  42915. return activeTextures;
  42916. };
  42917. StandardMaterial.prototype.hasTexture = function (texture) {
  42918. if (_super.prototype.hasTexture.call(this, texture)) {
  42919. return true;
  42920. }
  42921. if (this._diffuseTexture === texture) {
  42922. return true;
  42923. }
  42924. if (this._ambientTexture === texture) {
  42925. return true;
  42926. }
  42927. if (this._opacityTexture === texture) {
  42928. return true;
  42929. }
  42930. if (this._reflectionTexture === texture) {
  42931. return true;
  42932. }
  42933. if (this._emissiveTexture === texture) {
  42934. return true;
  42935. }
  42936. if (this._specularTexture === texture) {
  42937. return true;
  42938. }
  42939. if (this._bumpTexture === texture) {
  42940. return true;
  42941. }
  42942. if (this._lightmapTexture === texture) {
  42943. return true;
  42944. }
  42945. if (this._refractionTexture === texture) {
  42946. return true;
  42947. }
  42948. return false;
  42949. };
  42950. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42951. if (forceDisposeTextures) {
  42952. if (this._diffuseTexture) {
  42953. this._diffuseTexture.dispose();
  42954. }
  42955. if (this._ambientTexture) {
  42956. this._ambientTexture.dispose();
  42957. }
  42958. if (this._opacityTexture) {
  42959. this._opacityTexture.dispose();
  42960. }
  42961. if (this._reflectionTexture) {
  42962. this._reflectionTexture.dispose();
  42963. }
  42964. if (this._emissiveTexture) {
  42965. this._emissiveTexture.dispose();
  42966. }
  42967. if (this._specularTexture) {
  42968. this._specularTexture.dispose();
  42969. }
  42970. if (this._bumpTexture) {
  42971. this._bumpTexture.dispose();
  42972. }
  42973. if (this._lightmapTexture) {
  42974. this._lightmapTexture.dispose();
  42975. }
  42976. if (this._refractionTexture) {
  42977. this._refractionTexture.dispose();
  42978. }
  42979. }
  42980. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42981. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42982. }
  42983. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42984. };
  42985. StandardMaterial.prototype.clone = function (name) {
  42986. var _this = this;
  42987. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42988. result.name = name;
  42989. result.id = name;
  42990. return result;
  42991. };
  42992. StandardMaterial.prototype.serialize = function () {
  42993. return BABYLON.SerializationHelper.Serialize(this);
  42994. };
  42995. // Statics
  42996. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42997. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42998. };
  42999. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43000. get: function () {
  43001. return StandardMaterial._DiffuseTextureEnabled;
  43002. },
  43003. set: function (value) {
  43004. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43005. return;
  43006. }
  43007. StandardMaterial._DiffuseTextureEnabled = value;
  43008. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43009. },
  43010. enumerable: true,
  43011. configurable: true
  43012. });
  43013. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43014. get: function () {
  43015. return StandardMaterial._AmbientTextureEnabled;
  43016. },
  43017. set: function (value) {
  43018. if (StandardMaterial._AmbientTextureEnabled === value) {
  43019. return;
  43020. }
  43021. StandardMaterial._AmbientTextureEnabled = value;
  43022. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43023. },
  43024. enumerable: true,
  43025. configurable: true
  43026. });
  43027. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43028. get: function () {
  43029. return StandardMaterial._OpacityTextureEnabled;
  43030. },
  43031. set: function (value) {
  43032. if (StandardMaterial._OpacityTextureEnabled === value) {
  43033. return;
  43034. }
  43035. StandardMaterial._OpacityTextureEnabled = value;
  43036. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43037. },
  43038. enumerable: true,
  43039. configurable: true
  43040. });
  43041. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43042. get: function () {
  43043. return StandardMaterial._ReflectionTextureEnabled;
  43044. },
  43045. set: function (value) {
  43046. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43047. return;
  43048. }
  43049. StandardMaterial._ReflectionTextureEnabled = value;
  43050. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43051. },
  43052. enumerable: true,
  43053. configurable: true
  43054. });
  43055. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43056. get: function () {
  43057. return StandardMaterial._EmissiveTextureEnabled;
  43058. },
  43059. set: function (value) {
  43060. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43061. return;
  43062. }
  43063. StandardMaterial._EmissiveTextureEnabled = value;
  43064. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43065. },
  43066. enumerable: true,
  43067. configurable: true
  43068. });
  43069. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43070. get: function () {
  43071. return StandardMaterial._SpecularTextureEnabled;
  43072. },
  43073. set: function (value) {
  43074. if (StandardMaterial._SpecularTextureEnabled === value) {
  43075. return;
  43076. }
  43077. StandardMaterial._SpecularTextureEnabled = value;
  43078. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43079. },
  43080. enumerable: true,
  43081. configurable: true
  43082. });
  43083. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43084. get: function () {
  43085. return StandardMaterial._BumpTextureEnabled;
  43086. },
  43087. set: function (value) {
  43088. if (StandardMaterial._BumpTextureEnabled === value) {
  43089. return;
  43090. }
  43091. StandardMaterial._BumpTextureEnabled = value;
  43092. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43093. },
  43094. enumerable: true,
  43095. configurable: true
  43096. });
  43097. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43098. get: function () {
  43099. return StandardMaterial._LightmapTextureEnabled;
  43100. },
  43101. set: function (value) {
  43102. if (StandardMaterial._LightmapTextureEnabled === value) {
  43103. return;
  43104. }
  43105. StandardMaterial._LightmapTextureEnabled = value;
  43106. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43107. },
  43108. enumerable: true,
  43109. configurable: true
  43110. });
  43111. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43112. get: function () {
  43113. return StandardMaterial._RefractionTextureEnabled;
  43114. },
  43115. set: function (value) {
  43116. if (StandardMaterial._RefractionTextureEnabled === value) {
  43117. return;
  43118. }
  43119. StandardMaterial._RefractionTextureEnabled = value;
  43120. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43121. },
  43122. enumerable: true,
  43123. configurable: true
  43124. });
  43125. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43126. get: function () {
  43127. return StandardMaterial._ColorGradingTextureEnabled;
  43128. },
  43129. set: function (value) {
  43130. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43131. return;
  43132. }
  43133. StandardMaterial._ColorGradingTextureEnabled = value;
  43134. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43135. },
  43136. enumerable: true,
  43137. configurable: true
  43138. });
  43139. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43140. get: function () {
  43141. return StandardMaterial._FresnelEnabled;
  43142. },
  43143. set: function (value) {
  43144. if (StandardMaterial._FresnelEnabled === value) {
  43145. return;
  43146. }
  43147. StandardMaterial._FresnelEnabled = value;
  43148. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43149. },
  43150. enumerable: true,
  43151. configurable: true
  43152. });
  43153. // Flags used to enable or disable a type of texture for all Standard Materials
  43154. StandardMaterial._DiffuseTextureEnabled = true;
  43155. StandardMaterial._AmbientTextureEnabled = true;
  43156. StandardMaterial._OpacityTextureEnabled = true;
  43157. StandardMaterial._ReflectionTextureEnabled = true;
  43158. StandardMaterial._EmissiveTextureEnabled = true;
  43159. StandardMaterial._SpecularTextureEnabled = true;
  43160. StandardMaterial._BumpTextureEnabled = true;
  43161. StandardMaterial._LightmapTextureEnabled = true;
  43162. StandardMaterial._RefractionTextureEnabled = true;
  43163. StandardMaterial._ColorGradingTextureEnabled = true;
  43164. StandardMaterial._FresnelEnabled = true;
  43165. __decorate([
  43166. BABYLON.serializeAsTexture("diffuseTexture")
  43167. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43168. __decorate([
  43169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43170. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43171. __decorate([
  43172. BABYLON.serializeAsTexture("ambientTexture")
  43173. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43174. __decorate([
  43175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43176. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43177. __decorate([
  43178. BABYLON.serializeAsTexture("opacityTexture")
  43179. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43180. __decorate([
  43181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43182. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43183. __decorate([
  43184. BABYLON.serializeAsTexture("reflectionTexture")
  43185. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43186. __decorate([
  43187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43188. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43189. __decorate([
  43190. BABYLON.serializeAsTexture("emissiveTexture")
  43191. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43192. __decorate([
  43193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43194. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43195. __decorate([
  43196. BABYLON.serializeAsTexture("specularTexture")
  43197. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43198. __decorate([
  43199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43200. ], StandardMaterial.prototype, "specularTexture", void 0);
  43201. __decorate([
  43202. BABYLON.serializeAsTexture("bumpTexture")
  43203. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43204. __decorate([
  43205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43206. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43207. __decorate([
  43208. BABYLON.serializeAsTexture("lightmapTexture")
  43209. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43210. __decorate([
  43211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43212. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43213. __decorate([
  43214. BABYLON.serializeAsTexture("refractionTexture")
  43215. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43216. __decorate([
  43217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43218. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43219. __decorate([
  43220. BABYLON.serializeAsColor3("ambient")
  43221. ], StandardMaterial.prototype, "ambientColor", void 0);
  43222. __decorate([
  43223. BABYLON.serializeAsColor3("diffuse")
  43224. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43225. __decorate([
  43226. BABYLON.serializeAsColor3("specular")
  43227. ], StandardMaterial.prototype, "specularColor", void 0);
  43228. __decorate([
  43229. BABYLON.serializeAsColor3("emissive")
  43230. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43231. __decorate([
  43232. BABYLON.serialize()
  43233. ], StandardMaterial.prototype, "specularPower", void 0);
  43234. __decorate([
  43235. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43236. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43237. __decorate([
  43238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43239. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43240. __decorate([
  43241. BABYLON.serialize("useEmissiveAsIllumination")
  43242. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43243. __decorate([
  43244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43245. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43246. __decorate([
  43247. BABYLON.serialize("linkEmissiveWithDiffuse")
  43248. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43249. __decorate([
  43250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43251. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43252. __decorate([
  43253. BABYLON.serialize("useSpecularOverAlpha")
  43254. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43255. __decorate([
  43256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43257. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43258. __decorate([
  43259. BABYLON.serialize("useReflectionOverAlpha")
  43260. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43261. __decorate([
  43262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43263. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43264. __decorate([
  43265. BABYLON.serialize("disableLighting")
  43266. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43267. __decorate([
  43268. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43269. ], StandardMaterial.prototype, "disableLighting", void 0);
  43270. __decorate([
  43271. BABYLON.serialize("useObjectSpaceNormalMap")
  43272. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43273. __decorate([
  43274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43275. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43276. __decorate([
  43277. BABYLON.serialize("useParallax")
  43278. ], StandardMaterial.prototype, "_useParallax", void 0);
  43279. __decorate([
  43280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43281. ], StandardMaterial.prototype, "useParallax", void 0);
  43282. __decorate([
  43283. BABYLON.serialize("useParallaxOcclusion")
  43284. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43285. __decorate([
  43286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43287. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43288. __decorate([
  43289. BABYLON.serialize()
  43290. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43291. __decorate([
  43292. BABYLON.serialize("roughness")
  43293. ], StandardMaterial.prototype, "_roughness", void 0);
  43294. __decorate([
  43295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43296. ], StandardMaterial.prototype, "roughness", void 0);
  43297. __decorate([
  43298. BABYLON.serialize()
  43299. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43300. __decorate([
  43301. BABYLON.serialize()
  43302. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43303. __decorate([
  43304. BABYLON.serialize()
  43305. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43306. __decorate([
  43307. BABYLON.serialize("useLightmapAsShadowmap")
  43308. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43309. __decorate([
  43310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43311. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43312. __decorate([
  43313. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43314. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43315. __decorate([
  43316. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43317. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43318. __decorate([
  43319. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43320. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43321. __decorate([
  43322. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43323. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43324. __decorate([
  43325. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43326. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43327. __decorate([
  43328. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43329. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43330. __decorate([
  43331. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43332. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43333. __decorate([
  43334. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43335. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43336. __decorate([
  43337. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43338. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43339. __decorate([
  43340. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43341. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43342. __decorate([
  43343. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43344. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43345. __decorate([
  43346. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43347. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43348. __decorate([
  43349. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43350. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43351. __decorate([
  43352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43353. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43354. __decorate([
  43355. BABYLON.serialize("maxSimultaneousLights")
  43356. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43357. __decorate([
  43358. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43359. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43360. __decorate([
  43361. BABYLON.serialize("invertNormalMapX")
  43362. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43363. __decorate([
  43364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43365. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43366. __decorate([
  43367. BABYLON.serialize("invertNormalMapY")
  43368. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43369. __decorate([
  43370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43371. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43372. __decorate([
  43373. BABYLON.serialize("twoSidedLighting")
  43374. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43375. __decorate([
  43376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43377. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43378. __decorate([
  43379. BABYLON.serialize()
  43380. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43381. return StandardMaterial;
  43382. }(BABYLON.PushMaterial));
  43383. BABYLON.StandardMaterial = StandardMaterial;
  43384. })(BABYLON || (BABYLON = {}));
  43385. //# sourceMappingURL=babylon.standardMaterial.js.map
  43386. var BABYLON;
  43387. (function (BABYLON) {
  43388. /**
  43389. * Class representing spherical polynomial coefficients to the 3rd degree
  43390. */
  43391. var SphericalPolynomial = /** @class */ (function () {
  43392. function SphericalPolynomial() {
  43393. /**
  43394. * The x coefficients of the spherical polynomial
  43395. */
  43396. this.x = BABYLON.Vector3.Zero();
  43397. /**
  43398. * The y coefficients of the spherical polynomial
  43399. */
  43400. this.y = BABYLON.Vector3.Zero();
  43401. /**
  43402. * The z coefficients of the spherical polynomial
  43403. */
  43404. this.z = BABYLON.Vector3.Zero();
  43405. /**
  43406. * The xx coefficients of the spherical polynomial
  43407. */
  43408. this.xx = BABYLON.Vector3.Zero();
  43409. /**
  43410. * The yy coefficients of the spherical polynomial
  43411. */
  43412. this.yy = BABYLON.Vector3.Zero();
  43413. /**
  43414. * The zz coefficients of the spherical polynomial
  43415. */
  43416. this.zz = BABYLON.Vector3.Zero();
  43417. /**
  43418. * The xy coefficients of the spherical polynomial
  43419. */
  43420. this.xy = BABYLON.Vector3.Zero();
  43421. /**
  43422. * The yz coefficients of the spherical polynomial
  43423. */
  43424. this.yz = BABYLON.Vector3.Zero();
  43425. /**
  43426. * The zx coefficients of the spherical polynomial
  43427. */
  43428. this.zx = BABYLON.Vector3.Zero();
  43429. }
  43430. /**
  43431. * Adds an ambient color to the spherical polynomial
  43432. * @param color the color to add
  43433. */
  43434. SphericalPolynomial.prototype.addAmbient = function (color) {
  43435. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43436. this.xx = this.xx.add(colorVector);
  43437. this.yy = this.yy.add(colorVector);
  43438. this.zz = this.zz.add(colorVector);
  43439. };
  43440. /**
  43441. * Scales the spherical polynomial by the given amount
  43442. * @param scale the amount to scale
  43443. */
  43444. SphericalPolynomial.prototype.scale = function (scale) {
  43445. this.x = this.x.scale(scale);
  43446. this.y = this.y.scale(scale);
  43447. this.z = this.z.scale(scale);
  43448. this.xx = this.xx.scale(scale);
  43449. this.yy = this.yy.scale(scale);
  43450. this.zz = this.zz.scale(scale);
  43451. this.yz = this.yz.scale(scale);
  43452. this.zx = this.zx.scale(scale);
  43453. this.xy = this.xy.scale(scale);
  43454. };
  43455. /**
  43456. * Gets the spherical polynomial from harmonics
  43457. * @param harmonics the spherical harmonics
  43458. * @returns the spherical polynomial
  43459. */
  43460. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43461. var result = new SphericalPolynomial();
  43462. result.x = harmonics.l11.scale(1.02333);
  43463. result.y = harmonics.l1_1.scale(1.02333);
  43464. result.z = harmonics.l10.scale(1.02333);
  43465. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43466. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43467. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43468. result.yz = harmonics.l2_1.scale(0.858086);
  43469. result.zx = harmonics.l21.scale(0.858086);
  43470. result.xy = harmonics.l2_2.scale(0.858086);
  43471. result.scale(1.0 / Math.PI);
  43472. return result;
  43473. };
  43474. /**
  43475. * Constructs a spherical polynomial from an array.
  43476. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43477. * @returns the spherical polynomial
  43478. */
  43479. SphericalPolynomial.FromArray = function (data) {
  43480. var sp = new SphericalPolynomial();
  43481. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43482. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43483. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43484. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43485. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43486. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43487. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43488. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43489. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43490. return sp;
  43491. };
  43492. return SphericalPolynomial;
  43493. }());
  43494. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43495. /**
  43496. * Class representing spherical harmonics coefficients to the 3rd degree
  43497. */
  43498. var SphericalHarmonics = /** @class */ (function () {
  43499. function SphericalHarmonics() {
  43500. /**
  43501. * The l0,0 coefficients of the spherical harmonics
  43502. */
  43503. this.l00 = BABYLON.Vector3.Zero();
  43504. /**
  43505. * The l1,-1 coefficients of the spherical harmonics
  43506. */
  43507. this.l1_1 = BABYLON.Vector3.Zero();
  43508. /**
  43509. * The l1,0 coefficients of the spherical harmonics
  43510. */
  43511. this.l10 = BABYLON.Vector3.Zero();
  43512. /**
  43513. * The l1,1 coefficients of the spherical harmonics
  43514. */
  43515. this.l11 = BABYLON.Vector3.Zero();
  43516. /**
  43517. * The l2,-2 coefficients of the spherical harmonics
  43518. */
  43519. this.l2_2 = BABYLON.Vector3.Zero();
  43520. /**
  43521. * The l2,-1 coefficients of the spherical harmonics
  43522. */
  43523. this.l2_1 = BABYLON.Vector3.Zero();
  43524. /**
  43525. * The l2,0 coefficients of the spherical harmonics
  43526. */
  43527. this.l20 = BABYLON.Vector3.Zero();
  43528. /**
  43529. * The l2,1 coefficients of the spherical harmonics
  43530. */
  43531. this.l21 = BABYLON.Vector3.Zero();
  43532. /**
  43533. * The l2,2 coefficients of the spherical harmonics
  43534. */
  43535. this.lL22 = BABYLON.Vector3.Zero();
  43536. }
  43537. /**
  43538. * Adds a light to the spherical harmonics
  43539. * @param direction the direction of the light
  43540. * @param color the color of the light
  43541. * @param deltaSolidAngle the delta solid angle of the light
  43542. */
  43543. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43544. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43545. var c = colorVector.scale(deltaSolidAngle);
  43546. this.l00 = this.l00.add(c.scale(0.282095));
  43547. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43548. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43549. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43550. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43551. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43552. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43553. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43554. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43555. };
  43556. /**
  43557. * Scales the spherical harmonics by the given amount
  43558. * @param scale the amount to scale
  43559. */
  43560. SphericalHarmonics.prototype.scale = function (scale) {
  43561. this.l00 = this.l00.scale(scale);
  43562. this.l1_1 = this.l1_1.scale(scale);
  43563. this.l10 = this.l10.scale(scale);
  43564. this.l11 = this.l11.scale(scale);
  43565. this.l2_2 = this.l2_2.scale(scale);
  43566. this.l2_1 = this.l2_1.scale(scale);
  43567. this.l20 = this.l20.scale(scale);
  43568. this.l21 = this.l21.scale(scale);
  43569. this.lL22 = this.lL22.scale(scale);
  43570. };
  43571. /**
  43572. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43573. *
  43574. * ```
  43575. * E_lm = A_l * L_lm
  43576. * ```
  43577. *
  43578. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43579. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43580. * the scaling factors are given in equation 9.
  43581. */
  43582. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43583. // Constant (Band 0)
  43584. this.l00 = this.l00.scale(3.141593);
  43585. // Linear (Band 1)
  43586. this.l1_1 = this.l1_1.scale(2.094395);
  43587. this.l10 = this.l10.scale(2.094395);
  43588. this.l11 = this.l11.scale(2.094395);
  43589. // Quadratic (Band 2)
  43590. this.l2_2 = this.l2_2.scale(0.785398);
  43591. this.l2_1 = this.l2_1.scale(0.785398);
  43592. this.l20 = this.l20.scale(0.785398);
  43593. this.l21 = this.l21.scale(0.785398);
  43594. this.lL22 = this.lL22.scale(0.785398);
  43595. };
  43596. /**
  43597. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43598. *
  43599. * ```
  43600. * L = (1/pi) * E * rho
  43601. * ```
  43602. *
  43603. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43604. */
  43605. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43606. this.scale(1.0 / Math.PI);
  43607. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43608. // (The pixel shader must apply albedo after texture fetches, etc).
  43609. };
  43610. /**
  43611. * Gets the spherical harmonics from polynomial
  43612. * @param polynomial the spherical polynomial
  43613. * @returns the spherical harmonics
  43614. */
  43615. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43616. var result = new SphericalHarmonics();
  43617. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43618. result.l1_1 = polynomial.y.scale(0.977204);
  43619. result.l10 = polynomial.z.scale(0.977204);
  43620. result.l11 = polynomial.x.scale(0.977204);
  43621. result.l2_2 = polynomial.xy.scale(1.16538);
  43622. result.l2_1 = polynomial.yz.scale(1.16538);
  43623. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43624. result.l21 = polynomial.zx.scale(1.16538);
  43625. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43626. result.scale(Math.PI);
  43627. return result;
  43628. };
  43629. /**
  43630. * Constructs a spherical harmonics from an array.
  43631. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43632. * @returns the spherical harmonics
  43633. */
  43634. SphericalHarmonics.FromArray = function (data) {
  43635. var sh = new SphericalHarmonics();
  43636. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43637. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43638. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43639. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43640. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43641. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43642. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43643. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43644. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43645. return sh;
  43646. };
  43647. return SphericalHarmonics;
  43648. }());
  43649. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43650. })(BABYLON || (BABYLON = {}));
  43651. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43652. var BABYLON;
  43653. (function (BABYLON) {
  43654. var FileFaceOrientation = /** @class */ (function () {
  43655. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43656. this.name = name;
  43657. this.worldAxisForNormal = worldAxisForNormal;
  43658. this.worldAxisForFileX = worldAxisForFileX;
  43659. this.worldAxisForFileY = worldAxisForFileY;
  43660. }
  43661. return FileFaceOrientation;
  43662. }());
  43663. ;
  43664. /**
  43665. * Helper class dealing with the extraction of spherical polynomial dataArray
  43666. * from a cube map.
  43667. */
  43668. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43669. function CubeMapToSphericalPolynomialTools() {
  43670. }
  43671. /**
  43672. * Converts a texture to the according Spherical Polynomial data.
  43673. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43674. *
  43675. * @param texture The texture to extract the information from.
  43676. * @return The Spherical Polynomial data.
  43677. */
  43678. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43679. if (!texture.isCube) {
  43680. // Only supports cube Textures currently.
  43681. return null;
  43682. }
  43683. var size = texture.getSize().width;
  43684. var right = texture.readPixels(0);
  43685. var left = texture.readPixels(1);
  43686. var up;
  43687. var down;
  43688. if (texture.isRenderTarget) {
  43689. up = texture.readPixels(3);
  43690. down = texture.readPixels(2);
  43691. }
  43692. else {
  43693. up = texture.readPixels(2);
  43694. down = texture.readPixels(3);
  43695. }
  43696. var front = texture.readPixels(4);
  43697. var back = texture.readPixels(5);
  43698. var gammaSpace = texture.gammaSpace;
  43699. // Always read as RGBA.
  43700. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43701. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43702. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43703. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43704. }
  43705. var cubeInfo = {
  43706. size: size,
  43707. right: right,
  43708. left: left,
  43709. up: up,
  43710. down: down,
  43711. front: front,
  43712. back: back,
  43713. format: format,
  43714. type: type,
  43715. gammaSpace: gammaSpace,
  43716. };
  43717. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43718. };
  43719. /**
  43720. * Converts a cubemap to the according Spherical Polynomial data.
  43721. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43722. *
  43723. * @param cubeInfo The Cube map to extract the information from.
  43724. * @return The Spherical Polynomial data.
  43725. */
  43726. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43727. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43728. var totalSolidAngle = 0.0;
  43729. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43730. var du = 2.0 / cubeInfo.size;
  43731. var dv = du;
  43732. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43733. var minUV = du * 0.5 - 1.0;
  43734. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43735. var fileFace = this.FileFaces[faceIndex];
  43736. var dataArray = cubeInfo[fileFace.name];
  43737. var v = minUV;
  43738. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43739. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43740. // Because SP is still linear, so summation is fine in that basis.
  43741. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43742. for (var y = 0; y < cubeInfo.size; y++) {
  43743. var u = minUV;
  43744. for (var x = 0; x < cubeInfo.size; x++) {
  43745. // World direction (not normalised)
  43746. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43747. worldDirection.normalize();
  43748. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43749. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43750. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43751. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43752. // Handle Integer types.
  43753. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43754. r /= 255;
  43755. g /= 255;
  43756. b /= 255;
  43757. }
  43758. // Handle Gamma space textures.
  43759. if (cubeInfo.gammaSpace) {
  43760. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43761. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43762. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43763. }
  43764. var color = new BABYLON.Color3(r, g, b);
  43765. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43766. totalSolidAngle += deltaSolidAngle;
  43767. u += du;
  43768. }
  43769. v += dv;
  43770. }
  43771. }
  43772. // Solid angle for entire sphere is 4*pi
  43773. var sphereSolidAngle = 4.0 * Math.PI;
  43774. // Adjust the solid angle to allow for how many faces we processed.
  43775. var facesProcessed = 6.0;
  43776. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43777. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43778. // This is needed because the numerical integration over the cube uses a
  43779. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43780. // and also to compensate for accumulative error due to float precision in the summation.
  43781. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43782. sphericalHarmonics.scale(correctionFactor);
  43783. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43784. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43785. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43786. };
  43787. CubeMapToSphericalPolynomialTools.FileFaces = [
  43788. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43789. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43790. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43791. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43792. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43793. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43794. ];
  43795. return CubeMapToSphericalPolynomialTools;
  43796. }());
  43797. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43798. })(BABYLON || (BABYLON = {}));
  43799. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43800. var BABYLON;
  43801. (function (BABYLON) {
  43802. /**
  43803. * Manages the defines for the PBR Material.
  43804. * @hiddenChildren
  43805. */
  43806. var PBRMaterialDefines = /** @class */ (function (_super) {
  43807. __extends(PBRMaterialDefines, _super);
  43808. /**
  43809. * Initializes the PBR Material defines.
  43810. */
  43811. function PBRMaterialDefines() {
  43812. var _this = _super.call(this) || this;
  43813. _this.PBR = true;
  43814. _this.MAINUV1 = false;
  43815. _this.MAINUV2 = false;
  43816. _this.UV1 = false;
  43817. _this.UV2 = false;
  43818. _this.ALBEDO = false;
  43819. _this.ALBEDODIRECTUV = 0;
  43820. _this.VERTEXCOLOR = false;
  43821. _this.AMBIENT = false;
  43822. _this.AMBIENTDIRECTUV = 0;
  43823. _this.AMBIENTINGRAYSCALE = false;
  43824. _this.OPACITY = false;
  43825. _this.VERTEXALPHA = false;
  43826. _this.OPACITYDIRECTUV = 0;
  43827. _this.OPACITYRGB = false;
  43828. _this.ALPHATEST = false;
  43829. _this.DEPTHPREPASS = false;
  43830. _this.ALPHABLEND = false;
  43831. _this.ALPHAFROMALBEDO = false;
  43832. _this.ALPHATESTVALUE = "0.5";
  43833. _this.SPECULAROVERALPHA = false;
  43834. _this.RADIANCEOVERALPHA = false;
  43835. _this.ALPHAFRESNEL = false;
  43836. _this.LINEARALPHAFRESNEL = false;
  43837. _this.PREMULTIPLYALPHA = false;
  43838. _this.EMISSIVE = false;
  43839. _this.EMISSIVEDIRECTUV = 0;
  43840. _this.REFLECTIVITY = false;
  43841. _this.REFLECTIVITYDIRECTUV = 0;
  43842. _this.SPECULARTERM = false;
  43843. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43844. _this.MICROSURFACEAUTOMATIC = false;
  43845. _this.LODBASEDMICROSFURACE = false;
  43846. _this.MICROSURFACEMAP = false;
  43847. _this.MICROSURFACEMAPDIRECTUV = 0;
  43848. _this.METALLICWORKFLOW = false;
  43849. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43850. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43851. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43852. _this.AOSTOREINMETALMAPRED = false;
  43853. _this.ENVIRONMENTBRDF = false;
  43854. _this.NORMAL = false;
  43855. _this.TANGENT = false;
  43856. _this.BUMP = false;
  43857. _this.BUMPDIRECTUV = 0;
  43858. _this.OBJECTSPACE_NORMALMAP = false;
  43859. _this.PARALLAX = false;
  43860. _this.PARALLAXOCCLUSION = false;
  43861. _this.NORMALXYSCALE = true;
  43862. _this.LIGHTMAP = false;
  43863. _this.LIGHTMAPDIRECTUV = 0;
  43864. _this.USELIGHTMAPASSHADOWMAP = false;
  43865. _this.GAMMALIGHTMAP = false;
  43866. _this.REFLECTION = false;
  43867. _this.REFLECTIONMAP_3D = false;
  43868. _this.REFLECTIONMAP_SPHERICAL = false;
  43869. _this.REFLECTIONMAP_PLANAR = false;
  43870. _this.REFLECTIONMAP_CUBIC = false;
  43871. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43872. _this.REFLECTIONMAP_PROJECTION = false;
  43873. _this.REFLECTIONMAP_SKYBOX = false;
  43874. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43875. _this.REFLECTIONMAP_EXPLICIT = false;
  43876. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43877. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43878. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43879. _this.INVERTCUBICMAP = false;
  43880. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43881. _this.USESPHERICALINVERTEX = false;
  43882. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43883. _this.LODINREFLECTIONALPHA = false;
  43884. _this.GAMMAREFLECTION = false;
  43885. _this.RGBDREFLECTION = false;
  43886. _this.RADIANCEOCCLUSION = false;
  43887. _this.HORIZONOCCLUSION = false;
  43888. _this.REFRACTION = false;
  43889. _this.REFRACTIONMAP_3D = false;
  43890. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43891. _this.LODINREFRACTIONALPHA = false;
  43892. _this.GAMMAREFRACTION = false;
  43893. _this.RGBDREFRACTION = false;
  43894. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43895. _this.INSTANCES = false;
  43896. _this.NUM_BONE_INFLUENCERS = 0;
  43897. _this.BonesPerMesh = 0;
  43898. _this.NONUNIFORMSCALING = false;
  43899. _this.MORPHTARGETS = false;
  43900. _this.MORPHTARGETS_NORMAL = false;
  43901. _this.MORPHTARGETS_TANGENT = false;
  43902. _this.NUM_MORPH_INFLUENCERS = 0;
  43903. _this.IMAGEPROCESSING = false;
  43904. _this.VIGNETTE = false;
  43905. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43906. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43907. _this.TONEMAPPING = false;
  43908. _this.TONEMAPPING_ACES = false;
  43909. _this.CONTRAST = false;
  43910. _this.COLORCURVES = false;
  43911. _this.COLORGRADING = false;
  43912. _this.COLORGRADING3D = false;
  43913. _this.SAMPLER3DGREENDEPTH = false;
  43914. _this.SAMPLER3DBGRMAP = false;
  43915. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43916. _this.EXPOSURE = false;
  43917. _this.USEPHYSICALLIGHTFALLOFF = false;
  43918. _this.USEGLTFLIGHTFALLOFF = false;
  43919. _this.TWOSIDEDLIGHTING = false;
  43920. _this.SHADOWFLOAT = false;
  43921. _this.CLIPPLANE = false;
  43922. _this.CLIPPLANE2 = false;
  43923. _this.CLIPPLANE3 = false;
  43924. _this.CLIPPLANE4 = false;
  43925. _this.POINTSIZE = false;
  43926. _this.FOG = false;
  43927. _this.LOGARITHMICDEPTH = false;
  43928. _this.FORCENORMALFORWARD = false;
  43929. _this.SPECULARAA = false;
  43930. _this.UNLIT = false;
  43931. _this.rebuild();
  43932. return _this;
  43933. }
  43934. /**
  43935. * Resets the PBR Material defines.
  43936. */
  43937. PBRMaterialDefines.prototype.reset = function () {
  43938. _super.prototype.reset.call(this);
  43939. this.ALPHATESTVALUE = "0.5";
  43940. this.PBR = true;
  43941. };
  43942. return PBRMaterialDefines;
  43943. }(BABYLON.MaterialDefines));
  43944. /**
  43945. * The Physically based material base class of BJS.
  43946. *
  43947. * This offers the main features of a standard PBR material.
  43948. * For more information, please refer to the documentation :
  43949. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43950. */
  43951. var PBRBaseMaterial = /** @class */ (function (_super) {
  43952. __extends(PBRBaseMaterial, _super);
  43953. /**
  43954. * Instantiates a new PBRMaterial instance.
  43955. *
  43956. * @param name The material name
  43957. * @param scene The scene the material will be use in.
  43958. */
  43959. function PBRBaseMaterial(name, scene) {
  43960. var _this = _super.call(this, name, scene) || this;
  43961. /**
  43962. * Intensity of the direct lights e.g. the four lights available in your scene.
  43963. * This impacts both the direct diffuse and specular highlights.
  43964. */
  43965. _this._directIntensity = 1.0;
  43966. /**
  43967. * Intensity of the emissive part of the material.
  43968. * This helps controlling the emissive effect without modifying the emissive color.
  43969. */
  43970. _this._emissiveIntensity = 1.0;
  43971. /**
  43972. * Intensity of the environment e.g. how much the environment will light the object
  43973. * either through harmonics for rough material or through the refelction for shiny ones.
  43974. */
  43975. _this._environmentIntensity = 1.0;
  43976. /**
  43977. * This is a special control allowing the reduction of the specular highlights coming from the
  43978. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43979. */
  43980. _this._specularIntensity = 1.0;
  43981. /**
  43982. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43983. */
  43984. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43985. /**
  43986. * Debug Control allowing disabling the bump map on this material.
  43987. */
  43988. _this._disableBumpMap = false;
  43989. /**
  43990. * AKA Occlusion Texture Intensity in other nomenclature.
  43991. */
  43992. _this._ambientTextureStrength = 1.0;
  43993. /**
  43994. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43995. * 1 means it completely occludes it
  43996. * 0 mean it has no impact
  43997. */
  43998. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43999. /**
  44000. * The color of a material in ambient lighting.
  44001. */
  44002. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44003. /**
  44004. * AKA Diffuse Color in other nomenclature.
  44005. */
  44006. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44007. /**
  44008. * AKA Specular Color in other nomenclature.
  44009. */
  44010. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44011. /**
  44012. * The color applied when light is reflected from a material.
  44013. */
  44014. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44015. /**
  44016. * The color applied when light is emitted from a material.
  44017. */
  44018. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44019. /**
  44020. * AKA Glossiness in other nomenclature.
  44021. */
  44022. _this._microSurface = 0.9;
  44023. /**
  44024. * source material index of refraction (IOR)' / 'destination material IOR.
  44025. */
  44026. _this._indexOfRefraction = 0.66;
  44027. /**
  44028. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44029. */
  44030. _this._invertRefractionY = false;
  44031. /**
  44032. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44033. * Materials half opaque for instance using refraction could benefit from this control.
  44034. */
  44035. _this._linkRefractionWithTransparency = false;
  44036. /**
  44037. * Specifies that the material will use the light map as a show map.
  44038. */
  44039. _this._useLightmapAsShadowmap = false;
  44040. /**
  44041. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44042. * makes the reflect vector face the model (under horizon).
  44043. */
  44044. _this._useHorizonOcclusion = true;
  44045. /**
  44046. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44047. * too much the area relying on ambient texture to define their ambient occlusion.
  44048. */
  44049. _this._useRadianceOcclusion = true;
  44050. /**
  44051. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44052. */
  44053. _this._useAlphaFromAlbedoTexture = false;
  44054. /**
  44055. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44056. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44057. */
  44058. _this._useSpecularOverAlpha = true;
  44059. /**
  44060. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44061. */
  44062. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44063. /**
  44064. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44065. */
  44066. _this._useRoughnessFromMetallicTextureAlpha = true;
  44067. /**
  44068. * Specifies if the metallic texture contains the roughness information in its green channel.
  44069. */
  44070. _this._useRoughnessFromMetallicTextureGreen = false;
  44071. /**
  44072. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44073. */
  44074. _this._useMetallnessFromMetallicTextureBlue = false;
  44075. /**
  44076. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44077. */
  44078. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44079. /**
  44080. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44081. */
  44082. _this._useAmbientInGrayScale = false;
  44083. /**
  44084. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44085. * The material will try to infer what glossiness each pixel should be.
  44086. */
  44087. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44088. /**
  44089. * Defines the falloff type used in this material.
  44090. * It by default is Physical.
  44091. */
  44092. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44093. /**
  44094. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44095. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44096. */
  44097. _this._useRadianceOverAlpha = true;
  44098. /**
  44099. * Allows using an object space normal map (instead of tangent space).
  44100. */
  44101. _this._useObjectSpaceNormalMap = false;
  44102. /**
  44103. * Allows using the bump map in parallax mode.
  44104. */
  44105. _this._useParallax = false;
  44106. /**
  44107. * Allows using the bump map in parallax occlusion mode.
  44108. */
  44109. _this._useParallaxOcclusion = false;
  44110. /**
  44111. * Controls the scale bias of the parallax mode.
  44112. */
  44113. _this._parallaxScaleBias = 0.05;
  44114. /**
  44115. * If sets to true, disables all the lights affecting the material.
  44116. */
  44117. _this._disableLighting = false;
  44118. /**
  44119. * Number of Simultaneous lights allowed on the material.
  44120. */
  44121. _this._maxSimultaneousLights = 4;
  44122. /**
  44123. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44124. */
  44125. _this._invertNormalMapX = false;
  44126. /**
  44127. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44128. */
  44129. _this._invertNormalMapY = false;
  44130. /**
  44131. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44132. */
  44133. _this._twoSidedLighting = false;
  44134. /**
  44135. * Defines the alpha limits in alpha test mode.
  44136. */
  44137. _this._alphaCutOff = 0.4;
  44138. /**
  44139. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44140. */
  44141. _this._forceAlphaTest = false;
  44142. /**
  44143. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44144. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44145. */
  44146. _this._useAlphaFresnel = false;
  44147. /**
  44148. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44149. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44150. */
  44151. _this._useLinearAlphaFresnel = false;
  44152. /**
  44153. * The transparency mode of the material.
  44154. */
  44155. _this._transparencyMode = null;
  44156. /**
  44157. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44158. * from cos thetav and roughness:
  44159. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44160. */
  44161. _this._environmentBRDFTexture = null;
  44162. /**
  44163. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44164. */
  44165. _this._forceIrradianceInFragment = false;
  44166. /**
  44167. * Force normal to face away from face.
  44168. */
  44169. _this._forceNormalForward = false;
  44170. /**
  44171. * Enables specular anti aliasing in the PBR shader.
  44172. * It will both interacts on the Geometry for analytical and IBL lighting.
  44173. * It also prefilter the roughness map based on the bump values.
  44174. */
  44175. _this._enableSpecularAntiAliasing = false;
  44176. /**
  44177. * Stores the available render targets.
  44178. */
  44179. _this._renderTargets = new BABYLON.SmartArray(16);
  44180. /**
  44181. * Sets the global ambient color for the material used in lighting calculations.
  44182. */
  44183. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44184. /**
  44185. * If set to true, no lighting calculations will be applied.
  44186. */
  44187. _this._unlit = false;
  44188. // Setup the default processing configuration to the scene.
  44189. _this._attachImageProcessingConfiguration(null);
  44190. _this.getRenderTargetTextures = function () {
  44191. _this._renderTargets.reset();
  44192. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44193. _this._renderTargets.push(_this._reflectionTexture);
  44194. }
  44195. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44196. _this._renderTargets.push(_this._refractionTexture);
  44197. }
  44198. return _this._renderTargets;
  44199. };
  44200. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44201. return _this;
  44202. }
  44203. /**
  44204. * Attaches a new image processing configuration to the PBR Material.
  44205. * @param configuration
  44206. */
  44207. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44208. var _this = this;
  44209. if (configuration === this._imageProcessingConfiguration) {
  44210. return;
  44211. }
  44212. // Detaches observer.
  44213. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44214. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44215. }
  44216. // Pick the scene configuration if needed.
  44217. if (!configuration) {
  44218. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44219. }
  44220. else {
  44221. this._imageProcessingConfiguration = configuration;
  44222. }
  44223. // Attaches observer.
  44224. if (this._imageProcessingConfiguration) {
  44225. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44226. _this._markAllSubMeshesAsImageProcessingDirty();
  44227. });
  44228. }
  44229. };
  44230. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  44231. /**
  44232. * Gets a boolean indicating that current material needs to register RTT
  44233. */
  44234. get: function () {
  44235. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44236. return true;
  44237. }
  44238. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44239. return true;
  44240. }
  44241. return false;
  44242. },
  44243. enumerable: true,
  44244. configurable: true
  44245. });
  44246. /**
  44247. * Gets the name of the material class.
  44248. */
  44249. PBRBaseMaterial.prototype.getClassName = function () {
  44250. return "PBRBaseMaterial";
  44251. };
  44252. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44253. /**
  44254. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44255. */
  44256. get: function () {
  44257. return this._useLogarithmicDepth;
  44258. },
  44259. /**
  44260. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44261. */
  44262. set: function (value) {
  44263. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44264. },
  44265. enumerable: true,
  44266. configurable: true
  44267. });
  44268. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44269. /**
  44270. * Gets the current transparency mode.
  44271. */
  44272. get: function () {
  44273. return this._transparencyMode;
  44274. },
  44275. /**
  44276. * Sets the transparency mode of the material.
  44277. *
  44278. * | Value | Type | Description |
  44279. * | ----- | ----------------------------------- | ----------- |
  44280. * | 0 | OPAQUE | |
  44281. * | 1 | ALPHATEST | |
  44282. * | 2 | ALPHABLEND | |
  44283. * | 3 | ALPHATESTANDBLEND | |
  44284. *
  44285. */
  44286. set: function (value) {
  44287. if (this._transparencyMode === value) {
  44288. return;
  44289. }
  44290. this._transparencyMode = value;
  44291. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44292. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44293. },
  44294. enumerable: true,
  44295. configurable: true
  44296. });
  44297. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44298. /**
  44299. * Returns true if alpha blending should be disabled.
  44300. */
  44301. get: function () {
  44302. return (this._linkRefractionWithTransparency ||
  44303. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44304. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44305. },
  44306. enumerable: true,
  44307. configurable: true
  44308. });
  44309. /**
  44310. * Specifies whether or not this material should be rendered in alpha blend mode.
  44311. */
  44312. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44313. if (this._disableAlphaBlending) {
  44314. return false;
  44315. }
  44316. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44317. };
  44318. /**
  44319. * Specifies if the mesh will require alpha blending.
  44320. * @param mesh - BJS mesh.
  44321. */
  44322. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44323. if (this._disableAlphaBlending) {
  44324. return false;
  44325. }
  44326. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44327. };
  44328. /**
  44329. * Specifies whether or not this material should be rendered in alpha test mode.
  44330. */
  44331. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44332. if (this._forceAlphaTest) {
  44333. return true;
  44334. }
  44335. if (this._linkRefractionWithTransparency) {
  44336. return false;
  44337. }
  44338. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44339. };
  44340. /**
  44341. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44342. */
  44343. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44344. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44345. };
  44346. /**
  44347. * Gets the texture used for the alpha test.
  44348. */
  44349. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44350. return this._albedoTexture;
  44351. };
  44352. /**
  44353. * Specifies that the submesh is ready to be used.
  44354. * @param mesh - BJS mesh.
  44355. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44356. * @param useInstances - Specifies that instances should be used.
  44357. * @returns - boolean indicating that the submesh is ready or not.
  44358. */
  44359. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44360. if (subMesh.effect && this.isFrozen) {
  44361. if (this._wasPreviouslyReady) {
  44362. return true;
  44363. }
  44364. }
  44365. if (!subMesh._materialDefines) {
  44366. subMesh._materialDefines = new PBRMaterialDefines();
  44367. }
  44368. var defines = subMesh._materialDefines;
  44369. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44370. if (defines._renderId === this.getScene().getRenderId()) {
  44371. return true;
  44372. }
  44373. }
  44374. var scene = this.getScene();
  44375. var engine = scene.getEngine();
  44376. if (defines._areTexturesDirty) {
  44377. if (scene.texturesEnabled) {
  44378. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44379. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44380. return false;
  44381. }
  44382. }
  44383. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44384. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44385. return false;
  44386. }
  44387. }
  44388. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44389. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44390. return false;
  44391. }
  44392. }
  44393. var reflectionTexture = this._getReflectionTexture();
  44394. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44395. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44396. return false;
  44397. }
  44398. }
  44399. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44400. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44401. return false;
  44402. }
  44403. }
  44404. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44405. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44406. return false;
  44407. }
  44408. }
  44409. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44410. if (this._metallicTexture) {
  44411. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44412. return false;
  44413. }
  44414. }
  44415. else if (this._reflectivityTexture) {
  44416. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44417. return false;
  44418. }
  44419. }
  44420. if (this._microSurfaceTexture) {
  44421. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44422. return false;
  44423. }
  44424. }
  44425. }
  44426. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44427. // Bump texture cannot be not blocking.
  44428. if (!this._bumpTexture.isReady()) {
  44429. return false;
  44430. }
  44431. }
  44432. var refractionTexture = this._getRefractionTexture();
  44433. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44434. if (!refractionTexture.isReadyOrNotBlocking()) {
  44435. return false;
  44436. }
  44437. }
  44438. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44439. // This is blocking.
  44440. if (!this._environmentBRDFTexture.isReady()) {
  44441. return false;
  44442. }
  44443. }
  44444. }
  44445. }
  44446. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44447. if (!this._imageProcessingConfiguration.isReady()) {
  44448. return false;
  44449. }
  44450. }
  44451. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44452. mesh.createNormals(true);
  44453. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44454. }
  44455. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44456. if (effect) {
  44457. scene.resetCachedMaterial();
  44458. subMesh.setEffect(effect, defines);
  44459. this.buildUniformLayout();
  44460. }
  44461. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44462. return false;
  44463. }
  44464. defines._renderId = scene.getRenderId();
  44465. this._wasPreviouslyReady = true;
  44466. return true;
  44467. };
  44468. /**
  44469. * Specifies if the material uses metallic roughness workflow.
  44470. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44471. */
  44472. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44473. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44474. return true;
  44475. }
  44476. return false;
  44477. };
  44478. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44479. if (onCompiled === void 0) { onCompiled = null; }
  44480. if (onError === void 0) { onError = null; }
  44481. if (useInstances === void 0) { useInstances = null; }
  44482. if (useClipPlane === void 0) { useClipPlane = null; }
  44483. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44484. if (!defines.isDirty) {
  44485. return null;
  44486. }
  44487. defines.markAsProcessed();
  44488. var scene = this.getScene();
  44489. var engine = scene.getEngine();
  44490. // Fallbacks
  44491. var fallbacks = new BABYLON.EffectFallbacks();
  44492. var fallbackRank = 0;
  44493. if (defines.USESPHERICALINVERTEX) {
  44494. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44495. }
  44496. if (defines.FOG) {
  44497. fallbacks.addFallback(fallbackRank, "FOG");
  44498. }
  44499. if (defines.SPECULARAA) {
  44500. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44501. }
  44502. if (defines.POINTSIZE) {
  44503. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44504. }
  44505. if (defines.LOGARITHMICDEPTH) {
  44506. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44507. }
  44508. if (defines.PARALLAX) {
  44509. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44510. }
  44511. if (defines.PARALLAXOCCLUSION) {
  44512. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44513. }
  44514. if (defines.ENVIRONMENTBRDF) {
  44515. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44516. }
  44517. if (defines.TANGENT) {
  44518. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44519. }
  44520. if (defines.BUMP) {
  44521. fallbacks.addFallback(fallbackRank++, "BUMP");
  44522. }
  44523. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44524. if (defines.SPECULARTERM) {
  44525. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44526. }
  44527. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44528. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44529. }
  44530. if (defines.LIGHTMAP) {
  44531. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44532. }
  44533. if (defines.NORMAL) {
  44534. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44535. }
  44536. if (defines.AMBIENT) {
  44537. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44538. }
  44539. if (defines.EMISSIVE) {
  44540. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44541. }
  44542. if (defines.VERTEXCOLOR) {
  44543. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44544. }
  44545. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44546. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44547. }
  44548. if (defines.MORPHTARGETS) {
  44549. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44550. }
  44551. //Attributes
  44552. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44553. if (defines.NORMAL) {
  44554. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44555. }
  44556. if (defines.TANGENT) {
  44557. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44558. }
  44559. if (defines.UV1) {
  44560. attribs.push(BABYLON.VertexBuffer.UVKind);
  44561. }
  44562. if (defines.UV2) {
  44563. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44564. }
  44565. if (defines.VERTEXCOLOR) {
  44566. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44567. }
  44568. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44569. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44570. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44571. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44572. "vFogInfos", "vFogColor", "pointSize",
  44573. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44574. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44575. "mBones",
  44576. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44577. "vLightingIntensity",
  44578. "logarithmicDepthConstant",
  44579. "vSphericalX", "vSphericalY", "vSphericalZ",
  44580. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44581. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44582. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44583. "vTangentSpaceParams"
  44584. ];
  44585. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44586. "bumpSampler", "lightmapSampler", "opacitySampler",
  44587. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44588. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44589. "microSurfaceSampler", "environmentBrdfSampler"];
  44590. var uniformBuffers = ["Material", "Scene"];
  44591. if (BABYLON.ImageProcessingConfiguration) {
  44592. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44593. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44594. }
  44595. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44596. uniformsNames: uniforms,
  44597. uniformBuffersNames: uniformBuffers,
  44598. samplers: samplers,
  44599. defines: defines,
  44600. maxSimultaneousLights: this._maxSimultaneousLights
  44601. });
  44602. var join = defines.toString();
  44603. return engine.createEffect("pbr", {
  44604. attributes: attribs,
  44605. uniformsNames: uniforms,
  44606. uniformBuffersNames: uniformBuffers,
  44607. samplers: samplers,
  44608. defines: join,
  44609. fallbacks: fallbacks,
  44610. onCompiled: onCompiled,
  44611. onError: onError,
  44612. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44613. }, engine);
  44614. };
  44615. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44616. if (useInstances === void 0) { useInstances = null; }
  44617. if (useClipPlane === void 0) { useClipPlane = null; }
  44618. var scene = this.getScene();
  44619. var engine = scene.getEngine();
  44620. // Lights
  44621. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44622. defines._needNormals = true;
  44623. // Textures
  44624. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44625. if (defines._areTexturesDirty) {
  44626. defines._needUVs = false;
  44627. if (scene.texturesEnabled) {
  44628. if (scene.getEngine().getCaps().textureLOD) {
  44629. defines.LODBASEDMICROSFURACE = true;
  44630. }
  44631. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44632. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44633. }
  44634. else {
  44635. defines.ALBEDO = false;
  44636. }
  44637. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44638. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44639. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44640. }
  44641. else {
  44642. defines.AMBIENT = false;
  44643. }
  44644. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44645. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44646. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44647. }
  44648. else {
  44649. defines.OPACITY = false;
  44650. }
  44651. var reflectionTexture = this._getReflectionTexture();
  44652. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44653. defines.REFLECTION = true;
  44654. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44655. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44656. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44657. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44658. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44659. defines.INVERTCUBICMAP = true;
  44660. }
  44661. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44662. switch (reflectionTexture.coordinatesMode) {
  44663. case BABYLON.Texture.EXPLICIT_MODE:
  44664. defines.REFLECTIONMAP_EXPLICIT = true;
  44665. break;
  44666. case BABYLON.Texture.PLANAR_MODE:
  44667. defines.REFLECTIONMAP_PLANAR = true;
  44668. break;
  44669. case BABYLON.Texture.PROJECTION_MODE:
  44670. defines.REFLECTIONMAP_PROJECTION = true;
  44671. break;
  44672. case BABYLON.Texture.SKYBOX_MODE:
  44673. defines.REFLECTIONMAP_SKYBOX = true;
  44674. break;
  44675. case BABYLON.Texture.SPHERICAL_MODE:
  44676. defines.REFLECTIONMAP_SPHERICAL = true;
  44677. break;
  44678. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44679. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44680. break;
  44681. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44682. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44683. break;
  44684. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44685. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44686. break;
  44687. case BABYLON.Texture.CUBIC_MODE:
  44688. case BABYLON.Texture.INVCUBIC_MODE:
  44689. default:
  44690. defines.REFLECTIONMAP_CUBIC = true;
  44691. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44692. break;
  44693. }
  44694. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44695. if (reflectionTexture.sphericalPolynomial) {
  44696. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44697. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44698. defines.USESPHERICALINVERTEX = false;
  44699. }
  44700. else {
  44701. defines.USESPHERICALINVERTEX = true;
  44702. }
  44703. }
  44704. }
  44705. else {
  44706. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44707. }
  44708. }
  44709. else {
  44710. defines.REFLECTION = false;
  44711. defines.REFLECTIONMAP_3D = false;
  44712. defines.REFLECTIONMAP_SPHERICAL = false;
  44713. defines.REFLECTIONMAP_PLANAR = false;
  44714. defines.REFLECTIONMAP_CUBIC = false;
  44715. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44716. defines.REFLECTIONMAP_PROJECTION = false;
  44717. defines.REFLECTIONMAP_SKYBOX = false;
  44718. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44719. defines.REFLECTIONMAP_EXPLICIT = false;
  44720. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44721. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44722. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44723. defines.INVERTCUBICMAP = false;
  44724. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44725. defines.USESPHERICALINVERTEX = false;
  44726. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44727. defines.LODINREFLECTIONALPHA = false;
  44728. defines.GAMMAREFLECTION = false;
  44729. defines.RGBDREFLECTION = false;
  44730. }
  44731. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44732. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44733. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44734. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44735. }
  44736. else {
  44737. defines.LIGHTMAP = false;
  44738. }
  44739. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44740. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44741. }
  44742. else {
  44743. defines.EMISSIVE = false;
  44744. }
  44745. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44746. if (this._metallicTexture) {
  44747. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44748. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44749. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44750. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44751. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44752. }
  44753. else if (this._reflectivityTexture) {
  44754. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44755. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44756. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44757. }
  44758. else {
  44759. defines.REFLECTIVITY = false;
  44760. }
  44761. if (this._microSurfaceTexture) {
  44762. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44763. }
  44764. else {
  44765. defines.MICROSURFACEMAP = false;
  44766. }
  44767. }
  44768. else {
  44769. defines.REFLECTIVITY = false;
  44770. defines.MICROSURFACEMAP = false;
  44771. }
  44772. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44773. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44774. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44775. defines.PARALLAX = true;
  44776. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44777. }
  44778. else {
  44779. defines.PARALLAX = false;
  44780. }
  44781. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44782. }
  44783. else {
  44784. defines.BUMP = false;
  44785. }
  44786. var refractionTexture = this._getRefractionTexture();
  44787. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44788. defines.REFRACTION = true;
  44789. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44790. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44791. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44792. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44793. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44794. if (this._linkRefractionWithTransparency) {
  44795. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44796. }
  44797. }
  44798. else {
  44799. defines.REFRACTION = false;
  44800. }
  44801. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44802. defines.ENVIRONMENTBRDF = true;
  44803. }
  44804. else {
  44805. defines.ENVIRONMENTBRDF = false;
  44806. }
  44807. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44808. defines.ALPHAFROMALBEDO = true;
  44809. }
  44810. else {
  44811. defines.ALPHAFROMALBEDO = false;
  44812. }
  44813. }
  44814. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44815. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44816. defines.USEPHYSICALLIGHTFALLOFF = false;
  44817. defines.USEGLTFLIGHTFALLOFF = false;
  44818. }
  44819. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44820. defines.USEPHYSICALLIGHTFALLOFF = false;
  44821. defines.USEGLTFLIGHTFALLOFF = true;
  44822. }
  44823. else {
  44824. defines.USEPHYSICALLIGHTFALLOFF = true;
  44825. defines.USEGLTFLIGHTFALLOFF = false;
  44826. }
  44827. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44828. if (!this.backFaceCulling && this._twoSidedLighting) {
  44829. defines.TWOSIDEDLIGHTING = true;
  44830. }
  44831. else {
  44832. defines.TWOSIDEDLIGHTING = false;
  44833. }
  44834. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44835. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44836. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44837. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44838. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44839. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44840. }
  44841. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44842. this._imageProcessingConfiguration.prepareDefines(defines);
  44843. }
  44844. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44845. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44846. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44847. // Misc.
  44848. if (defines._areMiscDirty) {
  44849. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44850. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44851. }
  44852. // Values that need to be evaluated on every frame
  44853. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44854. // Attribs
  44855. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44856. };
  44857. /**
  44858. * Force shader compilation
  44859. */
  44860. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44861. var _this = this;
  44862. var localOptions = __assign({ clipPlane: false }, options);
  44863. var defines = new PBRMaterialDefines();
  44864. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44865. if (effect.isReady()) {
  44866. if (onCompiled) {
  44867. onCompiled(this);
  44868. }
  44869. }
  44870. else {
  44871. effect.onCompileObservable.add(function () {
  44872. if (onCompiled) {
  44873. onCompiled(_this);
  44874. }
  44875. });
  44876. }
  44877. };
  44878. /**
  44879. * Initializes the uniform buffer layout for the shader.
  44880. */
  44881. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44882. // Order is important !
  44883. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44884. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44885. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44886. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44887. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44888. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44889. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44890. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44891. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44892. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44893. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44894. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44895. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44896. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44897. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44898. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44899. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44900. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44901. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44902. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44903. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44904. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44905. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44906. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44907. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44908. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44909. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44910. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44911. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44912. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44913. this._uniformBuffer.addUniform("pointSize", 1);
  44914. this._uniformBuffer.create();
  44915. };
  44916. /**
  44917. * Unbinds the textures.
  44918. */
  44919. PBRBaseMaterial.prototype.unbind = function () {
  44920. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44921. this._uniformBuffer.setTexture("reflectionSampler", null);
  44922. }
  44923. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44924. this._uniformBuffer.setTexture("refractionSampler", null);
  44925. }
  44926. _super.prototype.unbind.call(this);
  44927. };
  44928. /**
  44929. * Binds the submesh data.
  44930. * @param world - The world matrix.
  44931. * @param mesh - The BJS mesh.
  44932. * @param subMesh - A submesh of the BJS mesh.
  44933. */
  44934. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44935. var scene = this.getScene();
  44936. var defines = subMesh._materialDefines;
  44937. if (!defines) {
  44938. return;
  44939. }
  44940. var effect = subMesh.effect;
  44941. if (!effect) {
  44942. return;
  44943. }
  44944. this._activeEffect = effect;
  44945. // Matrices
  44946. this.bindOnlyWorldMatrix(world);
  44947. // Normal Matrix
  44948. if (defines.OBJECTSPACE_NORMALMAP) {
  44949. world.toNormalMatrix(this._normalMatrix);
  44950. this.bindOnlyNormalMatrix(this._normalMatrix);
  44951. }
  44952. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44953. // Bones
  44954. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44955. var reflectionTexture = null;
  44956. if (mustRebind) {
  44957. this._uniformBuffer.bindToEffect(effect, "Material");
  44958. this.bindViewProjection(effect);
  44959. reflectionTexture = this._getReflectionTexture();
  44960. var refractionTexture = this._getRefractionTexture();
  44961. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44962. // Texture uniforms
  44963. if (scene.texturesEnabled) {
  44964. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44965. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44966. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44967. }
  44968. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44969. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44970. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44971. }
  44972. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44973. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44974. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44975. }
  44976. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44977. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44978. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44979. if (reflectionTexture.boundingBoxSize) {
  44980. var cubeTexture = reflectionTexture;
  44981. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44982. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44983. }
  44984. var polynomials = reflectionTexture.sphericalPolynomial;
  44985. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44986. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44987. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44988. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44989. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44990. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44991. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44992. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44993. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44994. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44995. }
  44996. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44997. }
  44998. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44999. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45000. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45001. }
  45002. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45003. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45004. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45005. }
  45006. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45007. if (this._metallicTexture) {
  45008. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45009. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45010. }
  45011. else if (this._reflectivityTexture) {
  45012. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45013. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45014. }
  45015. if (this._microSurfaceTexture) {
  45016. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45017. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45018. }
  45019. }
  45020. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45021. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45022. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45023. if (scene._mirroredCameraPosition) {
  45024. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45025. }
  45026. else {
  45027. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45028. }
  45029. }
  45030. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45031. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45032. var depth = 1.0;
  45033. if (!refractionTexture.isCube) {
  45034. if (refractionTexture.depth) {
  45035. depth = refractionTexture.depth;
  45036. }
  45037. }
  45038. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45039. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45040. }
  45041. }
  45042. // Point size
  45043. if (this.pointsCloud) {
  45044. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45045. }
  45046. // Colors
  45047. if (defines.METALLICWORKFLOW) {
  45048. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45049. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45050. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45051. }
  45052. else {
  45053. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45054. }
  45055. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45056. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45057. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45058. // Misc
  45059. this._lightingInfos.x = this._directIntensity;
  45060. this._lightingInfos.y = this._emissiveIntensity;
  45061. this._lightingInfos.z = this._environmentIntensity;
  45062. this._lightingInfos.w = this._specularIntensity;
  45063. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45064. }
  45065. // Textures
  45066. if (scene.texturesEnabled) {
  45067. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45068. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45069. }
  45070. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45071. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45072. }
  45073. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45074. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45075. }
  45076. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45077. if (defines.LODBASEDMICROSFURACE) {
  45078. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45079. }
  45080. else {
  45081. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45082. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45083. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45084. }
  45085. }
  45086. if (defines.ENVIRONMENTBRDF) {
  45087. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45088. }
  45089. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45090. if (defines.LODBASEDMICROSFURACE) {
  45091. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45092. }
  45093. else {
  45094. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45095. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45096. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45097. }
  45098. }
  45099. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45100. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45101. }
  45102. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45103. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45104. }
  45105. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45106. if (this._metallicTexture) {
  45107. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45108. }
  45109. else if (this._reflectivityTexture) {
  45110. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45111. }
  45112. if (this._microSurfaceTexture) {
  45113. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45114. }
  45115. }
  45116. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45117. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45118. }
  45119. }
  45120. // Clip plane
  45121. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45122. // Colors
  45123. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45124. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45125. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45126. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45127. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45128. }
  45129. if (mustRebind || !this.isFrozen) {
  45130. // Lights
  45131. if (scene.lightsEnabled && !this._disableLighting) {
  45132. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  45133. }
  45134. // View
  45135. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45136. this.bindView(effect);
  45137. }
  45138. // Fog
  45139. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  45140. // Morph targets
  45141. if (defines.NUM_MORPH_INFLUENCERS) {
  45142. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45143. }
  45144. // image processing
  45145. this._imageProcessingConfiguration.bind(this._activeEffect);
  45146. // Log. depth
  45147. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45148. }
  45149. this._uniformBuffer.update();
  45150. this._afterBind(mesh, this._activeEffect);
  45151. };
  45152. /**
  45153. * Returns the animatable textures.
  45154. * @returns - Array of animatable textures.
  45155. */
  45156. PBRBaseMaterial.prototype.getAnimatables = function () {
  45157. var results = [];
  45158. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45159. results.push(this._albedoTexture);
  45160. }
  45161. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45162. results.push(this._ambientTexture);
  45163. }
  45164. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45165. results.push(this._opacityTexture);
  45166. }
  45167. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45168. results.push(this._reflectionTexture);
  45169. }
  45170. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45171. results.push(this._emissiveTexture);
  45172. }
  45173. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45174. results.push(this._metallicTexture);
  45175. }
  45176. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45177. results.push(this._reflectivityTexture);
  45178. }
  45179. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45180. results.push(this._bumpTexture);
  45181. }
  45182. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45183. results.push(this._lightmapTexture);
  45184. }
  45185. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45186. results.push(this._refractionTexture);
  45187. }
  45188. return results;
  45189. };
  45190. /**
  45191. * Returns the texture used for reflections.
  45192. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45193. */
  45194. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45195. if (this._reflectionTexture) {
  45196. return this._reflectionTexture;
  45197. }
  45198. return this.getScene().environmentTexture;
  45199. };
  45200. /**
  45201. * Returns the texture used for refraction or null if none is used.
  45202. * @returns - Refection texture if present. If no refraction texture and refraction
  45203. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45204. */
  45205. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45206. if (this._refractionTexture) {
  45207. return this._refractionTexture;
  45208. }
  45209. if (this._linkRefractionWithTransparency) {
  45210. return this.getScene().environmentTexture;
  45211. }
  45212. return null;
  45213. };
  45214. /**
  45215. * Disposes the resources of the material.
  45216. * @param forceDisposeEffect - Forces the disposal of effects.
  45217. * @param forceDisposeTextures - Forces the disposal of all textures.
  45218. */
  45219. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45220. if (forceDisposeTextures) {
  45221. if (this._albedoTexture) {
  45222. this._albedoTexture.dispose();
  45223. }
  45224. if (this._ambientTexture) {
  45225. this._ambientTexture.dispose();
  45226. }
  45227. if (this._opacityTexture) {
  45228. this._opacityTexture.dispose();
  45229. }
  45230. if (this._reflectionTexture) {
  45231. this._reflectionTexture.dispose();
  45232. }
  45233. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45234. this._environmentBRDFTexture.dispose();
  45235. }
  45236. if (this._emissiveTexture) {
  45237. this._emissiveTexture.dispose();
  45238. }
  45239. if (this._metallicTexture) {
  45240. this._metallicTexture.dispose();
  45241. }
  45242. if (this._reflectivityTexture) {
  45243. this._reflectivityTexture.dispose();
  45244. }
  45245. if (this._bumpTexture) {
  45246. this._bumpTexture.dispose();
  45247. }
  45248. if (this._lightmapTexture) {
  45249. this._lightmapTexture.dispose();
  45250. }
  45251. if (this._refractionTexture) {
  45252. this._refractionTexture.dispose();
  45253. }
  45254. }
  45255. this._renderTargets.dispose();
  45256. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45257. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45258. }
  45259. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45260. };
  45261. /**
  45262. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45263. */
  45264. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45265. /**
  45266. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45267. * to enhance interoperability with other engines.
  45268. */
  45269. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45270. /**
  45271. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45272. * to enhance interoperability with other materials.
  45273. */
  45274. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45275. /**
  45276. * Stores the reflectivity values based on metallic roughness workflow.
  45277. */
  45278. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45279. __decorate([
  45280. BABYLON.serializeAsImageProcessingConfiguration()
  45281. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45282. __decorate([
  45283. BABYLON.serialize()
  45284. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45285. __decorate([
  45286. BABYLON.serialize()
  45287. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45288. return PBRBaseMaterial;
  45289. }(BABYLON.PushMaterial));
  45290. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45291. })(BABYLON || (BABYLON = {}));
  45292. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45293. var BABYLON;
  45294. (function (BABYLON) {
  45295. /**
  45296. * The Physically based simple base material of BJS.
  45297. *
  45298. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45299. * It is used as the base class for both the specGloss and metalRough conventions.
  45300. */
  45301. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45302. __extends(PBRBaseSimpleMaterial, _super);
  45303. /**
  45304. * Instantiates a new PBRMaterial instance.
  45305. *
  45306. * @param name The material name
  45307. * @param scene The scene the material will be use in.
  45308. */
  45309. function PBRBaseSimpleMaterial(name, scene) {
  45310. var _this = _super.call(this, name, scene) || this;
  45311. /**
  45312. * Number of Simultaneous lights allowed on the material.
  45313. */
  45314. _this.maxSimultaneousLights = 4;
  45315. /**
  45316. * If sets to true, disables all the lights affecting the material.
  45317. */
  45318. _this.disableLighting = false;
  45319. /**
  45320. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45321. */
  45322. _this.invertNormalMapX = false;
  45323. /**
  45324. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45325. */
  45326. _this.invertNormalMapY = false;
  45327. /**
  45328. * Emissivie color used to self-illuminate the model.
  45329. */
  45330. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45331. /**
  45332. * Occlusion Channel Strenght.
  45333. */
  45334. _this.occlusionStrength = 1.0;
  45335. _this.useLightmapAsShadowmap = false;
  45336. _this._useAlphaFromAlbedoTexture = true;
  45337. _this._useAmbientInGrayScale = true;
  45338. return _this;
  45339. }
  45340. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45341. /**
  45342. * Gets the current double sided mode.
  45343. */
  45344. get: function () {
  45345. return this._twoSidedLighting;
  45346. },
  45347. /**
  45348. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45349. */
  45350. set: function (value) {
  45351. if (this._twoSidedLighting === value) {
  45352. return;
  45353. }
  45354. this._twoSidedLighting = value;
  45355. this.backFaceCulling = !value;
  45356. this._markAllSubMeshesAsTexturesDirty();
  45357. },
  45358. enumerable: true,
  45359. configurable: true
  45360. });
  45361. /**
  45362. * Return the active textures of the material.
  45363. */
  45364. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45365. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45366. if (this.environmentTexture) {
  45367. activeTextures.push(this.environmentTexture);
  45368. }
  45369. if (this.normalTexture) {
  45370. activeTextures.push(this.normalTexture);
  45371. }
  45372. if (this.emissiveTexture) {
  45373. activeTextures.push(this.emissiveTexture);
  45374. }
  45375. if (this.occlusionTexture) {
  45376. activeTextures.push(this.occlusionTexture);
  45377. }
  45378. if (this.lightmapTexture) {
  45379. activeTextures.push(this.lightmapTexture);
  45380. }
  45381. return activeTextures;
  45382. };
  45383. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45384. if (_super.prototype.hasTexture.call(this, texture)) {
  45385. return true;
  45386. }
  45387. if (this.lightmapTexture === texture) {
  45388. return true;
  45389. }
  45390. return false;
  45391. };
  45392. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45393. return "PBRBaseSimpleMaterial";
  45394. };
  45395. __decorate([
  45396. BABYLON.serialize(),
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45398. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45399. __decorate([
  45400. BABYLON.serialize(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45402. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45403. __decorate([
  45404. BABYLON.serializeAsTexture(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45406. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45407. __decorate([
  45408. BABYLON.serialize(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45411. __decorate([
  45412. BABYLON.serialize(),
  45413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45414. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45415. __decorate([
  45416. BABYLON.serializeAsTexture(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45418. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45419. __decorate([
  45420. BABYLON.serializeAsColor3("emissive"),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45422. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45423. __decorate([
  45424. BABYLON.serializeAsTexture(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45426. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45427. __decorate([
  45428. BABYLON.serialize(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45430. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45431. __decorate([
  45432. BABYLON.serializeAsTexture(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45434. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45435. __decorate([
  45436. BABYLON.serialize(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45438. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45439. __decorate([
  45440. BABYLON.serialize()
  45441. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45442. __decorate([
  45443. BABYLON.serializeAsTexture(),
  45444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45445. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45446. __decorate([
  45447. BABYLON.serialize(),
  45448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45449. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45450. return PBRBaseSimpleMaterial;
  45451. }(BABYLON.PBRBaseMaterial));
  45452. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45453. })(BABYLON || (BABYLON = {}));
  45454. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45455. var BABYLON;
  45456. (function (BABYLON) {
  45457. /**
  45458. * The Physically based material of BJS.
  45459. *
  45460. * This offers the main features of a standard PBR material.
  45461. * For more information, please refer to the documentation :
  45462. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45463. */
  45464. var PBRMaterial = /** @class */ (function (_super) {
  45465. __extends(PBRMaterial, _super);
  45466. /**
  45467. * Instantiates a new PBRMaterial instance.
  45468. *
  45469. * @param name The material name
  45470. * @param scene The scene the material will be use in.
  45471. */
  45472. function PBRMaterial(name, scene) {
  45473. var _this = _super.call(this, name, scene) || this;
  45474. /**
  45475. * Intensity of the direct lights e.g. the four lights available in your scene.
  45476. * This impacts both the direct diffuse and specular highlights.
  45477. */
  45478. _this.directIntensity = 1.0;
  45479. /**
  45480. * Intensity of the emissive part of the material.
  45481. * This helps controlling the emissive effect without modifying the emissive color.
  45482. */
  45483. _this.emissiveIntensity = 1.0;
  45484. /**
  45485. * Intensity of the environment e.g. how much the environment will light the object
  45486. * either through harmonics for rough material or through the refelction for shiny ones.
  45487. */
  45488. _this.environmentIntensity = 1.0;
  45489. /**
  45490. * This is a special control allowing the reduction of the specular highlights coming from the
  45491. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45492. */
  45493. _this.specularIntensity = 1.0;
  45494. /**
  45495. * Debug Control allowing disabling the bump map on this material.
  45496. */
  45497. _this.disableBumpMap = false;
  45498. /**
  45499. * AKA Occlusion Texture Intensity in other nomenclature.
  45500. */
  45501. _this.ambientTextureStrength = 1.0;
  45502. /**
  45503. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45504. * 1 means it completely occludes it
  45505. * 0 mean it has no impact
  45506. */
  45507. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45508. /**
  45509. * The color of a material in ambient lighting.
  45510. */
  45511. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45512. /**
  45513. * AKA Diffuse Color in other nomenclature.
  45514. */
  45515. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45516. /**
  45517. * AKA Specular Color in other nomenclature.
  45518. */
  45519. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45520. /**
  45521. * The color reflected from the material.
  45522. */
  45523. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45524. /**
  45525. * The color emitted from the material.
  45526. */
  45527. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45528. /**
  45529. * AKA Glossiness in other nomenclature.
  45530. */
  45531. _this.microSurface = 1.0;
  45532. /**
  45533. * source material index of refraction (IOR)' / 'destination material IOR.
  45534. */
  45535. _this.indexOfRefraction = 0.66;
  45536. /**
  45537. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45538. */
  45539. _this.invertRefractionY = false;
  45540. /**
  45541. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45542. * Materials half opaque for instance using refraction could benefit from this control.
  45543. */
  45544. _this.linkRefractionWithTransparency = false;
  45545. _this.useLightmapAsShadowmap = false;
  45546. /**
  45547. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45548. */
  45549. _this.useAlphaFromAlbedoTexture = false;
  45550. /**
  45551. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45552. */
  45553. _this.forceAlphaTest = false;
  45554. /**
  45555. * Defines the alpha limits in alpha test mode.
  45556. */
  45557. _this.alphaCutOff = 0.4;
  45558. /**
  45559. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45560. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45561. */
  45562. _this.useSpecularOverAlpha = true;
  45563. /**
  45564. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45565. */
  45566. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45567. /**
  45568. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45569. */
  45570. _this.useRoughnessFromMetallicTextureAlpha = true;
  45571. /**
  45572. * Specifies if the metallic texture contains the roughness information in its green channel.
  45573. */
  45574. _this.useRoughnessFromMetallicTextureGreen = false;
  45575. /**
  45576. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45577. */
  45578. _this.useMetallnessFromMetallicTextureBlue = false;
  45579. /**
  45580. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45581. */
  45582. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45583. /**
  45584. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45585. */
  45586. _this.useAmbientInGrayScale = false;
  45587. /**
  45588. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45589. * The material will try to infer what glossiness each pixel should be.
  45590. */
  45591. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45592. /**
  45593. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45594. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45595. */
  45596. _this.useRadianceOverAlpha = true;
  45597. /**
  45598. * Allows using an object space normal map (instead of tangent space).
  45599. */
  45600. _this.useObjectSpaceNormalMap = false;
  45601. /**
  45602. * Allows using the bump map in parallax mode.
  45603. */
  45604. _this.useParallax = false;
  45605. /**
  45606. * Allows using the bump map in parallax occlusion mode.
  45607. */
  45608. _this.useParallaxOcclusion = false;
  45609. /**
  45610. * Controls the scale bias of the parallax mode.
  45611. */
  45612. _this.parallaxScaleBias = 0.05;
  45613. /**
  45614. * If sets to true, disables all the lights affecting the material.
  45615. */
  45616. _this.disableLighting = false;
  45617. /**
  45618. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45619. */
  45620. _this.forceIrradianceInFragment = false;
  45621. /**
  45622. * Number of Simultaneous lights allowed on the material.
  45623. */
  45624. _this.maxSimultaneousLights = 4;
  45625. /**
  45626. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45627. */
  45628. _this.invertNormalMapX = false;
  45629. /**
  45630. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45631. */
  45632. _this.invertNormalMapY = false;
  45633. /**
  45634. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45635. */
  45636. _this.twoSidedLighting = false;
  45637. /**
  45638. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45639. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45640. */
  45641. _this.useAlphaFresnel = false;
  45642. /**
  45643. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45644. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45645. */
  45646. _this.useLinearAlphaFresnel = false;
  45647. /**
  45648. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45649. * And/Or occlude the blended part.
  45650. */
  45651. _this.environmentBRDFTexture = null;
  45652. /**
  45653. * Force normal to face away from face.
  45654. */
  45655. _this.forceNormalForward = false;
  45656. /**
  45657. * Enables specular anti aliasing in the PBR shader.
  45658. * It will both interacts on the Geometry for analytical and IBL lighting.
  45659. * It also prefilter the roughness map based on the bump values.
  45660. */
  45661. _this.enableSpecularAntiAliasing = false;
  45662. /**
  45663. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45664. * makes the reflect vector face the model (under horizon).
  45665. */
  45666. _this.useHorizonOcclusion = true;
  45667. /**
  45668. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45669. * too much the area relying on ambient texture to define their ambient occlusion.
  45670. */
  45671. _this.useRadianceOcclusion = true;
  45672. /**
  45673. * If set to true, no lighting calculations will be applied.
  45674. */
  45675. _this.unlit = false;
  45676. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45677. return _this;
  45678. }
  45679. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45680. /**
  45681. * BJS is using an harcoded light falloff based on a manually sets up range.
  45682. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45683. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45684. */
  45685. get: function () {
  45686. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45687. },
  45688. /**
  45689. * BJS is using an harcoded light falloff based on a manually sets up range.
  45690. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45691. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45692. */
  45693. set: function (value) {
  45694. if (value !== this.usePhysicalLightFalloff) {
  45695. // Ensure the effect will be rebuilt.
  45696. this._markAllSubMeshesAsTexturesDirty();
  45697. if (value) {
  45698. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45699. }
  45700. else {
  45701. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45702. }
  45703. }
  45704. },
  45705. enumerable: true,
  45706. configurable: true
  45707. });
  45708. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45709. /**
  45710. * In order to support the falloff compatibility with gltf, a special mode has been added
  45711. * to reproduce the gltf light falloff.
  45712. */
  45713. get: function () {
  45714. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45715. },
  45716. /**
  45717. * In order to support the falloff compatibility with gltf, a special mode has been added
  45718. * to reproduce the gltf light falloff.
  45719. */
  45720. set: function (value) {
  45721. if (value !== this.useGLTFLightFalloff) {
  45722. // Ensure the effect will be rebuilt.
  45723. this._markAllSubMeshesAsTexturesDirty();
  45724. if (value) {
  45725. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45726. }
  45727. else {
  45728. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45729. }
  45730. }
  45731. },
  45732. enumerable: true,
  45733. configurable: true
  45734. });
  45735. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45736. /**
  45737. * Gets the image processing configuration used either in this material.
  45738. */
  45739. get: function () {
  45740. return this._imageProcessingConfiguration;
  45741. },
  45742. /**
  45743. * Sets the Default image processing configuration used either in the this material.
  45744. *
  45745. * If sets to null, the scene one is in use.
  45746. */
  45747. set: function (value) {
  45748. this._attachImageProcessingConfiguration(value);
  45749. // Ensure the effect will be rebuilt.
  45750. this._markAllSubMeshesAsTexturesDirty();
  45751. },
  45752. enumerable: true,
  45753. configurable: true
  45754. });
  45755. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45756. /**
  45757. * Gets wether the color curves effect is enabled.
  45758. */
  45759. get: function () {
  45760. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45761. },
  45762. /**
  45763. * Sets wether the color curves effect is enabled.
  45764. */
  45765. set: function (value) {
  45766. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45767. },
  45768. enumerable: true,
  45769. configurable: true
  45770. });
  45771. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45772. /**
  45773. * Gets wether the color grading effect is enabled.
  45774. */
  45775. get: function () {
  45776. return this.imageProcessingConfiguration.colorGradingEnabled;
  45777. },
  45778. /**
  45779. * Gets wether the color grading effect is enabled.
  45780. */
  45781. set: function (value) {
  45782. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45783. },
  45784. enumerable: true,
  45785. configurable: true
  45786. });
  45787. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45788. /**
  45789. * Gets wether tonemapping is enabled or not.
  45790. */
  45791. get: function () {
  45792. return this._imageProcessingConfiguration.toneMappingEnabled;
  45793. },
  45794. /**
  45795. * Sets wether tonemapping is enabled or not
  45796. */
  45797. set: function (value) {
  45798. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45799. },
  45800. enumerable: true,
  45801. configurable: true
  45802. });
  45803. ;
  45804. ;
  45805. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45806. /**
  45807. * The camera exposure used on this material.
  45808. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45809. * This corresponds to a photographic exposure.
  45810. */
  45811. get: function () {
  45812. return this._imageProcessingConfiguration.exposure;
  45813. },
  45814. /**
  45815. * The camera exposure used on this material.
  45816. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45817. * This corresponds to a photographic exposure.
  45818. */
  45819. set: function (value) {
  45820. this._imageProcessingConfiguration.exposure = value;
  45821. },
  45822. enumerable: true,
  45823. configurable: true
  45824. });
  45825. ;
  45826. ;
  45827. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45828. /**
  45829. * Gets The camera contrast used on this material.
  45830. */
  45831. get: function () {
  45832. return this._imageProcessingConfiguration.contrast;
  45833. },
  45834. /**
  45835. * Sets The camera contrast used on this material.
  45836. */
  45837. set: function (value) {
  45838. this._imageProcessingConfiguration.contrast = value;
  45839. },
  45840. enumerable: true,
  45841. configurable: true
  45842. });
  45843. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45844. /**
  45845. * Gets the Color Grading 2D Lookup Texture.
  45846. */
  45847. get: function () {
  45848. return this._imageProcessingConfiguration.colorGradingTexture;
  45849. },
  45850. /**
  45851. * Sets the Color Grading 2D Lookup Texture.
  45852. */
  45853. set: function (value) {
  45854. this._imageProcessingConfiguration.colorGradingTexture = value;
  45855. },
  45856. enumerable: true,
  45857. configurable: true
  45858. });
  45859. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45860. /**
  45861. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45862. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45863. * 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;
  45864. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45865. */
  45866. get: function () {
  45867. return this._imageProcessingConfiguration.colorCurves;
  45868. },
  45869. /**
  45870. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45871. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45872. * 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;
  45873. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45874. */
  45875. set: function (value) {
  45876. this._imageProcessingConfiguration.colorCurves = value;
  45877. },
  45878. enumerable: true,
  45879. configurable: true
  45880. });
  45881. /**
  45882. * Returns the name of this material class.
  45883. */
  45884. PBRMaterial.prototype.getClassName = function () {
  45885. return "PBRMaterial";
  45886. };
  45887. /**
  45888. * Returns an array of the actively used textures.
  45889. * @returns - Array of BaseTextures
  45890. */
  45891. PBRMaterial.prototype.getActiveTextures = function () {
  45892. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45893. if (this._albedoTexture) {
  45894. activeTextures.push(this._albedoTexture);
  45895. }
  45896. if (this._ambientTexture) {
  45897. activeTextures.push(this._ambientTexture);
  45898. }
  45899. if (this._opacityTexture) {
  45900. activeTextures.push(this._opacityTexture);
  45901. }
  45902. if (this._reflectionTexture) {
  45903. activeTextures.push(this._reflectionTexture);
  45904. }
  45905. if (this._emissiveTexture) {
  45906. activeTextures.push(this._emissiveTexture);
  45907. }
  45908. if (this._reflectivityTexture) {
  45909. activeTextures.push(this._reflectivityTexture);
  45910. }
  45911. if (this._metallicTexture) {
  45912. activeTextures.push(this._metallicTexture);
  45913. }
  45914. if (this._microSurfaceTexture) {
  45915. activeTextures.push(this._microSurfaceTexture);
  45916. }
  45917. if (this._bumpTexture) {
  45918. activeTextures.push(this._bumpTexture);
  45919. }
  45920. if (this._lightmapTexture) {
  45921. activeTextures.push(this._lightmapTexture);
  45922. }
  45923. if (this._refractionTexture) {
  45924. activeTextures.push(this._refractionTexture);
  45925. }
  45926. return activeTextures;
  45927. };
  45928. /**
  45929. * Checks to see if a texture is used in the material.
  45930. * @param texture - Base texture to use.
  45931. * @returns - Boolean specifying if a texture is used in the material.
  45932. */
  45933. PBRMaterial.prototype.hasTexture = function (texture) {
  45934. if (_super.prototype.hasTexture.call(this, texture)) {
  45935. return true;
  45936. }
  45937. if (this._albedoTexture === texture) {
  45938. return true;
  45939. }
  45940. if (this._ambientTexture === texture) {
  45941. return true;
  45942. }
  45943. if (this._opacityTexture === texture) {
  45944. return true;
  45945. }
  45946. if (this._reflectionTexture === texture) {
  45947. return true;
  45948. }
  45949. if (this._reflectivityTexture === texture) {
  45950. return true;
  45951. }
  45952. if (this._metallicTexture === texture) {
  45953. return true;
  45954. }
  45955. if (this._microSurfaceTexture === texture) {
  45956. return true;
  45957. }
  45958. if (this._bumpTexture === texture) {
  45959. return true;
  45960. }
  45961. if (this._lightmapTexture === texture) {
  45962. return true;
  45963. }
  45964. if (this._refractionTexture === texture) {
  45965. return true;
  45966. }
  45967. return false;
  45968. };
  45969. /**
  45970. * Makes a duplicate of the current material.
  45971. * @param name - name to use for the new material.
  45972. */
  45973. PBRMaterial.prototype.clone = function (name) {
  45974. var _this = this;
  45975. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45976. clone.id = name;
  45977. clone.name = name;
  45978. return clone;
  45979. };
  45980. /**
  45981. * Serializes this PBR Material.
  45982. * @returns - An object with the serialized material.
  45983. */
  45984. PBRMaterial.prototype.serialize = function () {
  45985. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45986. serializationObject.customType = "BABYLON.PBRMaterial";
  45987. return serializationObject;
  45988. };
  45989. // Statics
  45990. /**
  45991. * Parses a PBR Material from a serialized object.
  45992. * @param source - Serialized object.
  45993. * @param scene - BJS scene instance.
  45994. * @param rootUrl - url for the scene object
  45995. * @returns - PBRMaterial
  45996. */
  45997. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45998. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45999. };
  46000. /**
  46001. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46002. */
  46003. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  46004. /**
  46005. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46006. */
  46007. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  46008. /**
  46009. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46010. */
  46011. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  46012. /**
  46013. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46014. * They are also discarded below the alpha cutoff threshold to improve performances.
  46015. */
  46016. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46017. /**
  46018. * Defines the default value of how much AO map is occluding the analytical lights
  46019. * (point spot...).
  46020. */
  46021. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  46022. __decorate([
  46023. BABYLON.serialize(),
  46024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46025. ], PBRMaterial.prototype, "directIntensity", void 0);
  46026. __decorate([
  46027. BABYLON.serialize(),
  46028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46029. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46030. __decorate([
  46031. BABYLON.serialize(),
  46032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46033. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46034. __decorate([
  46035. BABYLON.serialize(),
  46036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46037. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46038. __decorate([
  46039. BABYLON.serialize(),
  46040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46041. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46042. __decorate([
  46043. BABYLON.serializeAsTexture(),
  46044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46045. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46046. __decorate([
  46047. BABYLON.serializeAsTexture(),
  46048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46049. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46050. __decorate([
  46051. BABYLON.serialize(),
  46052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46053. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46054. __decorate([
  46055. BABYLON.serialize(),
  46056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46057. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  46058. __decorate([
  46059. BABYLON.serializeAsTexture(),
  46060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46061. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46062. __decorate([
  46063. BABYLON.serializeAsTexture(),
  46064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46065. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46066. __decorate([
  46067. BABYLON.serializeAsTexture(),
  46068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46069. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46070. __decorate([
  46071. BABYLON.serializeAsTexture(),
  46072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46073. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46074. __decorate([
  46075. BABYLON.serializeAsTexture(),
  46076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46077. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46078. __decorate([
  46079. BABYLON.serialize(),
  46080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46081. ], PBRMaterial.prototype, "metallic", void 0);
  46082. __decorate([
  46083. BABYLON.serialize(),
  46084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46085. ], PBRMaterial.prototype, "roughness", void 0);
  46086. __decorate([
  46087. BABYLON.serializeAsTexture(),
  46088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46089. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46090. __decorate([
  46091. BABYLON.serializeAsTexture(),
  46092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46093. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46094. __decorate([
  46095. BABYLON.serializeAsTexture(),
  46096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46097. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46098. __decorate([
  46099. BABYLON.serializeAsTexture(),
  46100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46101. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46102. __decorate([
  46103. BABYLON.serializeAsColor3("ambient"),
  46104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46105. ], PBRMaterial.prototype, "ambientColor", void 0);
  46106. __decorate([
  46107. BABYLON.serializeAsColor3("albedo"),
  46108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46109. ], PBRMaterial.prototype, "albedoColor", void 0);
  46110. __decorate([
  46111. BABYLON.serializeAsColor3("reflectivity"),
  46112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46113. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46114. __decorate([
  46115. BABYLON.serializeAsColor3("reflection"),
  46116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46117. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46118. __decorate([
  46119. BABYLON.serializeAsColor3("emissive"),
  46120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46121. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46122. __decorate([
  46123. BABYLON.serialize(),
  46124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46125. ], PBRMaterial.prototype, "microSurface", void 0);
  46126. __decorate([
  46127. BABYLON.serialize(),
  46128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46129. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46130. __decorate([
  46131. BABYLON.serialize(),
  46132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46133. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46134. __decorate([
  46135. BABYLON.serialize(),
  46136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46137. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46138. __decorate([
  46139. BABYLON.serialize(),
  46140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46141. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46142. __decorate([
  46143. BABYLON.serialize(),
  46144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46145. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46146. __decorate([
  46147. BABYLON.serialize(),
  46148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46149. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46150. __decorate([
  46151. BABYLON.serialize(),
  46152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46153. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46154. __decorate([
  46155. BABYLON.serialize(),
  46156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46157. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46158. __decorate([
  46159. BABYLON.serialize(),
  46160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46161. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46162. __decorate([
  46163. BABYLON.serialize(),
  46164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46165. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46166. __decorate([
  46167. BABYLON.serialize(),
  46168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46169. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46170. __decorate([
  46171. BABYLON.serialize(),
  46172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46173. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46174. __decorate([
  46175. BABYLON.serialize(),
  46176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46177. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46178. __decorate([
  46179. BABYLON.serialize(),
  46180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46181. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46182. __decorate([
  46183. BABYLON.serialize(),
  46184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46185. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46186. __decorate([
  46187. BABYLON.serialize()
  46188. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  46189. __decorate([
  46190. BABYLON.serialize()
  46191. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  46192. __decorate([
  46193. BABYLON.serialize(),
  46194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46195. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46196. __decorate([
  46197. BABYLON.serialize(),
  46198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46199. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46200. __decorate([
  46201. BABYLON.serialize(),
  46202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46203. ], PBRMaterial.prototype, "useParallax", void 0);
  46204. __decorate([
  46205. BABYLON.serialize(),
  46206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46207. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46208. __decorate([
  46209. BABYLON.serialize(),
  46210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46211. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46212. __decorate([
  46213. BABYLON.serialize(),
  46214. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46215. ], PBRMaterial.prototype, "disableLighting", void 0);
  46216. __decorate([
  46217. BABYLON.serialize(),
  46218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46219. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46220. __decorate([
  46221. BABYLON.serialize(),
  46222. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46223. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46224. __decorate([
  46225. BABYLON.serialize(),
  46226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46227. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46228. __decorate([
  46229. BABYLON.serialize(),
  46230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46231. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46232. __decorate([
  46233. BABYLON.serialize(),
  46234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46235. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46236. __decorate([
  46237. BABYLON.serialize(),
  46238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46239. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46240. __decorate([
  46241. BABYLON.serialize(),
  46242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46243. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46244. __decorate([
  46245. BABYLON.serializeAsTexture(),
  46246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46247. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46248. __decorate([
  46249. BABYLON.serialize(),
  46250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46251. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46252. __decorate([
  46253. BABYLON.serialize(),
  46254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46255. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46256. __decorate([
  46257. BABYLON.serialize(),
  46258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46259. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46260. __decorate([
  46261. BABYLON.serialize(),
  46262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46263. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46264. __decorate([
  46265. BABYLON.serialize(),
  46266. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46267. ], PBRMaterial.prototype, "unlit", void 0);
  46268. return PBRMaterial;
  46269. }(BABYLON.PBRBaseMaterial));
  46270. BABYLON.PBRMaterial = PBRMaterial;
  46271. })(BABYLON || (BABYLON = {}));
  46272. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46273. var BABYLON;
  46274. (function (BABYLON) {
  46275. /**
  46276. * The PBR material of BJS following the metal roughness convention.
  46277. *
  46278. * This fits to the PBR convention in the GLTF definition:
  46279. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46280. */
  46281. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46282. __extends(PBRMetallicRoughnessMaterial, _super);
  46283. /**
  46284. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46285. *
  46286. * @param name The material name
  46287. * @param scene The scene the material will be use in.
  46288. */
  46289. function PBRMetallicRoughnessMaterial(name, scene) {
  46290. var _this = _super.call(this, name, scene) || this;
  46291. _this._useRoughnessFromMetallicTextureAlpha = false;
  46292. _this._useRoughnessFromMetallicTextureGreen = true;
  46293. _this._useMetallnessFromMetallicTextureBlue = true;
  46294. _this.metallic = 1.0;
  46295. _this.roughness = 1.0;
  46296. return _this;
  46297. }
  46298. /**
  46299. * Return the currrent class name of the material.
  46300. */
  46301. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46302. return "PBRMetallicRoughnessMaterial";
  46303. };
  46304. /**
  46305. * Return the active textures of the material.
  46306. */
  46307. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46308. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46309. if (this.baseTexture) {
  46310. activeTextures.push(this.baseTexture);
  46311. }
  46312. if (this.metallicRoughnessTexture) {
  46313. activeTextures.push(this.metallicRoughnessTexture);
  46314. }
  46315. return activeTextures;
  46316. };
  46317. /**
  46318. * Checks to see if a texture is used in the material.
  46319. * @param texture - Base texture to use.
  46320. * @returns - Boolean specifying if a texture is used in the material.
  46321. */
  46322. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46323. if (_super.prototype.hasTexture.call(this, texture)) {
  46324. return true;
  46325. }
  46326. if (this.baseTexture === texture) {
  46327. return true;
  46328. }
  46329. if (this.metallicRoughnessTexture === texture) {
  46330. return true;
  46331. }
  46332. return false;
  46333. };
  46334. /**
  46335. * Makes a duplicate of the current material.
  46336. * @param name - name to use for the new material.
  46337. */
  46338. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46339. var _this = this;
  46340. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46341. clone.id = name;
  46342. clone.name = name;
  46343. return clone;
  46344. };
  46345. /**
  46346. * Serialize the material to a parsable JSON object.
  46347. */
  46348. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46349. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46350. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46351. return serializationObject;
  46352. };
  46353. /**
  46354. * Parses a JSON object correponding to the serialize function.
  46355. */
  46356. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46357. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46358. };
  46359. __decorate([
  46360. BABYLON.serializeAsColor3(),
  46361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46362. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46363. __decorate([
  46364. BABYLON.serializeAsTexture(),
  46365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46366. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46367. __decorate([
  46368. BABYLON.serialize(),
  46369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46370. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46371. __decorate([
  46372. BABYLON.serialize(),
  46373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46374. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46375. __decorate([
  46376. BABYLON.serializeAsTexture(),
  46377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46378. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46379. return PBRMetallicRoughnessMaterial;
  46380. }(BABYLON.PBRBaseSimpleMaterial));
  46381. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46382. })(BABYLON || (BABYLON = {}));
  46383. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46384. var BABYLON;
  46385. (function (BABYLON) {
  46386. /**
  46387. * The PBR material of BJS following the specular glossiness convention.
  46388. *
  46389. * This fits to the PBR convention in the GLTF definition:
  46390. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46391. */
  46392. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46393. __extends(PBRSpecularGlossinessMaterial, _super);
  46394. /**
  46395. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46396. *
  46397. * @param name The material name
  46398. * @param scene The scene the material will be use in.
  46399. */
  46400. function PBRSpecularGlossinessMaterial(name, scene) {
  46401. var _this = _super.call(this, name, scene) || this;
  46402. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46403. return _this;
  46404. }
  46405. /**
  46406. * Return the currrent class name of the material.
  46407. */
  46408. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46409. return "PBRSpecularGlossinessMaterial";
  46410. };
  46411. /**
  46412. * Return the active textures of the material.
  46413. */
  46414. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46415. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46416. if (this.diffuseTexture) {
  46417. activeTextures.push(this.diffuseTexture);
  46418. }
  46419. if (this.specularGlossinessTexture) {
  46420. activeTextures.push(this.specularGlossinessTexture);
  46421. }
  46422. return activeTextures;
  46423. };
  46424. /**
  46425. * Checks to see if a texture is used in the material.
  46426. * @param texture - Base texture to use.
  46427. * @returns - Boolean specifying if a texture is used in the material.
  46428. */
  46429. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46430. if (_super.prototype.hasTexture.call(this, texture)) {
  46431. return true;
  46432. }
  46433. if (this.diffuseTexture === texture) {
  46434. return true;
  46435. }
  46436. if (this.specularGlossinessTexture === texture) {
  46437. return true;
  46438. }
  46439. return false;
  46440. };
  46441. /**
  46442. * Makes a duplicate of the current material.
  46443. * @param name - name to use for the new material.
  46444. */
  46445. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46446. var _this = this;
  46447. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46448. clone.id = name;
  46449. clone.name = name;
  46450. return clone;
  46451. };
  46452. /**
  46453. * Serialize the material to a parsable JSON object.
  46454. */
  46455. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46456. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46457. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46458. return serializationObject;
  46459. };
  46460. /**
  46461. * Parses a JSON object correponding to the serialize function.
  46462. */
  46463. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46464. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46465. };
  46466. __decorate([
  46467. BABYLON.serializeAsColor3("diffuse"),
  46468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46469. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46470. __decorate([
  46471. BABYLON.serializeAsTexture(),
  46472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46473. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46474. __decorate([
  46475. BABYLON.serializeAsColor3("specular"),
  46476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46477. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46478. __decorate([
  46479. BABYLON.serialize(),
  46480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46481. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46482. __decorate([
  46483. BABYLON.serializeAsTexture(),
  46484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46485. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46486. return PBRSpecularGlossinessMaterial;
  46487. }(BABYLON.PBRBaseSimpleMaterial));
  46488. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46489. })(BABYLON || (BABYLON = {}));
  46490. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46491. var BABYLON;
  46492. (function (BABYLON) {
  46493. /**
  46494. * This is a list of all the different input types that are available in the application.
  46495. * Fo instance: ArcRotateCameraGamepadInput...
  46496. */
  46497. BABYLON.CameraInputTypes = {};
  46498. /**
  46499. * This represents the input manager used within a camera.
  46500. * It helps dealing with all the different kind of input attached to a camera.
  46501. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46502. */
  46503. var CameraInputsManager = /** @class */ (function () {
  46504. /**
  46505. * Instantiate a new Camera Input Manager.
  46506. * @param camera Defines the camera the input manager blongs to
  46507. */
  46508. function CameraInputsManager(camera) {
  46509. this.attached = {};
  46510. this.camera = camera;
  46511. this.checkInputs = function () { };
  46512. }
  46513. /**
  46514. * Add an input method to a camera
  46515. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46516. * @param input camera input method
  46517. */
  46518. CameraInputsManager.prototype.add = function (input) {
  46519. var type = input.getSimpleName();
  46520. if (this.attached[type]) {
  46521. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46522. return;
  46523. }
  46524. this.attached[type] = input;
  46525. input.camera = this.camera;
  46526. //for checkInputs, we are dynamically creating a function
  46527. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46528. if (input.checkInputs) {
  46529. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46530. }
  46531. if (this.attachedElement) {
  46532. input.attachControl(this.attachedElement);
  46533. }
  46534. };
  46535. /**
  46536. * Remove a specific input method from a camera
  46537. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46538. * @param inputToRemove camera input method
  46539. */
  46540. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46541. for (var cam in this.attached) {
  46542. var input = this.attached[cam];
  46543. if (input === inputToRemove) {
  46544. input.detachControl(this.attachedElement);
  46545. input.camera = null;
  46546. delete this.attached[cam];
  46547. this.rebuildInputCheck();
  46548. }
  46549. }
  46550. };
  46551. /**
  46552. * Remove a specific input type from a camera
  46553. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  46554. * @param inputType the type of the input to remove
  46555. */
  46556. CameraInputsManager.prototype.removeByType = function (inputType) {
  46557. for (var cam in this.attached) {
  46558. var input = this.attached[cam];
  46559. if (input.getClassName() === inputType) {
  46560. input.detachControl(this.attachedElement);
  46561. input.camera = null;
  46562. delete this.attached[cam];
  46563. this.rebuildInputCheck();
  46564. }
  46565. }
  46566. };
  46567. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46568. var current = this.checkInputs;
  46569. return function () {
  46570. current();
  46571. fn();
  46572. };
  46573. };
  46574. /**
  46575. * Attach the input controls to the currently attached dom element to listen the events from.
  46576. * @param input Defines the input to attach
  46577. */
  46578. CameraInputsManager.prototype.attachInput = function (input) {
  46579. if (this.attachedElement) {
  46580. input.attachControl(this.attachedElement, this.noPreventDefault);
  46581. }
  46582. };
  46583. /**
  46584. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  46585. * @param element Defines the dom element to collect the events from
  46586. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46587. */
  46588. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46589. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46590. if (this.attachedElement) {
  46591. return;
  46592. }
  46593. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46594. this.attachedElement = element;
  46595. this.noPreventDefault = noPreventDefault;
  46596. for (var cam in this.attached) {
  46597. this.attached[cam].attachControl(element, noPreventDefault);
  46598. }
  46599. };
  46600. /**
  46601. * Detach the current manager inputs controls from a specific dom element.
  46602. * @param element Defines the dom element to collect the events from
  46603. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  46604. */
  46605. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46606. if (disconnect === void 0) { disconnect = false; }
  46607. if (this.attachedElement !== element) {
  46608. return;
  46609. }
  46610. for (var cam in this.attached) {
  46611. this.attached[cam].detachControl(element);
  46612. if (disconnect) {
  46613. this.attached[cam].camera = null;
  46614. }
  46615. }
  46616. this.attachedElement = null;
  46617. };
  46618. /**
  46619. * Rebuild the dynamic inputCheck function from the current list of
  46620. * defined inputs in the manager.
  46621. */
  46622. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46623. this.checkInputs = function () { };
  46624. for (var cam in this.attached) {
  46625. var input = this.attached[cam];
  46626. if (input.checkInputs) {
  46627. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46628. }
  46629. }
  46630. };
  46631. /**
  46632. * Remove all attached input methods from a camera
  46633. */
  46634. CameraInputsManager.prototype.clear = function () {
  46635. if (this.attachedElement) {
  46636. this.detachElement(this.attachedElement, true);
  46637. }
  46638. this.attached = {};
  46639. this.attachedElement = null;
  46640. this.checkInputs = function () { };
  46641. };
  46642. /**
  46643. * Serialize the current input manager attached to a camera.
  46644. * This ensures than once parsed,
  46645. * the input associated to the camera will be identical to the current ones
  46646. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  46647. */
  46648. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46649. var inputs = {};
  46650. for (var cam in this.attached) {
  46651. var input = this.attached[cam];
  46652. var res = BABYLON.SerializationHelper.Serialize(input);
  46653. inputs[input.getClassName()] = res;
  46654. }
  46655. serializedCamera.inputsmgr = inputs;
  46656. };
  46657. /**
  46658. * Parses an input manager serialized JSON to restore the previous list of inputs
  46659. * and states associated to a camera.
  46660. * @param parsedCamera Defines the JSON to parse
  46661. */
  46662. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46663. var parsedInputs = parsedCamera.inputsmgr;
  46664. if (parsedInputs) {
  46665. this.clear();
  46666. for (var n in parsedInputs) {
  46667. var construct = BABYLON.CameraInputTypes[n];
  46668. if (construct) {
  46669. var parsedinput = parsedInputs[n];
  46670. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46671. this.add(input);
  46672. }
  46673. }
  46674. }
  46675. else {
  46676. //2016-03-08 this part is for managing backward compatibility
  46677. for (var n in this.attached) {
  46678. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46679. if (construct) {
  46680. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46681. this.remove(this.attached[n]);
  46682. this.add(input);
  46683. }
  46684. }
  46685. }
  46686. };
  46687. return CameraInputsManager;
  46688. }());
  46689. BABYLON.CameraInputsManager = CameraInputsManager;
  46690. })(BABYLON || (BABYLON = {}));
  46691. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46692. var BABYLON;
  46693. (function (BABYLON) {
  46694. /**
  46695. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  46696. * This is the base of the follow, arc rotate cameras and Free camera
  46697. * @see http://doc.babylonjs.com/features/cameras
  46698. */
  46699. var TargetCamera = /** @class */ (function (_super) {
  46700. __extends(TargetCamera, _super);
  46701. /**
  46702. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  46703. * This is the base of the follow, arc rotate cameras and Free camera
  46704. * @see http://doc.babylonjs.com/features/cameras
  46705. * @param name Defines the name of the camera in the scene
  46706. * @param position Defines the start position of the camera in the scene
  46707. * @param scene Defines the scene the camera belongs to
  46708. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  46709. */
  46710. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46711. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46712. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46713. /**
  46714. * Define the current direction the camera is moving to
  46715. */
  46716. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46717. /**
  46718. * Define the current rotation the camera is rotating to
  46719. */
  46720. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46721. /**
  46722. * Define the current rotation of the camera
  46723. */
  46724. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46725. /**
  46726. * Define the current speed of the camera
  46727. */
  46728. _this.speed = 2.0;
  46729. /**
  46730. * Add cconstraint to the camera to prevent it to move freely in all directions and
  46731. * around all axis.
  46732. */
  46733. _this.noRotationConstraint = false;
  46734. /**
  46735. * Define the current target of the camera as an object or a position.
  46736. */
  46737. _this.lockedTarget = null;
  46738. /** @hidden */
  46739. _this._currentTarget = BABYLON.Vector3.Zero();
  46740. /** @hidden */
  46741. _this._viewMatrix = BABYLON.Matrix.Zero();
  46742. /** @hidden */
  46743. _this._camMatrix = BABYLON.Matrix.Zero();
  46744. /** @hidden */
  46745. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46746. /** @hidden */
  46747. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46748. /** @hidden */
  46749. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46750. /** @hidden */
  46751. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46752. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46753. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46754. _this._defaultUp = BABYLON.Vector3.Up();
  46755. _this._cachedRotationZ = 0;
  46756. return _this;
  46757. }
  46758. /**
  46759. * Gets the position in front of the camera at a given distance.
  46760. * @param distance The distance from the camera we want the position to be
  46761. * @returns the position
  46762. */
  46763. TargetCamera.prototype.getFrontPosition = function (distance) {
  46764. this.getWorldMatrix();
  46765. var direction = this.getTarget().subtract(this.position);
  46766. direction.normalize();
  46767. direction.scaleInPlace(distance);
  46768. return this.globalPosition.add(direction);
  46769. };
  46770. /** @hidden */
  46771. TargetCamera.prototype._getLockedTargetPosition = function () {
  46772. if (!this.lockedTarget) {
  46773. return null;
  46774. }
  46775. if (this.lockedTarget.absolutePosition) {
  46776. this.lockedTarget.computeWorldMatrix();
  46777. }
  46778. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46779. };
  46780. /**
  46781. * Store current camera state of the camera (fov, position, rotation, etc..)
  46782. * @returns the camera
  46783. */
  46784. TargetCamera.prototype.storeState = function () {
  46785. this._storedPosition = this.position.clone();
  46786. this._storedRotation = this.rotation.clone();
  46787. if (this.rotationQuaternion) {
  46788. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46789. }
  46790. return _super.prototype.storeState.call(this);
  46791. };
  46792. /**
  46793. * Restored camera state. You must call storeState() first
  46794. * @returns whether it was successful or not
  46795. * @hidden
  46796. */
  46797. TargetCamera.prototype._restoreStateValues = function () {
  46798. if (!_super.prototype._restoreStateValues.call(this)) {
  46799. return false;
  46800. }
  46801. this.position = this._storedPosition.clone();
  46802. this.rotation = this._storedRotation.clone();
  46803. if (this.rotationQuaternion) {
  46804. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46805. }
  46806. this.cameraDirection.copyFromFloats(0, 0, 0);
  46807. this.cameraRotation.copyFromFloats(0, 0);
  46808. return true;
  46809. };
  46810. /** @hidden */
  46811. TargetCamera.prototype._initCache = function () {
  46812. _super.prototype._initCache.call(this);
  46813. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46814. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46815. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46816. };
  46817. /** @hidden */
  46818. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46819. if (!ignoreParentClass) {
  46820. _super.prototype._updateCache.call(this);
  46821. }
  46822. var lockedTargetPosition = this._getLockedTargetPosition();
  46823. if (!lockedTargetPosition) {
  46824. this._cache.lockedTarget = null;
  46825. }
  46826. else {
  46827. if (!this._cache.lockedTarget) {
  46828. this._cache.lockedTarget = lockedTargetPosition.clone();
  46829. }
  46830. else {
  46831. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46832. }
  46833. }
  46834. this._cache.rotation.copyFrom(this.rotation);
  46835. if (this.rotationQuaternion)
  46836. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46837. };
  46838. // Synchronized
  46839. /** @hidden */
  46840. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46841. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46842. return false;
  46843. }
  46844. var lockedTargetPosition = this._getLockedTargetPosition();
  46845. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46846. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46847. };
  46848. // Methods
  46849. /** @hidden */
  46850. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46851. var engine = this.getEngine();
  46852. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46853. };
  46854. // Target
  46855. /** @hidden */
  46856. TargetCamera.prototype.setTarget = function (target) {
  46857. this.upVector.normalize();
  46858. if (this.position.z === target.z) {
  46859. this.position.z += BABYLON.Epsilon;
  46860. }
  46861. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46862. this._camMatrix.invert();
  46863. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46864. var vDir = target.subtract(this.position);
  46865. if (vDir.x >= 0.0) {
  46866. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46867. }
  46868. else {
  46869. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46870. }
  46871. this.rotation.z = 0;
  46872. if (isNaN(this.rotation.x)) {
  46873. this.rotation.x = 0;
  46874. }
  46875. if (isNaN(this.rotation.y)) {
  46876. this.rotation.y = 0;
  46877. }
  46878. if (isNaN(this.rotation.z)) {
  46879. this.rotation.z = 0;
  46880. }
  46881. if (this.rotationQuaternion) {
  46882. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46883. }
  46884. };
  46885. /**
  46886. * Return the current target position of the camera. This value is expressed in local space.
  46887. * @returns the target position
  46888. */
  46889. TargetCamera.prototype.getTarget = function () {
  46890. return this._currentTarget;
  46891. };
  46892. /** @hidden */
  46893. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46894. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46895. };
  46896. /** @hidden */
  46897. TargetCamera.prototype._updatePosition = function () {
  46898. if (this.parent) {
  46899. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46900. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46901. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46902. return;
  46903. }
  46904. this.position.addInPlace(this.cameraDirection);
  46905. };
  46906. /** @hidden */
  46907. TargetCamera.prototype._checkInputs = function () {
  46908. var needToMove = this._decideIfNeedsToMove();
  46909. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46910. // Move
  46911. if (needToMove) {
  46912. this._updatePosition();
  46913. }
  46914. // Rotate
  46915. if (needToRotate) {
  46916. this.rotation.x += this.cameraRotation.x;
  46917. this.rotation.y += this.cameraRotation.y;
  46918. //rotate, if quaternion is set and rotation was used
  46919. if (this.rotationQuaternion) {
  46920. var len = this.rotation.lengthSquared();
  46921. if (len) {
  46922. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46923. }
  46924. }
  46925. if (!this.noRotationConstraint) {
  46926. var limit = (Math.PI / 2) * 0.95;
  46927. if (this.rotation.x > limit)
  46928. this.rotation.x = limit;
  46929. if (this.rotation.x < -limit)
  46930. this.rotation.x = -limit;
  46931. }
  46932. }
  46933. // Inertia
  46934. if (needToMove) {
  46935. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46936. this.cameraDirection.x = 0;
  46937. }
  46938. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46939. this.cameraDirection.y = 0;
  46940. }
  46941. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46942. this.cameraDirection.z = 0;
  46943. }
  46944. this.cameraDirection.scaleInPlace(this.inertia);
  46945. }
  46946. if (needToRotate) {
  46947. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46948. this.cameraRotation.x = 0;
  46949. }
  46950. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46951. this.cameraRotation.y = 0;
  46952. }
  46953. this.cameraRotation.scaleInPlace(this.inertia);
  46954. }
  46955. _super.prototype._checkInputs.call(this);
  46956. };
  46957. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46958. if (this.rotationQuaternion) {
  46959. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46960. }
  46961. else {
  46962. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46963. }
  46964. };
  46965. /**
  46966. * 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)
  46967. * @returns the current camera
  46968. */
  46969. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46970. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46971. return this;
  46972. };
  46973. /** @hidden */
  46974. TargetCamera.prototype._getViewMatrix = function () {
  46975. if (this.lockedTarget) {
  46976. this.setTarget(this._getLockedTargetPosition());
  46977. }
  46978. // Compute
  46979. this._updateCameraRotationMatrix();
  46980. // Apply the changed rotation to the upVector.
  46981. if (this._cachedRotationZ != this.rotation.z) {
  46982. this._rotateUpVectorWithCameraRotationMatrix();
  46983. this._cachedRotationZ = this.rotation.z;
  46984. }
  46985. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46986. // Computing target and final matrix
  46987. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46988. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46989. return this._viewMatrix;
  46990. };
  46991. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46992. if (this.parent) {
  46993. var parentWorldMatrix = this.parent.getWorldMatrix();
  46994. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46995. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46996. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46997. this._markSyncedWithParent();
  46998. }
  46999. else {
  47000. this._globalPosition.copyFrom(position);
  47001. this._globalCurrentTarget.copyFrom(target);
  47002. this._globalCurrentUpVector.copyFrom(up);
  47003. }
  47004. if (this.getScene().useRightHandedSystem) {
  47005. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47006. }
  47007. else {
  47008. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47009. }
  47010. };
  47011. /**
  47012. * @hidden
  47013. */
  47014. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47015. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47016. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47017. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47018. if (!this.rotationQuaternion) {
  47019. this.rotationQuaternion = new BABYLON.Quaternion();
  47020. }
  47021. rigCamera._cameraRigParams = {};
  47022. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47023. }
  47024. return rigCamera;
  47025. }
  47026. return null;
  47027. };
  47028. /**
  47029. * @hidden
  47030. */
  47031. TargetCamera.prototype._updateRigCameras = function () {
  47032. var camLeft = this._rigCameras[0];
  47033. var camRight = this._rigCameras[1];
  47034. switch (this.cameraRigMode) {
  47035. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47036. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47037. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47038. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47039. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47040. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47041. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47042. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47043. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47044. camLeft.setTarget(this.getTarget());
  47045. camRight.setTarget(this.getTarget());
  47046. break;
  47047. case BABYLON.Camera.RIG_MODE_VR:
  47048. if (camLeft.rotationQuaternion) {
  47049. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47050. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47051. }
  47052. else {
  47053. camLeft.rotation.copyFrom(this.rotation);
  47054. camRight.rotation.copyFrom(this.rotation);
  47055. }
  47056. camLeft.position.copyFrom(this.position);
  47057. camRight.position.copyFrom(this.position);
  47058. break;
  47059. }
  47060. _super.prototype._updateRigCameras.call(this);
  47061. };
  47062. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47063. if (!this._rigCamTransformMatrix) {
  47064. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47065. }
  47066. var target = this.getTarget();
  47067. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47068. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47069. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47070. };
  47071. /**
  47072. * Gets the current object class name.
  47073. * @return the class name
  47074. */
  47075. TargetCamera.prototype.getClassName = function () {
  47076. return "TargetCamera";
  47077. };
  47078. __decorate([
  47079. BABYLON.serializeAsVector3()
  47080. ], TargetCamera.prototype, "rotation", void 0);
  47081. __decorate([
  47082. BABYLON.serialize()
  47083. ], TargetCamera.prototype, "speed", void 0);
  47084. __decorate([
  47085. BABYLON.serializeAsMeshReference("lockedTargetId")
  47086. ], TargetCamera.prototype, "lockedTarget", void 0);
  47087. return TargetCamera;
  47088. }(BABYLON.Camera));
  47089. BABYLON.TargetCamera = TargetCamera;
  47090. })(BABYLON || (BABYLON = {}));
  47091. //# sourceMappingURL=babylon.targetCamera.js.map
  47092. var BABYLON;
  47093. (function (BABYLON) {
  47094. /**
  47095. * Manage the mouse inputs to control the movement of a free camera.
  47096. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47097. */
  47098. var FreeCameraMouseInput = /** @class */ (function () {
  47099. /**
  47100. * Manage the mouse inputs to control the movement of a free camera.
  47101. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47102. * @param touchEnabled Defines if touch is enabled or not
  47103. */
  47104. function FreeCameraMouseInput(
  47105. /**
  47106. * Define if touch is enabled in the mouse input
  47107. */
  47108. touchEnabled) {
  47109. if (touchEnabled === void 0) { touchEnabled = true; }
  47110. this.touchEnabled = touchEnabled;
  47111. /**
  47112. * Defines the buttons associated with the input to handle camera move.
  47113. */
  47114. this.buttons = [0, 1, 2];
  47115. /**
  47116. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  47117. */
  47118. this.angularSensibility = 2000.0;
  47119. this.previousPosition = null;
  47120. }
  47121. /**
  47122. * Attach the input controls to a specific dom element to get the input from.
  47123. * @param element Defines the element the controls should be listened from
  47124. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47125. */
  47126. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47127. var _this = this;
  47128. var engine = this.camera.getEngine();
  47129. if (!this._pointerInput) {
  47130. this._pointerInput = function (p, s) {
  47131. var evt = p.event;
  47132. if (engine.isInVRExclusivePointerMode) {
  47133. return;
  47134. }
  47135. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47136. return;
  47137. }
  47138. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47139. return;
  47140. }
  47141. var srcElement = (evt.srcElement || evt.target);
  47142. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47143. try {
  47144. srcElement.setPointerCapture(evt.pointerId);
  47145. }
  47146. catch (e) {
  47147. //Nothing to do with the error. Execution will continue.
  47148. }
  47149. _this.previousPosition = {
  47150. x: evt.clientX,
  47151. y: evt.clientY
  47152. };
  47153. if (!noPreventDefault) {
  47154. evt.preventDefault();
  47155. element.focus();
  47156. }
  47157. }
  47158. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47159. try {
  47160. srcElement.releasePointerCapture(evt.pointerId);
  47161. }
  47162. catch (e) {
  47163. //Nothing to do with the error.
  47164. }
  47165. _this.previousPosition = null;
  47166. if (!noPreventDefault) {
  47167. evt.preventDefault();
  47168. }
  47169. }
  47170. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47171. if (!_this.previousPosition || engine.isPointerLock) {
  47172. return;
  47173. }
  47174. var offsetX = evt.clientX - _this.previousPosition.x;
  47175. if (_this.camera.getScene().useRightHandedSystem)
  47176. offsetX *= -1;
  47177. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47178. offsetX *= -1;
  47179. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47180. var offsetY = evt.clientY - _this.previousPosition.y;
  47181. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47182. _this.previousPosition = {
  47183. x: evt.clientX,
  47184. y: evt.clientY
  47185. };
  47186. if (!noPreventDefault) {
  47187. evt.preventDefault();
  47188. }
  47189. }
  47190. };
  47191. }
  47192. this._onMouseMove = function (evt) {
  47193. if (!engine.isPointerLock) {
  47194. return;
  47195. }
  47196. if (engine.isInVRExclusivePointerMode) {
  47197. return;
  47198. }
  47199. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47200. if (_this.camera.getScene().useRightHandedSystem)
  47201. offsetX *= -1;
  47202. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47203. offsetX *= -1;
  47204. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47205. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47206. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47207. _this.previousPosition = null;
  47208. if (!noPreventDefault) {
  47209. evt.preventDefault();
  47210. }
  47211. };
  47212. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47213. element.addEventListener("mousemove", this._onMouseMove, false);
  47214. };
  47215. /**
  47216. * Detach the current controls from the specified dom element.
  47217. * @param element Defines the element to stop listening the inputs from
  47218. */
  47219. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47220. if (this._observer && element) {
  47221. this.camera.getScene().onPointerObservable.remove(this._observer);
  47222. if (this._onMouseMove) {
  47223. element.removeEventListener("mousemove", this._onMouseMove);
  47224. }
  47225. this._observer = null;
  47226. this._onMouseMove = null;
  47227. this.previousPosition = null;
  47228. }
  47229. };
  47230. /**
  47231. * Gets the class name of the current intput.
  47232. * @returns the class name
  47233. */
  47234. FreeCameraMouseInput.prototype.getClassName = function () {
  47235. return "FreeCameraMouseInput";
  47236. };
  47237. /**
  47238. * Get the friendly name associated with the input class.
  47239. * @returns the input friendly name
  47240. */
  47241. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47242. return "mouse";
  47243. };
  47244. __decorate([
  47245. BABYLON.serialize()
  47246. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47247. __decorate([
  47248. BABYLON.serialize()
  47249. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47250. return FreeCameraMouseInput;
  47251. }());
  47252. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47253. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47254. })(BABYLON || (BABYLON = {}));
  47255. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47256. var BABYLON;
  47257. (function (BABYLON) {
  47258. /**
  47259. * Manage the keyboard inputs to control the movement of a free camera.
  47260. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47261. */
  47262. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47263. function FreeCameraKeyboardMoveInput() {
  47264. /**
  47265. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47266. */
  47267. this.keysUp = [38];
  47268. /**
  47269. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47270. */
  47271. this.keysDown = [40];
  47272. /**
  47273. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47274. */
  47275. this.keysLeft = [37];
  47276. /**
  47277. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47278. */
  47279. this.keysRight = [39];
  47280. this._keys = new Array();
  47281. }
  47282. /**
  47283. * Attach the input controls to a specific dom element to get the input from.
  47284. * @param element Defines the element the controls should be listened from
  47285. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47286. */
  47287. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47288. var _this = this;
  47289. if (this._onCanvasBlurObserver) {
  47290. return;
  47291. }
  47292. this._scene = this.camera.getScene();
  47293. this._engine = this._scene.getEngine();
  47294. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47295. _this._keys = [];
  47296. });
  47297. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47298. var evt = info.event;
  47299. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47300. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47301. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47302. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47303. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47304. var index = _this._keys.indexOf(evt.keyCode);
  47305. if (index === -1) {
  47306. _this._keys.push(evt.keyCode);
  47307. }
  47308. if (!noPreventDefault) {
  47309. evt.preventDefault();
  47310. }
  47311. }
  47312. }
  47313. else {
  47314. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47315. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47316. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47317. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47318. var index = _this._keys.indexOf(evt.keyCode);
  47319. if (index >= 0) {
  47320. _this._keys.splice(index, 1);
  47321. }
  47322. if (!noPreventDefault) {
  47323. evt.preventDefault();
  47324. }
  47325. }
  47326. }
  47327. });
  47328. };
  47329. /**
  47330. * Detach the current controls from the specified dom element.
  47331. * @param element Defines the element to stop listening the inputs from
  47332. */
  47333. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47334. if (this._scene) {
  47335. if (this._onKeyboardObserver) {
  47336. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47337. }
  47338. if (this._onCanvasBlurObserver) {
  47339. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47340. }
  47341. this._onKeyboardObserver = null;
  47342. this._onCanvasBlurObserver = null;
  47343. }
  47344. this._keys = [];
  47345. };
  47346. /**
  47347. * Update the current camera state depending on the inputs that have been used this frame.
  47348. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47349. */
  47350. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47351. if (this._onKeyboardObserver) {
  47352. var camera = this.camera;
  47353. // Keyboard
  47354. for (var index = 0; index < this._keys.length; index++) {
  47355. var keyCode = this._keys[index];
  47356. var speed = camera._computeLocalCameraSpeed();
  47357. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47358. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47359. }
  47360. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47361. camera._localDirection.copyFromFloats(0, 0, speed);
  47362. }
  47363. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47364. camera._localDirection.copyFromFloats(speed, 0, 0);
  47365. }
  47366. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47367. camera._localDirection.copyFromFloats(0, 0, -speed);
  47368. }
  47369. if (camera.getScene().useRightHandedSystem) {
  47370. camera._localDirection.z *= -1;
  47371. }
  47372. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47373. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47374. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47375. }
  47376. }
  47377. };
  47378. /**
  47379. * Gets the class name of the current intput.
  47380. * @returns the class name
  47381. */
  47382. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47383. return "FreeCameraKeyboardMoveInput";
  47384. };
  47385. /** @hidden */
  47386. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47387. this._keys = [];
  47388. };
  47389. /**
  47390. * Get the friendly name associated with the input class.
  47391. * @returns the input friendly name
  47392. */
  47393. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47394. return "keyboard";
  47395. };
  47396. __decorate([
  47397. BABYLON.serialize()
  47398. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47399. __decorate([
  47400. BABYLON.serialize()
  47401. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47402. __decorate([
  47403. BABYLON.serialize()
  47404. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47405. __decorate([
  47406. BABYLON.serialize()
  47407. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47408. return FreeCameraKeyboardMoveInput;
  47409. }());
  47410. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47411. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47412. })(BABYLON || (BABYLON = {}));
  47413. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47414. var BABYLON;
  47415. (function (BABYLON) {
  47416. /**
  47417. * Default Inputs manager for the FreeCamera.
  47418. * It groups all the default supported inputs for ease of use.
  47419. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47420. */
  47421. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47422. __extends(FreeCameraInputsManager, _super);
  47423. /**
  47424. * Instantiates a new FreeCameraInputsManager.
  47425. * @param camera Defines the camera the inputs belong to
  47426. */
  47427. function FreeCameraInputsManager(camera) {
  47428. return _super.call(this, camera) || this;
  47429. }
  47430. /**
  47431. * Add keyboard input support to the input manager.
  47432. * @returns the current input manager
  47433. */
  47434. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47435. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47436. return this;
  47437. };
  47438. /**
  47439. * Add mouse input support to the input manager.
  47440. * @returns the current input manager
  47441. */
  47442. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47443. if (touchEnabled === void 0) { touchEnabled = true; }
  47444. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47445. return this;
  47446. };
  47447. /**
  47448. * Add orientation input support to the input manager.
  47449. * @returns the current input manager
  47450. */
  47451. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47452. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47453. return this;
  47454. };
  47455. /**
  47456. * Add touch input support to the input manager.
  47457. * @returns the current input manager
  47458. */
  47459. FreeCameraInputsManager.prototype.addTouch = function () {
  47460. this.add(new BABYLON.FreeCameraTouchInput());
  47461. return this;
  47462. };
  47463. /**
  47464. * Add virtual joystick input support to the input manager.
  47465. * @returns the current input manager
  47466. */
  47467. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47468. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47469. return this;
  47470. };
  47471. return FreeCameraInputsManager;
  47472. }(BABYLON.CameraInputsManager));
  47473. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47474. })(BABYLON || (BABYLON = {}));
  47475. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47476. var BABYLON;
  47477. (function (BABYLON) {
  47478. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47479. // Forcing to use the Universal camera
  47480. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47481. });
  47482. /**
  47483. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47484. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47485. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47486. */
  47487. var FreeCamera = /** @class */ (function (_super) {
  47488. __extends(FreeCamera, _super);
  47489. /**
  47490. * Instantiates a Free Camera.
  47491. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47492. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47493. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47494. * @param name Define the name of the camera in the scene
  47495. * @param position Define the start position of the camera in the scene
  47496. * @param scene Define the scene the camera belongs to
  47497. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47498. */
  47499. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47500. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47501. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47502. /**
  47503. * Define the collision ellipsoid of the camera.
  47504. * This is helpful to simulate a camera body like the player body around the camera
  47505. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47506. */
  47507. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47508. /**
  47509. * Define an offset for the position of the ellipsoid around the camera.
  47510. * This can be helpful to determine the center of the body near the gravity center of the body
  47511. * instead of its head.
  47512. */
  47513. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47514. /**
  47515. * Enable or disable collisions of the camera with the rest of the scene objects.
  47516. */
  47517. _this.checkCollisions = false;
  47518. /**
  47519. * Enable or disable gravity on the camera.
  47520. */
  47521. _this.applyGravity = false;
  47522. _this._needMoveForGravity = false;
  47523. _this._oldPosition = BABYLON.Vector3.Zero();
  47524. _this._diffPosition = BABYLON.Vector3.Zero();
  47525. _this._newPosition = BABYLON.Vector3.Zero();
  47526. // Collisions
  47527. _this._collisionMask = -1;
  47528. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47529. if (collidedMesh === void 0) { collidedMesh = null; }
  47530. //TODO move this to the collision coordinator!
  47531. if (_this.getScene().workerCollisions)
  47532. newPosition.multiplyInPlace(_this._collider._radius);
  47533. var updatePosition = function (newPos) {
  47534. _this._newPosition.copyFrom(newPos);
  47535. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47536. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47537. _this.position.addInPlace(_this._diffPosition);
  47538. if (_this.onCollide && collidedMesh) {
  47539. _this.onCollide(collidedMesh);
  47540. }
  47541. }
  47542. };
  47543. updatePosition(newPosition);
  47544. };
  47545. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47546. _this.inputs.addKeyboard().addMouse();
  47547. return _this;
  47548. }
  47549. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47550. /**
  47551. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47552. * Higher values reduce sensitivity.
  47553. */
  47554. get: function () {
  47555. var mouse = this.inputs.attached["mouse"];
  47556. if (mouse)
  47557. return mouse.angularSensibility;
  47558. return 0;
  47559. },
  47560. /**
  47561. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47562. * Higher values reduce sensitivity.
  47563. */
  47564. set: function (value) {
  47565. var mouse = this.inputs.attached["mouse"];
  47566. if (mouse)
  47567. mouse.angularSensibility = value;
  47568. },
  47569. enumerable: true,
  47570. configurable: true
  47571. });
  47572. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47573. /**
  47574. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47575. */
  47576. get: function () {
  47577. var keyboard = this.inputs.attached["keyboard"];
  47578. if (keyboard)
  47579. return keyboard.keysUp;
  47580. return [];
  47581. },
  47582. set: function (value) {
  47583. var keyboard = this.inputs.attached["keyboard"];
  47584. if (keyboard)
  47585. keyboard.keysUp = value;
  47586. },
  47587. enumerable: true,
  47588. configurable: true
  47589. });
  47590. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47591. /**
  47592. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47593. */
  47594. get: function () {
  47595. var keyboard = this.inputs.attached["keyboard"];
  47596. if (keyboard)
  47597. return keyboard.keysDown;
  47598. return [];
  47599. },
  47600. set: function (value) {
  47601. var keyboard = this.inputs.attached["keyboard"];
  47602. if (keyboard)
  47603. keyboard.keysDown = value;
  47604. },
  47605. enumerable: true,
  47606. configurable: true
  47607. });
  47608. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47609. /**
  47610. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47611. */
  47612. get: function () {
  47613. var keyboard = this.inputs.attached["keyboard"];
  47614. if (keyboard)
  47615. return keyboard.keysLeft;
  47616. return [];
  47617. },
  47618. set: function (value) {
  47619. var keyboard = this.inputs.attached["keyboard"];
  47620. if (keyboard)
  47621. keyboard.keysLeft = value;
  47622. },
  47623. enumerable: true,
  47624. configurable: true
  47625. });
  47626. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47627. /**
  47628. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47629. */
  47630. get: function () {
  47631. var keyboard = this.inputs.attached["keyboard"];
  47632. if (keyboard)
  47633. return keyboard.keysRight;
  47634. return [];
  47635. },
  47636. set: function (value) {
  47637. var keyboard = this.inputs.attached["keyboard"];
  47638. if (keyboard)
  47639. keyboard.keysRight = value;
  47640. },
  47641. enumerable: true,
  47642. configurable: true
  47643. });
  47644. /**
  47645. * Attached controls to the current camera.
  47646. * @param element Defines the element the controls should be listened from
  47647. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47648. */
  47649. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47650. this.inputs.attachElement(element, noPreventDefault);
  47651. };
  47652. /**
  47653. * Detach the current controls from the camera.
  47654. * The camera will stop reacting to inputs.
  47655. * @param element Defines the element to stop listening the inputs from
  47656. */
  47657. FreeCamera.prototype.detachControl = function (element) {
  47658. this.inputs.detachElement(element);
  47659. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47660. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47661. };
  47662. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47663. /**
  47664. * Define a collision mask to limit the list of object the camera can collide with
  47665. */
  47666. get: function () {
  47667. return this._collisionMask;
  47668. },
  47669. set: function (mask) {
  47670. this._collisionMask = !isNaN(mask) ? mask : -1;
  47671. },
  47672. enumerable: true,
  47673. configurable: true
  47674. });
  47675. /** @hidden */
  47676. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47677. var globalPosition;
  47678. if (this.parent) {
  47679. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47680. }
  47681. else {
  47682. globalPosition = this.position;
  47683. }
  47684. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47685. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47686. if (!this._collider) {
  47687. this._collider = new BABYLON.Collider();
  47688. }
  47689. this._collider._radius = this.ellipsoid;
  47690. this._collider.collisionMask = this._collisionMask;
  47691. //no need for clone, as long as gravity is not on.
  47692. var actualDisplacement = displacement;
  47693. //add gravity to the direction to prevent the dual-collision checking
  47694. if (this.applyGravity) {
  47695. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47696. actualDisplacement = displacement.add(this.getScene().gravity);
  47697. }
  47698. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47699. };
  47700. /** @hidden */
  47701. FreeCamera.prototype._checkInputs = function () {
  47702. if (!this._localDirection) {
  47703. this._localDirection = BABYLON.Vector3.Zero();
  47704. this._transformedDirection = BABYLON.Vector3.Zero();
  47705. }
  47706. this.inputs.checkInputs();
  47707. _super.prototype._checkInputs.call(this);
  47708. };
  47709. /** @hidden */
  47710. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47711. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47712. };
  47713. /** @hidden */
  47714. FreeCamera.prototype._updatePosition = function () {
  47715. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47716. this._collideWithWorld(this.cameraDirection);
  47717. }
  47718. else {
  47719. _super.prototype._updatePosition.call(this);
  47720. }
  47721. };
  47722. /**
  47723. * Destroy the camera and release the current resources hold by it.
  47724. */
  47725. FreeCamera.prototype.dispose = function () {
  47726. this.inputs.clear();
  47727. _super.prototype.dispose.call(this);
  47728. };
  47729. /**
  47730. * Gets the current object class name.
  47731. * @return the class name
  47732. */
  47733. FreeCamera.prototype.getClassName = function () {
  47734. return "FreeCamera";
  47735. };
  47736. __decorate([
  47737. BABYLON.serializeAsVector3()
  47738. ], FreeCamera.prototype, "ellipsoid", void 0);
  47739. __decorate([
  47740. BABYLON.serializeAsVector3()
  47741. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47742. __decorate([
  47743. BABYLON.serialize()
  47744. ], FreeCamera.prototype, "checkCollisions", void 0);
  47745. __decorate([
  47746. BABYLON.serialize()
  47747. ], FreeCamera.prototype, "applyGravity", void 0);
  47748. return FreeCamera;
  47749. }(BABYLON.TargetCamera));
  47750. BABYLON.FreeCamera = FreeCamera;
  47751. })(BABYLON || (BABYLON = {}));
  47752. //# sourceMappingURL=babylon.freeCamera.js.map
  47753. var BABYLON;
  47754. (function (BABYLON) {
  47755. /**
  47756. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  47757. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47758. */
  47759. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47760. function ArcRotateCameraKeyboardMoveInput() {
  47761. /**
  47762. * Defines the list of key codes associated with the up action (increase alpha)
  47763. */
  47764. this.keysUp = [38];
  47765. /**
  47766. * Defines the list of key codes associated with the down action (decrease alpha)
  47767. */
  47768. this.keysDown = [40];
  47769. /**
  47770. * Defines the list of key codes associated with the left action (increase beta)
  47771. */
  47772. this.keysLeft = [37];
  47773. /**
  47774. * Defines the list of key codes associated with the right action (decrease beta)
  47775. */
  47776. this.keysRight = [39];
  47777. /**
  47778. * Defines the list of key codes associated with the reset action.
  47779. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  47780. */
  47781. this.keysReset = [220];
  47782. /**
  47783. * Defines the panning sensibility of the inputs.
  47784. * (How fast is the camera paning)
  47785. */
  47786. this.panningSensibility = 50.0;
  47787. /**
  47788. * Defines the zooming sensibility of the inputs.
  47789. * (How fast is the camera zooming)
  47790. */
  47791. this.zoomingSensibility = 25.0;
  47792. /**
  47793. * Defines wether maintaining the alt key down switch the movement mode from
  47794. * orientation to zoom.
  47795. */
  47796. this.useAltToZoom = true;
  47797. this._keys = new Array();
  47798. }
  47799. /**
  47800. * Attach the input controls to a specific dom element to get the input from.
  47801. * @param element Defines the element the controls should be listened from
  47802. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47803. */
  47804. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47805. var _this = this;
  47806. if (this._onCanvasBlurObserver) {
  47807. return;
  47808. }
  47809. this._scene = this.camera.getScene();
  47810. this._engine = this._scene.getEngine();
  47811. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47812. _this._keys = [];
  47813. });
  47814. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47815. var evt = info.event;
  47816. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47817. _this._ctrlPressed = evt.ctrlKey;
  47818. _this._altPressed = evt.altKey;
  47819. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47820. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47821. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47822. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47823. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47824. var index = _this._keys.indexOf(evt.keyCode);
  47825. if (index === -1) {
  47826. _this._keys.push(evt.keyCode);
  47827. }
  47828. if (evt.preventDefault) {
  47829. if (!noPreventDefault) {
  47830. evt.preventDefault();
  47831. }
  47832. }
  47833. }
  47834. }
  47835. else {
  47836. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47837. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47838. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47839. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47840. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47841. var index = _this._keys.indexOf(evt.keyCode);
  47842. if (index >= 0) {
  47843. _this._keys.splice(index, 1);
  47844. }
  47845. if (evt.preventDefault) {
  47846. if (!noPreventDefault) {
  47847. evt.preventDefault();
  47848. }
  47849. }
  47850. }
  47851. }
  47852. });
  47853. };
  47854. /**
  47855. * Detach the current controls from the specified dom element.
  47856. * @param element Defines the element to stop listening the inputs from
  47857. */
  47858. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47859. if (this._scene) {
  47860. if (this._onKeyboardObserver) {
  47861. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47862. }
  47863. if (this._onCanvasBlurObserver) {
  47864. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47865. }
  47866. this._onKeyboardObserver = null;
  47867. this._onCanvasBlurObserver = null;
  47868. }
  47869. this._keys = [];
  47870. };
  47871. /**
  47872. * Update the current camera state depending on the inputs that have been used this frame.
  47873. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47874. */
  47875. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47876. if (this._onKeyboardObserver) {
  47877. var camera = this.camera;
  47878. for (var index = 0; index < this._keys.length; index++) {
  47879. var keyCode = this._keys[index];
  47880. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47881. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47882. camera.inertialPanningX -= 1 / this.panningSensibility;
  47883. }
  47884. else {
  47885. camera.inertialAlphaOffset -= 0.01;
  47886. }
  47887. }
  47888. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47889. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47890. camera.inertialPanningY += 1 / this.panningSensibility;
  47891. }
  47892. else if (this._altPressed && this.useAltToZoom) {
  47893. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47894. }
  47895. else {
  47896. camera.inertialBetaOffset -= 0.01;
  47897. }
  47898. }
  47899. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47900. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47901. camera.inertialPanningX += 1 / this.panningSensibility;
  47902. }
  47903. else {
  47904. camera.inertialAlphaOffset += 0.01;
  47905. }
  47906. }
  47907. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47908. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47909. camera.inertialPanningY -= 1 / this.panningSensibility;
  47910. }
  47911. else if (this._altPressed && this.useAltToZoom) {
  47912. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47913. }
  47914. else {
  47915. camera.inertialBetaOffset += 0.01;
  47916. }
  47917. }
  47918. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47919. if (camera.useInputToRestoreState) {
  47920. camera.restoreState();
  47921. }
  47922. }
  47923. }
  47924. }
  47925. };
  47926. /**
  47927. * Gets the class name of the current intput.
  47928. * @returns the class name
  47929. */
  47930. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47931. return "ArcRotateCameraKeyboardMoveInput";
  47932. };
  47933. /**
  47934. * Get the friendly name associated with the input class.
  47935. * @returns the input friendly name
  47936. */
  47937. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47938. return "keyboard";
  47939. };
  47940. __decorate([
  47941. BABYLON.serialize()
  47942. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47943. __decorate([
  47944. BABYLON.serialize()
  47945. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47946. __decorate([
  47947. BABYLON.serialize()
  47948. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47949. __decorate([
  47950. BABYLON.serialize()
  47951. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47952. __decorate([
  47953. BABYLON.serialize()
  47954. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47955. __decorate([
  47956. BABYLON.serialize()
  47957. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47958. __decorate([
  47959. BABYLON.serialize()
  47960. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47961. __decorate([
  47962. BABYLON.serialize()
  47963. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47964. return ArcRotateCameraKeyboardMoveInput;
  47965. }());
  47966. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47967. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47968. })(BABYLON || (BABYLON = {}));
  47969. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47970. var BABYLON;
  47971. (function (BABYLON) {
  47972. /**
  47973. * Manage the mouse wheel inputs to control an arc rotate camera.
  47974. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47975. */
  47976. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47977. function ArcRotateCameraMouseWheelInput() {
  47978. /**
  47979. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47980. */
  47981. this.wheelPrecision = 3.0;
  47982. /**
  47983. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47984. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47985. */
  47986. this.wheelDeltaPercentage = 0;
  47987. }
  47988. /**
  47989. * Attach the input controls to a specific dom element to get the input from.
  47990. * @param element Defines the element the controls should be listened from
  47991. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47992. */
  47993. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47994. var _this = this;
  47995. this._wheel = function (p, s) {
  47996. //sanity check - this should be a PointerWheel event.
  47997. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47998. return;
  47999. var event = p.event;
  48000. var delta = 0;
  48001. if (event.wheelDelta) {
  48002. if (_this.wheelDeltaPercentage) {
  48003. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48004. if (event.wheelDelta > 0) {
  48005. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48006. }
  48007. else {
  48008. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48009. }
  48010. }
  48011. else {
  48012. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48013. }
  48014. }
  48015. else if (event.detail) {
  48016. delta = -event.detail / _this.wheelPrecision;
  48017. }
  48018. if (delta)
  48019. _this.camera.inertialRadiusOffset += delta;
  48020. if (event.preventDefault) {
  48021. if (!noPreventDefault) {
  48022. event.preventDefault();
  48023. }
  48024. }
  48025. };
  48026. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48027. };
  48028. /**
  48029. * Detach the current controls from the specified dom element.
  48030. * @param element Defines the element to stop listening the inputs from
  48031. */
  48032. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48033. if (this._observer && element) {
  48034. this.camera.getScene().onPointerObservable.remove(this._observer);
  48035. this._observer = null;
  48036. this._wheel = null;
  48037. }
  48038. };
  48039. /**
  48040. * Gets the class name of the current intput.
  48041. * @returns the class name
  48042. */
  48043. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48044. return "ArcRotateCameraMouseWheelInput";
  48045. };
  48046. /**
  48047. * Get the friendly name associated with the input class.
  48048. * @returns the input friendly name
  48049. */
  48050. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48051. return "mousewheel";
  48052. };
  48053. __decorate([
  48054. BABYLON.serialize()
  48055. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48056. __decorate([
  48057. BABYLON.serialize()
  48058. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48059. return ArcRotateCameraMouseWheelInput;
  48060. }());
  48061. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48062. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48063. })(BABYLON || (BABYLON = {}));
  48064. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48065. var BABYLON;
  48066. (function (BABYLON) {
  48067. /**
  48068. * Manage the pointers inputs to control an arc rotate camera.
  48069. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48070. */
  48071. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48072. function ArcRotateCameraPointersInput() {
  48073. /**
  48074. * Defines the buttons associated with the input to handle camera move.
  48075. */
  48076. this.buttons = [0, 1, 2];
  48077. /**
  48078. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48079. */
  48080. this.angularSensibilityX = 1000.0;
  48081. /**
  48082. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48083. */
  48084. this.angularSensibilityY = 1000.0;
  48085. /**
  48086. * Defines the pointer pinch precision or how fast is the camera zooming.
  48087. */
  48088. this.pinchPrecision = 12.0;
  48089. /**
  48090. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48091. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48092. */
  48093. this.pinchDeltaPercentage = 0;
  48094. /**
  48095. * Defines the pointer panning sensibility or how fast is the camera moving.
  48096. */
  48097. this.panningSensibility = 1000.0;
  48098. /**
  48099. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  48100. */
  48101. this.multiTouchPanning = true;
  48102. /**
  48103. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  48104. */
  48105. this.multiTouchPanAndZoom = true;
  48106. /**
  48107. * Revers pinch action direction.
  48108. */
  48109. this.pinchInwards = true;
  48110. this._isPanClick = false;
  48111. }
  48112. /**
  48113. * Attach the input controls to a specific dom element to get the input from.
  48114. * @param element Defines the element the controls should be listened from
  48115. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48116. */
  48117. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48118. var _this = this;
  48119. var engine = this.camera.getEngine();
  48120. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48121. var pointA = null;
  48122. var pointB = null;
  48123. var previousPinchSquaredDistance = 0;
  48124. var initialDistance = 0;
  48125. var twoFingerActivityCount = 0;
  48126. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48127. this._pointerInput = function (p, s) {
  48128. var evt = p.event;
  48129. var isTouch = p.event.pointerType === "touch";
  48130. if (engine.isInVRExclusivePointerMode) {
  48131. return;
  48132. }
  48133. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48134. return;
  48135. }
  48136. var srcElement = (evt.srcElement || evt.target);
  48137. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48138. try {
  48139. srcElement.setPointerCapture(evt.pointerId);
  48140. }
  48141. catch (e) {
  48142. //Nothing to do with the error. Execution will continue.
  48143. }
  48144. // Manage panning with pan button click
  48145. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48146. // manage pointers
  48147. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48148. if (pointA === null) {
  48149. pointA = cacheSoloPointer;
  48150. }
  48151. else if (pointB === null) {
  48152. pointB = cacheSoloPointer;
  48153. }
  48154. if (!noPreventDefault) {
  48155. evt.preventDefault();
  48156. element.focus();
  48157. }
  48158. }
  48159. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48160. if (_this.camera.useInputToRestoreState) {
  48161. _this.camera.restoreState();
  48162. }
  48163. }
  48164. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48165. try {
  48166. srcElement.releasePointerCapture(evt.pointerId);
  48167. }
  48168. catch (e) {
  48169. //Nothing to do with the error.
  48170. }
  48171. cacheSoloPointer = null;
  48172. previousPinchSquaredDistance = 0;
  48173. previousMultiTouchPanPosition.isPaning = false;
  48174. previousMultiTouchPanPosition.isPinching = false;
  48175. twoFingerActivityCount = 0;
  48176. initialDistance = 0;
  48177. if (!isTouch) {
  48178. pointB = null; // Mouse and pen are mono pointer
  48179. }
  48180. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48181. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48182. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48183. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48184. if (engine._badOS) {
  48185. pointA = pointB = null;
  48186. }
  48187. else {
  48188. //only remove the impacted pointer in case of multitouch allowing on most
  48189. //platforms switching from rotate to zoom and pan seamlessly.
  48190. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48191. pointA = pointB;
  48192. pointB = null;
  48193. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48194. }
  48195. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48196. pointB = null;
  48197. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48198. }
  48199. else {
  48200. pointA = pointB = null;
  48201. }
  48202. }
  48203. if (!noPreventDefault) {
  48204. evt.preventDefault();
  48205. }
  48206. }
  48207. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48208. if (!noPreventDefault) {
  48209. evt.preventDefault();
  48210. }
  48211. // One button down
  48212. if (pointA && pointB === null && cacheSoloPointer) {
  48213. if (_this.panningSensibility !== 0 &&
  48214. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48215. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48216. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48217. }
  48218. else {
  48219. var offsetX = evt.clientX - cacheSoloPointer.x;
  48220. var offsetY = evt.clientY - cacheSoloPointer.y;
  48221. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48222. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48223. }
  48224. cacheSoloPointer.x = evt.clientX;
  48225. cacheSoloPointer.y = evt.clientY;
  48226. }
  48227. // Two buttons down: pinch/pan
  48228. else if (pointA && pointB) {
  48229. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48230. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48231. ed.x = evt.clientX;
  48232. ed.y = evt.clientY;
  48233. var direction = _this.pinchInwards ? 1 : -1;
  48234. var distX = pointA.x - pointB.x;
  48235. var distY = pointA.y - pointB.y;
  48236. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48237. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48238. if (previousPinchSquaredDistance === 0) {
  48239. initialDistance = pinchDistance;
  48240. previousPinchSquaredDistance = pinchSquaredDistance;
  48241. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48242. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48243. return;
  48244. }
  48245. if (_this.multiTouchPanAndZoom) {
  48246. if (_this.pinchDeltaPercentage) {
  48247. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48248. }
  48249. else {
  48250. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48251. (_this.pinchPrecision *
  48252. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48253. direction);
  48254. }
  48255. if (_this.panningSensibility !== 0) {
  48256. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48257. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48258. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48259. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48260. previousMultiTouchPanPosition.x = pointersCenterX;
  48261. previousMultiTouchPanPosition.y = pointersCenterY;
  48262. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48263. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48264. }
  48265. }
  48266. else {
  48267. twoFingerActivityCount++;
  48268. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48269. if (_this.pinchDeltaPercentage) {
  48270. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48271. }
  48272. else {
  48273. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48274. (_this.pinchPrecision *
  48275. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48276. direction);
  48277. }
  48278. previousMultiTouchPanPosition.isPaning = false;
  48279. previousMultiTouchPanPosition.isPinching = true;
  48280. }
  48281. else {
  48282. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48283. if (!previousMultiTouchPanPosition.isPaning) {
  48284. previousMultiTouchPanPosition.isPaning = true;
  48285. previousMultiTouchPanPosition.isPinching = false;
  48286. previousMultiTouchPanPosition.x = ed.x;
  48287. previousMultiTouchPanPosition.y = ed.y;
  48288. return;
  48289. }
  48290. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48291. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48292. }
  48293. }
  48294. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48295. previousMultiTouchPanPosition.x = ed.x;
  48296. previousMultiTouchPanPosition.y = ed.y;
  48297. }
  48298. }
  48299. previousPinchSquaredDistance = pinchSquaredDistance;
  48300. }
  48301. }
  48302. };
  48303. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  48304. this._onContextMenu = function (evt) {
  48305. evt.preventDefault();
  48306. };
  48307. if (!this.camera._useCtrlForPanning) {
  48308. element.addEventListener("contextmenu", this._onContextMenu, false);
  48309. }
  48310. this._onLostFocus = function () {
  48311. //this._keys = [];
  48312. pointA = pointB = null;
  48313. previousPinchSquaredDistance = 0;
  48314. previousMultiTouchPanPosition.isPaning = false;
  48315. previousMultiTouchPanPosition.isPinching = false;
  48316. twoFingerActivityCount = 0;
  48317. cacheSoloPointer = null;
  48318. initialDistance = 0;
  48319. };
  48320. this._onMouseMove = function (evt) {
  48321. if (!engine.isPointerLock) {
  48322. return;
  48323. }
  48324. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48325. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48326. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48327. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48328. if (!noPreventDefault) {
  48329. evt.preventDefault();
  48330. }
  48331. };
  48332. this._onGestureStart = function (e) {
  48333. if (window.MSGesture === undefined) {
  48334. return;
  48335. }
  48336. if (!_this._MSGestureHandler) {
  48337. _this._MSGestureHandler = new MSGesture();
  48338. _this._MSGestureHandler.target = element;
  48339. }
  48340. _this._MSGestureHandler.addPointer(e.pointerId);
  48341. };
  48342. this._onGesture = function (e) {
  48343. _this.camera.radius *= e.scale;
  48344. if (e.preventDefault) {
  48345. if (!noPreventDefault) {
  48346. e.stopPropagation();
  48347. e.preventDefault();
  48348. }
  48349. }
  48350. };
  48351. element.addEventListener("mousemove", this._onMouseMove, false);
  48352. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48353. element.addEventListener("MSGestureChange", this._onGesture, false);
  48354. BABYLON.Tools.RegisterTopRootEvents([
  48355. { name: "blur", handler: this._onLostFocus }
  48356. ]);
  48357. };
  48358. /**
  48359. * Detach the current controls from the specified dom element.
  48360. * @param element Defines the element to stop listening the inputs from
  48361. */
  48362. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48363. if (this._onLostFocus) {
  48364. BABYLON.Tools.UnregisterTopRootEvents([
  48365. { name: "blur", handler: this._onLostFocus }
  48366. ]);
  48367. }
  48368. if (element && this._observer) {
  48369. this.camera.getScene().onPointerObservable.remove(this._observer);
  48370. this._observer = null;
  48371. if (this._onContextMenu) {
  48372. element.removeEventListener("contextmenu", this._onContextMenu);
  48373. }
  48374. if (this._onMouseMove) {
  48375. element.removeEventListener("mousemove", this._onMouseMove);
  48376. }
  48377. if (this._onGestureStart) {
  48378. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48379. }
  48380. if (this._onGesture) {
  48381. element.removeEventListener("MSGestureChange", this._onGesture);
  48382. }
  48383. this._isPanClick = false;
  48384. this.pinchInwards = true;
  48385. this._onMouseMove = null;
  48386. this._onGestureStart = null;
  48387. this._onGesture = null;
  48388. this._MSGestureHandler = null;
  48389. this._onLostFocus = null;
  48390. this._onContextMenu = null;
  48391. }
  48392. };
  48393. /**
  48394. * Gets the class name of the current intput.
  48395. * @returns the class name
  48396. */
  48397. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48398. return "ArcRotateCameraPointersInput";
  48399. };
  48400. /**
  48401. * Get the friendly name associated with the input class.
  48402. * @returns the input friendly name
  48403. */
  48404. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48405. return "pointers";
  48406. };
  48407. __decorate([
  48408. BABYLON.serialize()
  48409. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48410. __decorate([
  48411. BABYLON.serialize()
  48412. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48413. __decorate([
  48414. BABYLON.serialize()
  48415. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48416. __decorate([
  48417. BABYLON.serialize()
  48418. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48419. __decorate([
  48420. BABYLON.serialize()
  48421. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48422. __decorate([
  48423. BABYLON.serialize()
  48424. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48425. __decorate([
  48426. BABYLON.serialize()
  48427. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48428. __decorate([
  48429. BABYLON.serialize()
  48430. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48431. return ArcRotateCameraPointersInput;
  48432. }());
  48433. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48434. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48435. })(BABYLON || (BABYLON = {}));
  48436. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48437. var BABYLON;
  48438. (function (BABYLON) {
  48439. /**
  48440. * Default Inputs manager for the ArcRotateCamera.
  48441. * It groups all the default supported inputs for ease of use.
  48442. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48443. */
  48444. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48445. __extends(ArcRotateCameraInputsManager, _super);
  48446. /**
  48447. * Instantiates a new ArcRotateCameraInputsManager.
  48448. * @param camera Defines the camera the inputs belong to
  48449. */
  48450. function ArcRotateCameraInputsManager(camera) {
  48451. return _super.call(this, camera) || this;
  48452. }
  48453. /**
  48454. * Add mouse wheel input support to the input manager.
  48455. * @returns the current input manager
  48456. */
  48457. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48458. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48459. return this;
  48460. };
  48461. /**
  48462. * Add pointers input support to the input manager.
  48463. * @returns the current input manager
  48464. */
  48465. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48466. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48467. return this;
  48468. };
  48469. /**
  48470. * Add keyboard input support to the input manager.
  48471. * @returns the current input manager
  48472. */
  48473. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48474. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48475. return this;
  48476. };
  48477. /**
  48478. * Add orientation input support to the input manager.
  48479. * @returns the current input manager
  48480. */
  48481. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48482. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48483. return this;
  48484. };
  48485. return ArcRotateCameraInputsManager;
  48486. }(BABYLON.CameraInputsManager));
  48487. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48488. })(BABYLON || (BABYLON = {}));
  48489. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48490. var BABYLON;
  48491. (function (BABYLON) {
  48492. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48493. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48494. });
  48495. /**
  48496. * This represents an orbital type of camera.
  48497. *
  48498. * 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.
  48499. * 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.
  48500. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48501. */
  48502. var ArcRotateCamera = /** @class */ (function (_super) {
  48503. __extends(ArcRotateCamera, _super);
  48504. /**
  48505. * Instantiates a new ArcRotateCamera in a given scene
  48506. * @param name Defines the name of the camera
  48507. * @param alpha Defines the camera rotation along the logitudinal axis
  48508. * @param beta Defines the camera rotation along the latitudinal axis
  48509. * @param radius Defines the camera distance from its target
  48510. * @param target Defines the camera target
  48511. * @param scene Defines the scene the camera belongs to
  48512. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48513. */
  48514. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48515. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48516. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48517. /**
  48518. * Current inertia value on the longitudinal axis.
  48519. * The bigger this number the longer it will take for the camera to stop.
  48520. */
  48521. _this.inertialAlphaOffset = 0;
  48522. /**
  48523. * Current inertia value on the latitudinal axis.
  48524. * The bigger this number the longer it will take for the camera to stop.
  48525. */
  48526. _this.inertialBetaOffset = 0;
  48527. /**
  48528. * Current inertia value on the radius axis.
  48529. * The bigger this number the longer it will take for the camera to stop.
  48530. */
  48531. _this.inertialRadiusOffset = 0;
  48532. /**
  48533. * Minimum allowed angle on the longitudinal axis.
  48534. * This can help limiting how the Camera is able to move in the scene.
  48535. */
  48536. _this.lowerAlphaLimit = null;
  48537. /**
  48538. * Maximum allowed angle on the longitudinal axis.
  48539. * This can help limiting how the Camera is able to move in the scene.
  48540. */
  48541. _this.upperAlphaLimit = null;
  48542. /**
  48543. * Minimum allowed angle on the latitudinal axis.
  48544. * This can help limiting how the Camera is able to move in the scene.
  48545. */
  48546. _this.lowerBetaLimit = 0.01;
  48547. /**
  48548. * Maximum allowed angle on the latitudinal axis.
  48549. * This can help limiting how the Camera is able to move in the scene.
  48550. */
  48551. _this.upperBetaLimit = Math.PI;
  48552. /**
  48553. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  48554. * This can help limiting how the Camera is able to move in the scene.
  48555. */
  48556. _this.lowerRadiusLimit = null;
  48557. /**
  48558. * Maximum allowed distance of the camera to the target (The camera can not get further).
  48559. * This can help limiting how the Camera is able to move in the scene.
  48560. */
  48561. _this.upperRadiusLimit = null;
  48562. /**
  48563. * Defines the current inertia value used during panning of the camera along the X axis.
  48564. */
  48565. _this.inertialPanningX = 0;
  48566. /**
  48567. * Defines the current inertia value used during panning of the camera along the Y axis.
  48568. */
  48569. _this.inertialPanningY = 0;
  48570. /**
  48571. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  48572. * Basically if your fingers moves away from more than this distance you will be considered
  48573. * in pinch mode.
  48574. */
  48575. _this.pinchToPanMaxDistance = 20;
  48576. /**
  48577. * Defines the maximum distance the camera can pan.
  48578. * This could help keeping the cammera always in your scene.
  48579. */
  48580. _this.panningDistanceLimit = null;
  48581. /**
  48582. * Defines the target of the camera before paning.
  48583. */
  48584. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48585. /**
  48586. * Defines the value of the inertia used during panning.
  48587. * 0 would mean stop inertia and one would mean no decelleration at all.
  48588. */
  48589. _this.panningInertia = 0.9;
  48590. //-- end properties for backward compatibility for inputs
  48591. /**
  48592. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  48593. */
  48594. _this.zoomOnFactor = 1;
  48595. /**
  48596. * Defines a screen offset for the camera position.
  48597. */
  48598. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48599. /**
  48600. * Allows the camera to be completely reversed.
  48601. * If false the camera can not arrive upside down.
  48602. */
  48603. _this.allowUpsideDown = true;
  48604. /**
  48605. * Define if double tap/click is used to restore the previously saved state of the camera.
  48606. */
  48607. _this.useInputToRestoreState = true;
  48608. /** @hidden */
  48609. _this._viewMatrix = new BABYLON.Matrix();
  48610. /**
  48611. * Defines the allowed panning axis.
  48612. */
  48613. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48614. /**
  48615. * Observable triggered when the mesh target has been changed on the camera.
  48616. */
  48617. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48618. /**
  48619. * Defines whether the camera should check collision with the objects oh the scene.
  48620. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  48621. */
  48622. _this.checkCollisions = false;
  48623. /**
  48624. * Defines the collision radius of the camera.
  48625. * This simulates a sphere around the camera.
  48626. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48627. */
  48628. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48629. _this._previousPosition = BABYLON.Vector3.Zero();
  48630. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48631. _this._newPosition = BABYLON.Vector3.Zero();
  48632. _this._computationVector = BABYLON.Vector3.Zero();
  48633. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48634. if (collidedMesh === void 0) { collidedMesh = null; }
  48635. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48636. newPosition.multiplyInPlace(_this._collider._radius);
  48637. }
  48638. if (!collidedMesh) {
  48639. _this._previousPosition.copyFrom(_this.position);
  48640. }
  48641. else {
  48642. _this.setPosition(newPosition);
  48643. if (_this.onCollide) {
  48644. _this.onCollide(collidedMesh);
  48645. }
  48646. }
  48647. // Recompute because of constraints
  48648. var cosa = Math.cos(_this.alpha);
  48649. var sina = Math.sin(_this.alpha);
  48650. var cosb = Math.cos(_this.beta);
  48651. var sinb = Math.sin(_this.beta);
  48652. if (sinb === 0) {
  48653. sinb = 0.0001;
  48654. }
  48655. var target = _this._getTargetPosition();
  48656. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48657. target.addToRef(_this._computationVector, _this._newPosition);
  48658. _this.position.copyFrom(_this._newPosition);
  48659. var up = _this.upVector;
  48660. if (_this.allowUpsideDown && _this.beta < 0) {
  48661. up = up.clone();
  48662. up = up.negate();
  48663. }
  48664. _this._computeViewMatrix(_this.position, target, up);
  48665. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48666. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48667. _this._collisionTriggered = false;
  48668. };
  48669. _this._target = BABYLON.Vector3.Zero();
  48670. if (target) {
  48671. _this.setTarget(target);
  48672. }
  48673. _this.alpha = alpha;
  48674. _this.beta = beta;
  48675. _this.radius = radius;
  48676. _this.getViewMatrix();
  48677. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48678. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48679. return _this;
  48680. }
  48681. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48682. /**
  48683. * Defines the target point of the camera.
  48684. * The camera looks towards it form the radius distance.
  48685. */
  48686. get: function () {
  48687. return this._target;
  48688. },
  48689. set: function (value) {
  48690. this.setTarget(value);
  48691. },
  48692. enumerable: true,
  48693. configurable: true
  48694. });
  48695. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48696. //-- begin properties for backward compatibility for inputs
  48697. /**
  48698. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48699. */
  48700. get: function () {
  48701. var pointers = this.inputs.attached["pointers"];
  48702. if (pointers)
  48703. return pointers.angularSensibilityX;
  48704. return 0;
  48705. },
  48706. set: function (value) {
  48707. var pointers = this.inputs.attached["pointers"];
  48708. if (pointers) {
  48709. pointers.angularSensibilityX = value;
  48710. }
  48711. },
  48712. enumerable: true,
  48713. configurable: true
  48714. });
  48715. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48716. /**
  48717. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48718. */
  48719. get: function () {
  48720. var pointers = this.inputs.attached["pointers"];
  48721. if (pointers)
  48722. return pointers.angularSensibilityY;
  48723. return 0;
  48724. },
  48725. set: function (value) {
  48726. var pointers = this.inputs.attached["pointers"];
  48727. if (pointers) {
  48728. pointers.angularSensibilityY = value;
  48729. }
  48730. },
  48731. enumerable: true,
  48732. configurable: true
  48733. });
  48734. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48735. /**
  48736. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  48737. */
  48738. get: function () {
  48739. var pointers = this.inputs.attached["pointers"];
  48740. if (pointers)
  48741. return pointers.pinchPrecision;
  48742. return 0;
  48743. },
  48744. set: function (value) {
  48745. var pointers = this.inputs.attached["pointers"];
  48746. if (pointers) {
  48747. pointers.pinchPrecision = value;
  48748. }
  48749. },
  48750. enumerable: true,
  48751. configurable: true
  48752. });
  48753. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48754. /**
  48755. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  48756. * It will be used instead of pinchDeltaPrecision if different from 0.
  48757. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48758. */
  48759. get: function () {
  48760. var pointers = this.inputs.attached["pointers"];
  48761. if (pointers)
  48762. return pointers.pinchDeltaPercentage;
  48763. return 0;
  48764. },
  48765. set: function (value) {
  48766. var pointers = this.inputs.attached["pointers"];
  48767. if (pointers) {
  48768. pointers.pinchDeltaPercentage = value;
  48769. }
  48770. },
  48771. enumerable: true,
  48772. configurable: true
  48773. });
  48774. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48775. /**
  48776. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  48777. */
  48778. get: function () {
  48779. var pointers = this.inputs.attached["pointers"];
  48780. if (pointers)
  48781. return pointers.panningSensibility;
  48782. return 0;
  48783. },
  48784. set: function (value) {
  48785. var pointers = this.inputs.attached["pointers"];
  48786. if (pointers) {
  48787. pointers.panningSensibility = value;
  48788. }
  48789. },
  48790. enumerable: true,
  48791. configurable: true
  48792. });
  48793. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48794. /**
  48795. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  48796. */
  48797. get: function () {
  48798. var keyboard = this.inputs.attached["keyboard"];
  48799. if (keyboard)
  48800. return keyboard.keysUp;
  48801. return [];
  48802. },
  48803. set: function (value) {
  48804. var keyboard = this.inputs.attached["keyboard"];
  48805. if (keyboard)
  48806. keyboard.keysUp = value;
  48807. },
  48808. enumerable: true,
  48809. configurable: true
  48810. });
  48811. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48812. /**
  48813. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  48814. */
  48815. get: function () {
  48816. var keyboard = this.inputs.attached["keyboard"];
  48817. if (keyboard)
  48818. return keyboard.keysDown;
  48819. return [];
  48820. },
  48821. set: function (value) {
  48822. var keyboard = this.inputs.attached["keyboard"];
  48823. if (keyboard)
  48824. keyboard.keysDown = value;
  48825. },
  48826. enumerable: true,
  48827. configurable: true
  48828. });
  48829. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48830. /**
  48831. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  48832. */
  48833. get: function () {
  48834. var keyboard = this.inputs.attached["keyboard"];
  48835. if (keyboard)
  48836. return keyboard.keysLeft;
  48837. return [];
  48838. },
  48839. set: function (value) {
  48840. var keyboard = this.inputs.attached["keyboard"];
  48841. if (keyboard)
  48842. keyboard.keysLeft = value;
  48843. },
  48844. enumerable: true,
  48845. configurable: true
  48846. });
  48847. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48848. /**
  48849. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  48850. */
  48851. get: function () {
  48852. var keyboard = this.inputs.attached["keyboard"];
  48853. if (keyboard)
  48854. return keyboard.keysRight;
  48855. return [];
  48856. },
  48857. set: function (value) {
  48858. var keyboard = this.inputs.attached["keyboard"];
  48859. if (keyboard)
  48860. keyboard.keysRight = value;
  48861. },
  48862. enumerable: true,
  48863. configurable: true
  48864. });
  48865. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48866. /**
  48867. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48868. */
  48869. get: function () {
  48870. var mousewheel = this.inputs.attached["mousewheel"];
  48871. if (mousewheel)
  48872. return mousewheel.wheelPrecision;
  48873. return 0;
  48874. },
  48875. set: function (value) {
  48876. var mousewheel = this.inputs.attached["mousewheel"];
  48877. if (mousewheel)
  48878. mousewheel.wheelPrecision = value;
  48879. },
  48880. enumerable: true,
  48881. configurable: true
  48882. });
  48883. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48884. /**
  48885. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  48886. * It will be used instead of pinchDeltaPrecision if different from 0.
  48887. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48888. */
  48889. get: function () {
  48890. var mousewheel = this.inputs.attached["mousewheel"];
  48891. if (mousewheel)
  48892. return mousewheel.wheelDeltaPercentage;
  48893. return 0;
  48894. },
  48895. set: function (value) {
  48896. var mousewheel = this.inputs.attached["mousewheel"];
  48897. if (mousewheel)
  48898. mousewheel.wheelDeltaPercentage = value;
  48899. },
  48900. enumerable: true,
  48901. configurable: true
  48902. });
  48903. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48904. /**
  48905. * Gets the bouncing behavior of the camera if it has been enabled.
  48906. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48907. */
  48908. get: function () {
  48909. return this._bouncingBehavior;
  48910. },
  48911. enumerable: true,
  48912. configurable: true
  48913. });
  48914. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48915. /**
  48916. * Defines if the bouncing behavior of the camera is enabled on the camera.
  48917. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48918. */
  48919. get: function () {
  48920. return this._bouncingBehavior != null;
  48921. },
  48922. set: function (value) {
  48923. if (value === this.useBouncingBehavior) {
  48924. return;
  48925. }
  48926. if (value) {
  48927. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48928. this.addBehavior(this._bouncingBehavior);
  48929. }
  48930. else if (this._bouncingBehavior) {
  48931. this.removeBehavior(this._bouncingBehavior);
  48932. this._bouncingBehavior = null;
  48933. }
  48934. },
  48935. enumerable: true,
  48936. configurable: true
  48937. });
  48938. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48939. /**
  48940. * Gets the framing behavior of the camera if it has been enabled.
  48941. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48942. */
  48943. get: function () {
  48944. return this._framingBehavior;
  48945. },
  48946. enumerable: true,
  48947. configurable: true
  48948. });
  48949. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48950. /**
  48951. * Defines if the framing behavior of the camera is enabled on the camera.
  48952. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48953. */
  48954. get: function () {
  48955. return this._framingBehavior != null;
  48956. },
  48957. set: function (value) {
  48958. if (value === this.useFramingBehavior) {
  48959. return;
  48960. }
  48961. if (value) {
  48962. this._framingBehavior = new BABYLON.FramingBehavior();
  48963. this.addBehavior(this._framingBehavior);
  48964. }
  48965. else if (this._framingBehavior) {
  48966. this.removeBehavior(this._framingBehavior);
  48967. this._framingBehavior = null;
  48968. }
  48969. },
  48970. enumerable: true,
  48971. configurable: true
  48972. });
  48973. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48974. /**
  48975. * Gets the auto rotation behavior of the camera if it has been enabled.
  48976. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48977. */
  48978. get: function () {
  48979. return this._autoRotationBehavior;
  48980. },
  48981. enumerable: true,
  48982. configurable: true
  48983. });
  48984. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48985. /**
  48986. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  48987. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48988. */
  48989. get: function () {
  48990. return this._autoRotationBehavior != null;
  48991. },
  48992. set: function (value) {
  48993. if (value === this.useAutoRotationBehavior) {
  48994. return;
  48995. }
  48996. if (value) {
  48997. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48998. this.addBehavior(this._autoRotationBehavior);
  48999. }
  49000. else if (this._autoRotationBehavior) {
  49001. this.removeBehavior(this._autoRotationBehavior);
  49002. this._autoRotationBehavior = null;
  49003. }
  49004. },
  49005. enumerable: true,
  49006. configurable: true
  49007. });
  49008. // Cache
  49009. /** @hidden */
  49010. ArcRotateCamera.prototype._initCache = function () {
  49011. _super.prototype._initCache.call(this);
  49012. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49013. this._cache.alpha = undefined;
  49014. this._cache.beta = undefined;
  49015. this._cache.radius = undefined;
  49016. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49017. };
  49018. /** @hidden */
  49019. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49020. if (!ignoreParentClass) {
  49021. _super.prototype._updateCache.call(this);
  49022. }
  49023. this._cache._target.copyFrom(this._getTargetPosition());
  49024. this._cache.alpha = this.alpha;
  49025. this._cache.beta = this.beta;
  49026. this._cache.radius = this.radius;
  49027. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49028. };
  49029. ArcRotateCamera.prototype._getTargetPosition = function () {
  49030. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49031. var pos = this._targetHost.getAbsolutePosition();
  49032. if (this._targetBoundingCenter) {
  49033. pos.addToRef(this._targetBoundingCenter, this._target);
  49034. }
  49035. else {
  49036. this._target.copyFrom(pos);
  49037. }
  49038. }
  49039. var lockedTargetPosition = this._getLockedTargetPosition();
  49040. if (lockedTargetPosition) {
  49041. return lockedTargetPosition;
  49042. }
  49043. return this._target;
  49044. };
  49045. /**
  49046. * Stores the current state of the camera (alpha, beta, radius and target)
  49047. * @returns the camera itself
  49048. */
  49049. ArcRotateCamera.prototype.storeState = function () {
  49050. this._storedAlpha = this.alpha;
  49051. this._storedBeta = this.beta;
  49052. this._storedRadius = this.radius;
  49053. this._storedTarget = this._getTargetPosition().clone();
  49054. return _super.prototype.storeState.call(this);
  49055. };
  49056. /**
  49057. * @hidden
  49058. * Restored camera state. You must call storeState() first
  49059. */
  49060. ArcRotateCamera.prototype._restoreStateValues = function () {
  49061. if (!_super.prototype._restoreStateValues.call(this)) {
  49062. return false;
  49063. }
  49064. this.alpha = this._storedAlpha;
  49065. this.beta = this._storedBeta;
  49066. this.radius = this._storedRadius;
  49067. this.setTarget(this._storedTarget.clone());
  49068. this.inertialAlphaOffset = 0;
  49069. this.inertialBetaOffset = 0;
  49070. this.inertialRadiusOffset = 0;
  49071. this.inertialPanningX = 0;
  49072. this.inertialPanningY = 0;
  49073. return true;
  49074. };
  49075. // Synchronized
  49076. /** @hidden */
  49077. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49078. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49079. return false;
  49080. return this._cache._target.equals(this._getTargetPosition())
  49081. && this._cache.alpha === this.alpha
  49082. && this._cache.beta === this.beta
  49083. && this._cache.radius === this.radius
  49084. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49085. };
  49086. /**
  49087. * Attached controls to the current camera.
  49088. * @param element Defines the element the controls should be listened from
  49089. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49090. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  49091. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  49092. */
  49093. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49094. var _this = this;
  49095. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49096. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49097. this._useCtrlForPanning = useCtrlForPanning;
  49098. this._panningMouseButton = panningMouseButton;
  49099. this.inputs.attachElement(element, noPreventDefault);
  49100. this._reset = function () {
  49101. _this.inertialAlphaOffset = 0;
  49102. _this.inertialBetaOffset = 0;
  49103. _this.inertialRadiusOffset = 0;
  49104. _this.inertialPanningX = 0;
  49105. _this.inertialPanningY = 0;
  49106. };
  49107. };
  49108. /**
  49109. * Detach the current controls from the camera.
  49110. * The camera will stop reacting to inputs.
  49111. * @param element Defines the element to stop listening the inputs from
  49112. */
  49113. ArcRotateCamera.prototype.detachControl = function (element) {
  49114. this.inputs.detachElement(element);
  49115. if (this._reset) {
  49116. this._reset();
  49117. }
  49118. };
  49119. /** @hidden */
  49120. ArcRotateCamera.prototype._checkInputs = function () {
  49121. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49122. if (this._collisionTriggered) {
  49123. return;
  49124. }
  49125. this.inputs.checkInputs();
  49126. // Inertia
  49127. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49128. var inertialAlphaOffset = this.inertialAlphaOffset;
  49129. if (this.beta <= 0)
  49130. inertialAlphaOffset *= -1;
  49131. if (this.getScene().useRightHandedSystem)
  49132. inertialAlphaOffset *= -1;
  49133. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49134. inertialAlphaOffset *= -1;
  49135. this.alpha += inertialAlphaOffset;
  49136. this.beta += this.inertialBetaOffset;
  49137. this.radius -= this.inertialRadiusOffset;
  49138. this.inertialAlphaOffset *= this.inertia;
  49139. this.inertialBetaOffset *= this.inertia;
  49140. this.inertialRadiusOffset *= this.inertia;
  49141. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49142. this.inertialAlphaOffset = 0;
  49143. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49144. this.inertialBetaOffset = 0;
  49145. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49146. this.inertialRadiusOffset = 0;
  49147. }
  49148. // Panning inertia
  49149. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49150. if (!this._localDirection) {
  49151. this._localDirection = BABYLON.Vector3.Zero();
  49152. this._transformedDirection = BABYLON.Vector3.Zero();
  49153. }
  49154. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49155. this._localDirection.multiplyInPlace(this.panningAxis);
  49156. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49157. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49158. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49159. if (!this.panningAxis.y) {
  49160. this._transformedDirection.y = 0;
  49161. }
  49162. if (!this._targetHost) {
  49163. if (this.panningDistanceLimit) {
  49164. this._transformedDirection.addInPlace(this._target);
  49165. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49166. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49167. this._target.copyFrom(this._transformedDirection);
  49168. }
  49169. }
  49170. else {
  49171. this._target.addInPlace(this._transformedDirection);
  49172. }
  49173. }
  49174. this.inertialPanningX *= this.panningInertia;
  49175. this.inertialPanningY *= this.panningInertia;
  49176. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49177. this.inertialPanningX = 0;
  49178. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49179. this.inertialPanningY = 0;
  49180. }
  49181. // Limits
  49182. this._checkLimits();
  49183. _super.prototype._checkInputs.call(this);
  49184. };
  49185. ArcRotateCamera.prototype._checkLimits = function () {
  49186. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49187. if (this.allowUpsideDown && this.beta > Math.PI) {
  49188. this.beta = this.beta - (2 * Math.PI);
  49189. }
  49190. }
  49191. else {
  49192. if (this.beta < this.lowerBetaLimit) {
  49193. this.beta = this.lowerBetaLimit;
  49194. }
  49195. }
  49196. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49197. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49198. this.beta = this.beta + (2 * Math.PI);
  49199. }
  49200. }
  49201. else {
  49202. if (this.beta > this.upperBetaLimit) {
  49203. this.beta = this.upperBetaLimit;
  49204. }
  49205. }
  49206. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  49207. this.alpha = this.lowerAlphaLimit;
  49208. }
  49209. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  49210. this.alpha = this.upperAlphaLimit;
  49211. }
  49212. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  49213. this.radius = this.lowerRadiusLimit;
  49214. }
  49215. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  49216. this.radius = this.upperRadiusLimit;
  49217. }
  49218. };
  49219. /**
  49220. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  49221. */
  49222. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49223. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49224. this.radius = this._computationVector.length();
  49225. if (this.radius === 0) {
  49226. this.radius = 0.0001; // Just to avoid division by zero
  49227. }
  49228. // Alpha
  49229. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49230. if (this._computationVector.z < 0) {
  49231. this.alpha = 2 * Math.PI - this.alpha;
  49232. }
  49233. // Beta
  49234. this.beta = Math.acos(this._computationVector.y / this.radius);
  49235. this._checkLimits();
  49236. };
  49237. /**
  49238. * Use a position to define the current camera related information like aplha, beta and radius
  49239. * @param position Defines the position to set the camera at
  49240. */
  49241. ArcRotateCamera.prototype.setPosition = function (position) {
  49242. if (this.position.equals(position)) {
  49243. return;
  49244. }
  49245. this.position.copyFrom(position);
  49246. this.rebuildAnglesAndRadius();
  49247. };
  49248. /**
  49249. * Defines the target the camera should look at.
  49250. * This will automatically adapt alpha beta and radius to fit within the new target.
  49251. * @param target Defines the new target as a Vector or a mesh
  49252. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  49253. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  49254. */
  49255. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49256. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49257. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49258. if (target.getBoundingInfo) {
  49259. if (toBoundingCenter) {
  49260. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49261. }
  49262. else {
  49263. this._targetBoundingCenter = null;
  49264. }
  49265. this._targetHost = target;
  49266. this._target = this._getTargetPosition();
  49267. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49268. }
  49269. else {
  49270. var newTarget = target;
  49271. var currentTarget = this._getTargetPosition();
  49272. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49273. return;
  49274. }
  49275. this._targetHost = null;
  49276. this._target = newTarget;
  49277. this._targetBoundingCenter = null;
  49278. this.onMeshTargetChangedObservable.notifyObservers(null);
  49279. }
  49280. this.rebuildAnglesAndRadius();
  49281. };
  49282. /** @hidden */
  49283. ArcRotateCamera.prototype._getViewMatrix = function () {
  49284. // Compute
  49285. var cosa = Math.cos(this.alpha);
  49286. var sina = Math.sin(this.alpha);
  49287. var cosb = Math.cos(this.beta);
  49288. var sinb = Math.sin(this.beta);
  49289. if (sinb === 0) {
  49290. sinb = 0.0001;
  49291. }
  49292. var target = this._getTargetPosition();
  49293. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49294. target.addToRef(this._computationVector, this._newPosition);
  49295. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49296. if (!this._collider) {
  49297. this._collider = new BABYLON.Collider();
  49298. }
  49299. this._collider._radius = this.collisionRadius;
  49300. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49301. this._collisionTriggered = true;
  49302. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49303. }
  49304. else {
  49305. this.position.copyFrom(this._newPosition);
  49306. var up = this.upVector;
  49307. if (this.allowUpsideDown && sinb < 0) {
  49308. up = up.clone();
  49309. up = up.negate();
  49310. }
  49311. this._computeViewMatrix(this.position, target, up);
  49312. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49313. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49314. }
  49315. this._currentTarget = target;
  49316. return this._viewMatrix;
  49317. };
  49318. /**
  49319. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  49320. * @param meshes Defines the mesh to zoom on
  49321. * @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)
  49322. */
  49323. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49324. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49325. meshes = meshes || this.getScene().meshes;
  49326. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49327. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49328. this.radius = distance * this.zoomOnFactor;
  49329. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49330. };
  49331. /**
  49332. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  49333. * The target will be changed but the radius
  49334. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  49335. * @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)
  49336. */
  49337. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49338. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49339. var meshesOrMinMaxVector;
  49340. var distance;
  49341. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49342. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49343. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49344. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49345. }
  49346. else { //minMaxVector and distance
  49347. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49348. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49349. distance = minMaxVectorAndDistance.distance;
  49350. }
  49351. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49352. if (!doNotUpdateMaxZ) {
  49353. this.maxZ = distance * 2;
  49354. }
  49355. };
  49356. /**
  49357. * @override
  49358. * Override Camera.createRigCamera
  49359. */
  49360. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49361. var alphaShift = 0;
  49362. switch (this.cameraRigMode) {
  49363. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49364. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49365. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49366. case BABYLON.Camera.RIG_MODE_VR:
  49367. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49368. break;
  49369. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49370. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49371. break;
  49372. }
  49373. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49374. rigCam._cameraRigParams = {};
  49375. return rigCam;
  49376. };
  49377. /**
  49378. * @hidden
  49379. * @override
  49380. * Override Camera._updateRigCameras
  49381. */
  49382. ArcRotateCamera.prototype._updateRigCameras = function () {
  49383. var camLeft = this._rigCameras[0];
  49384. var camRight = this._rigCameras[1];
  49385. camLeft.beta = camRight.beta = this.beta;
  49386. camLeft.radius = camRight.radius = this.radius;
  49387. switch (this.cameraRigMode) {
  49388. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49389. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49390. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49391. case BABYLON.Camera.RIG_MODE_VR:
  49392. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49393. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49394. break;
  49395. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49396. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49397. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49398. break;
  49399. }
  49400. _super.prototype._updateRigCameras.call(this);
  49401. };
  49402. /**
  49403. * Destroy the camera and release the current resources hold by it.
  49404. */
  49405. ArcRotateCamera.prototype.dispose = function () {
  49406. this.inputs.clear();
  49407. _super.prototype.dispose.call(this);
  49408. };
  49409. /**
  49410. * Gets the current object class name.
  49411. * @return the class name
  49412. */
  49413. ArcRotateCamera.prototype.getClassName = function () {
  49414. return "ArcRotateCamera";
  49415. };
  49416. __decorate([
  49417. BABYLON.serialize()
  49418. ], ArcRotateCamera.prototype, "alpha", void 0);
  49419. __decorate([
  49420. BABYLON.serialize()
  49421. ], ArcRotateCamera.prototype, "beta", void 0);
  49422. __decorate([
  49423. BABYLON.serialize()
  49424. ], ArcRotateCamera.prototype, "radius", void 0);
  49425. __decorate([
  49426. BABYLON.serializeAsVector3("target")
  49427. ], ArcRotateCamera.prototype, "_target", void 0);
  49428. __decorate([
  49429. BABYLON.serialize()
  49430. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49431. __decorate([
  49432. BABYLON.serialize()
  49433. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49434. __decorate([
  49435. BABYLON.serialize()
  49436. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49437. __decorate([
  49438. BABYLON.serialize()
  49439. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49440. __decorate([
  49441. BABYLON.serialize()
  49442. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49443. __decorate([
  49444. BABYLON.serialize()
  49445. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49446. __decorate([
  49447. BABYLON.serialize()
  49448. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49449. __decorate([
  49450. BABYLON.serialize()
  49451. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49452. __decorate([
  49453. BABYLON.serialize()
  49454. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49455. __decorate([
  49456. BABYLON.serialize()
  49457. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49458. __decorate([
  49459. BABYLON.serialize()
  49460. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49461. __decorate([
  49462. BABYLON.serialize()
  49463. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49464. __decorate([
  49465. BABYLON.serialize()
  49466. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49467. __decorate([
  49468. BABYLON.serializeAsVector3()
  49469. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49470. __decorate([
  49471. BABYLON.serialize()
  49472. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49473. __decorate([
  49474. BABYLON.serialize()
  49475. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49476. __decorate([
  49477. BABYLON.serialize()
  49478. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49479. __decorate([
  49480. BABYLON.serialize()
  49481. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49482. __decorate([
  49483. BABYLON.serialize()
  49484. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  49485. return ArcRotateCamera;
  49486. }(BABYLON.TargetCamera));
  49487. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49488. })(BABYLON || (BABYLON = {}));
  49489. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49490. var BABYLON;
  49491. (function (BABYLON) {
  49492. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49493. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49494. });
  49495. /**
  49496. * The HemisphericLight simulates the ambient environment light,
  49497. * so the passed direction is the light reflection direction, not the incoming direction.
  49498. */
  49499. var HemisphericLight = /** @class */ (function (_super) {
  49500. __extends(HemisphericLight, _super);
  49501. /**
  49502. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49503. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49504. * The HemisphericLight can't cast shadows.
  49505. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49506. * @param name The friendly name of the light
  49507. * @param direction The direction of the light reflection
  49508. * @param scene The scene the light belongs to
  49509. */
  49510. function HemisphericLight(name, direction, scene) {
  49511. var _this = _super.call(this, name, scene) || this;
  49512. /**
  49513. * The groundColor is the light in the opposite direction to the one specified during creation.
  49514. * 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.
  49515. */
  49516. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49517. _this.direction = direction || BABYLON.Vector3.Up();
  49518. return _this;
  49519. }
  49520. HemisphericLight.prototype._buildUniformLayout = function () {
  49521. this._uniformBuffer.addUniform("vLightData", 4);
  49522. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49523. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49524. this._uniformBuffer.addUniform("vLightGround", 3);
  49525. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49526. this._uniformBuffer.addUniform("depthValues", 2);
  49527. this._uniformBuffer.create();
  49528. };
  49529. /**
  49530. * Returns the string "HemisphericLight".
  49531. * @return The class name
  49532. */
  49533. HemisphericLight.prototype.getClassName = function () {
  49534. return "HemisphericLight";
  49535. };
  49536. /**
  49537. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49538. * Returns the updated direction.
  49539. * @param target The target the direction should point to
  49540. * @return The computed direction
  49541. */
  49542. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49543. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49544. return this.direction;
  49545. };
  49546. /**
  49547. * Returns the shadow generator associated to the light.
  49548. * @returns Always null for hemispheric lights because it does not support shadows.
  49549. */
  49550. HemisphericLight.prototype.getShadowGenerator = function () {
  49551. return null;
  49552. };
  49553. /**
  49554. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49555. * @param effect The effect to update
  49556. * @param lightIndex The index of the light in the effect to update
  49557. * @returns The hemispheric light
  49558. */
  49559. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49560. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49561. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49562. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49563. return this;
  49564. };
  49565. /**
  49566. * Computes the world matrix of the node
  49567. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49568. * @param useWasUpdatedFlag defines a reserved property
  49569. * @returns the world matrix
  49570. */
  49571. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  49572. if (!this._worldMatrix) {
  49573. this._worldMatrix = BABYLON.Matrix.Identity();
  49574. }
  49575. return this._worldMatrix;
  49576. };
  49577. /**
  49578. * Returns the integer 3.
  49579. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49580. */
  49581. HemisphericLight.prototype.getTypeID = function () {
  49582. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49583. };
  49584. /**
  49585. * Prepares the list of defines specific to the light type.
  49586. * @param defines the list of defines
  49587. * @param lightIndex defines the index of the light for the effect
  49588. */
  49589. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49590. defines["HEMILIGHT" + lightIndex] = true;
  49591. };
  49592. __decorate([
  49593. BABYLON.serializeAsColor3()
  49594. ], HemisphericLight.prototype, "groundColor", void 0);
  49595. __decorate([
  49596. BABYLON.serializeAsVector3()
  49597. ], HemisphericLight.prototype, "direction", void 0);
  49598. return HemisphericLight;
  49599. }(BABYLON.Light));
  49600. BABYLON.HemisphericLight = HemisphericLight;
  49601. })(BABYLON || (BABYLON = {}));
  49602. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49603. var BABYLON;
  49604. (function (BABYLON) {
  49605. /**
  49606. * Base implementation IShadowLight
  49607. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49608. */
  49609. var ShadowLight = /** @class */ (function (_super) {
  49610. __extends(ShadowLight, _super);
  49611. function ShadowLight() {
  49612. var _this = _super !== null && _super.apply(this, arguments) || this;
  49613. _this._needProjectionMatrixCompute = true;
  49614. return _this;
  49615. }
  49616. ShadowLight.prototype._setPosition = function (value) {
  49617. this._position = value;
  49618. };
  49619. Object.defineProperty(ShadowLight.prototype, "position", {
  49620. /**
  49621. * Sets the position the shadow will be casted from. Also use as the light position for both
  49622. * point and spot lights.
  49623. */
  49624. get: function () {
  49625. return this._position;
  49626. },
  49627. /**
  49628. * Sets the position the shadow will be casted from. Also use as the light position for both
  49629. * point and spot lights.
  49630. */
  49631. set: function (value) {
  49632. this._setPosition(value);
  49633. },
  49634. enumerable: true,
  49635. configurable: true
  49636. });
  49637. ShadowLight.prototype._setDirection = function (value) {
  49638. this._direction = value;
  49639. };
  49640. Object.defineProperty(ShadowLight.prototype, "direction", {
  49641. /**
  49642. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49643. * Also use as the light direction on spot and directional lights.
  49644. */
  49645. get: function () {
  49646. return this._direction;
  49647. },
  49648. /**
  49649. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49650. * Also use as the light direction on spot and directional lights.
  49651. */
  49652. set: function (value) {
  49653. this._setDirection(value);
  49654. },
  49655. enumerable: true,
  49656. configurable: true
  49657. });
  49658. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49659. /**
  49660. * Gets the shadow projection clipping minimum z value.
  49661. */
  49662. get: function () {
  49663. return this._shadowMinZ;
  49664. },
  49665. /**
  49666. * Sets the shadow projection clipping minimum z value.
  49667. */
  49668. set: function (value) {
  49669. this._shadowMinZ = value;
  49670. this.forceProjectionMatrixCompute();
  49671. },
  49672. enumerable: true,
  49673. configurable: true
  49674. });
  49675. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49676. /**
  49677. * Sets the shadow projection clipping maximum z value.
  49678. */
  49679. get: function () {
  49680. return this._shadowMaxZ;
  49681. },
  49682. /**
  49683. * Gets the shadow projection clipping maximum z value.
  49684. */
  49685. set: function (value) {
  49686. this._shadowMaxZ = value;
  49687. this.forceProjectionMatrixCompute();
  49688. },
  49689. enumerable: true,
  49690. configurable: true
  49691. });
  49692. /**
  49693. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49694. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49695. */
  49696. ShadowLight.prototype.computeTransformedInformation = function () {
  49697. if (this.parent && this.parent.getWorldMatrix) {
  49698. if (!this.transformedPosition) {
  49699. this.transformedPosition = BABYLON.Vector3.Zero();
  49700. }
  49701. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49702. // In case the direction is present.
  49703. if (this.direction) {
  49704. if (!this.transformedDirection) {
  49705. this.transformedDirection = BABYLON.Vector3.Zero();
  49706. }
  49707. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49708. }
  49709. return true;
  49710. }
  49711. return false;
  49712. };
  49713. /**
  49714. * Return the depth scale used for the shadow map.
  49715. * @returns the depth scale.
  49716. */
  49717. ShadowLight.prototype.getDepthScale = function () {
  49718. return 50.0;
  49719. };
  49720. /**
  49721. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49722. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49723. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49724. */
  49725. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49726. return this.transformedDirection ? this.transformedDirection : this.direction;
  49727. };
  49728. /**
  49729. * Returns the ShadowLight absolute position in the World.
  49730. * @returns the position vector in world space
  49731. */
  49732. ShadowLight.prototype.getAbsolutePosition = function () {
  49733. return this.transformedPosition ? this.transformedPosition : this.position;
  49734. };
  49735. /**
  49736. * Sets the ShadowLight direction toward the passed target.
  49737. * @param target The point tot target in local space
  49738. * @returns the updated ShadowLight direction
  49739. */
  49740. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49741. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49742. return this.direction;
  49743. };
  49744. /**
  49745. * Returns the light rotation in euler definition.
  49746. * @returns the x y z rotation in local space.
  49747. */
  49748. ShadowLight.prototype.getRotation = function () {
  49749. this.direction.normalize();
  49750. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49751. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49752. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49753. };
  49754. /**
  49755. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49756. * @returns true if a cube texture needs to be use
  49757. */
  49758. ShadowLight.prototype.needCube = function () {
  49759. return false;
  49760. };
  49761. /**
  49762. * Detects if the projection matrix requires to be recomputed this frame.
  49763. * @returns true if it requires to be recomputed otherwise, false.
  49764. */
  49765. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49766. return this._needProjectionMatrixCompute;
  49767. };
  49768. /**
  49769. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49770. */
  49771. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49772. this._needProjectionMatrixCompute = true;
  49773. };
  49774. /** @hidden */
  49775. ShadowLight.prototype._initCache = function () {
  49776. _super.prototype._initCache.call(this);
  49777. this._cache.position = BABYLON.Vector3.Zero();
  49778. };
  49779. /** @hidden */
  49780. ShadowLight.prototype._isSynchronized = function () {
  49781. if (!this._cache.position.equals(this.position))
  49782. return false;
  49783. return true;
  49784. };
  49785. /**
  49786. * Computes the world matrix of the node
  49787. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49788. * @returns the world matrix
  49789. */
  49790. ShadowLight.prototype.computeWorldMatrix = function (force) {
  49791. if (!force && this.isSynchronized()) {
  49792. this._currentRenderId = this.getScene().getRenderId();
  49793. return this._worldMatrix;
  49794. }
  49795. this._updateCache();
  49796. this._cache.position.copyFrom(this.position);
  49797. if (!this._worldMatrix) {
  49798. this._worldMatrix = BABYLON.Matrix.Identity();
  49799. }
  49800. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49801. if (this.parent && this.parent.getWorldMatrix) {
  49802. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  49803. this._markSyncedWithParent();
  49804. }
  49805. // Cache the determinant
  49806. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  49807. return this._worldMatrix;
  49808. };
  49809. /**
  49810. * Gets the minZ used for shadow according to both the scene and the light.
  49811. * @param activeCamera The camera we are returning the min for
  49812. * @returns the depth min z
  49813. */
  49814. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49815. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49816. };
  49817. /**
  49818. * Gets the maxZ used for shadow according to both the scene and the light.
  49819. * @param activeCamera The camera we are returning the max for
  49820. * @returns the depth max z
  49821. */
  49822. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49823. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49824. };
  49825. /**
  49826. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49827. * @param matrix The materix to updated with the projection information
  49828. * @param viewMatrix The transform matrix of the light
  49829. * @param renderList The list of mesh to render in the map
  49830. * @returns The current light
  49831. */
  49832. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49833. if (this.customProjectionMatrixBuilder) {
  49834. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49835. }
  49836. else {
  49837. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49838. }
  49839. return this;
  49840. };
  49841. __decorate([
  49842. BABYLON.serializeAsVector3()
  49843. ], ShadowLight.prototype, "position", null);
  49844. __decorate([
  49845. BABYLON.serializeAsVector3()
  49846. ], ShadowLight.prototype, "direction", null);
  49847. __decorate([
  49848. BABYLON.serialize()
  49849. ], ShadowLight.prototype, "shadowMinZ", null);
  49850. __decorate([
  49851. BABYLON.serialize()
  49852. ], ShadowLight.prototype, "shadowMaxZ", null);
  49853. return ShadowLight;
  49854. }(BABYLON.Light));
  49855. BABYLON.ShadowLight = ShadowLight;
  49856. })(BABYLON || (BABYLON = {}));
  49857. //# sourceMappingURL=babylon.shadowLight.js.map
  49858. var BABYLON;
  49859. (function (BABYLON) {
  49860. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49861. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49862. });
  49863. /**
  49864. * A point light is a light defined by an unique point in world space.
  49865. * The light is emitted in every direction from this point.
  49866. * A good example of a point light is a standard light bulb.
  49867. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49868. */
  49869. var PointLight = /** @class */ (function (_super) {
  49870. __extends(PointLight, _super);
  49871. /**
  49872. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49873. * A PointLight emits the light in every direction.
  49874. * It can cast shadows.
  49875. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49876. * ```javascript
  49877. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49878. * ```
  49879. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49880. * @param name The light friendly name
  49881. * @param position The position of the point light in the scene
  49882. * @param scene The scene the lights belongs to
  49883. */
  49884. function PointLight(name, position, scene) {
  49885. var _this = _super.call(this, name, scene) || this;
  49886. _this._shadowAngle = Math.PI / 2;
  49887. _this.position = position;
  49888. return _this;
  49889. }
  49890. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49891. /**
  49892. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49893. * This specifies what angle the shadow will use to be created.
  49894. *
  49895. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49896. */
  49897. get: function () {
  49898. return this._shadowAngle;
  49899. },
  49900. /**
  49901. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49902. * This specifies what angle the shadow will use to be created.
  49903. *
  49904. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49905. */
  49906. set: function (value) {
  49907. this._shadowAngle = value;
  49908. this.forceProjectionMatrixCompute();
  49909. },
  49910. enumerable: true,
  49911. configurable: true
  49912. });
  49913. Object.defineProperty(PointLight.prototype, "direction", {
  49914. /**
  49915. * Gets the direction if it has been set.
  49916. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49917. */
  49918. get: function () {
  49919. return this._direction;
  49920. },
  49921. /**
  49922. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49923. */
  49924. set: function (value) {
  49925. var previousNeedCube = this.needCube();
  49926. this._direction = value;
  49927. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49928. this._shadowGenerator.recreateShadowMap();
  49929. }
  49930. },
  49931. enumerable: true,
  49932. configurable: true
  49933. });
  49934. /**
  49935. * Returns the string "PointLight"
  49936. * @returns the class name
  49937. */
  49938. PointLight.prototype.getClassName = function () {
  49939. return "PointLight";
  49940. };
  49941. /**
  49942. * Returns the integer 0.
  49943. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49944. */
  49945. PointLight.prototype.getTypeID = function () {
  49946. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49947. };
  49948. /**
  49949. * Specifies wether or not the shadowmap should be a cube texture.
  49950. * @returns true if the shadowmap needs to be a cube texture.
  49951. */
  49952. PointLight.prototype.needCube = function () {
  49953. return !this.direction;
  49954. };
  49955. /**
  49956. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49957. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49958. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49959. */
  49960. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49961. if (this.direction) {
  49962. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49963. }
  49964. else {
  49965. switch (faceIndex) {
  49966. case 0:
  49967. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49968. case 1:
  49969. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49970. case 2:
  49971. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49972. case 3:
  49973. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49974. case 4:
  49975. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49976. case 5:
  49977. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49978. }
  49979. }
  49980. return BABYLON.Vector3.Zero();
  49981. };
  49982. /**
  49983. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49984. * - fov = PI / 2
  49985. * - aspect ratio : 1.0
  49986. * - z-near and far equal to the active camera minZ and maxZ.
  49987. * Returns the PointLight.
  49988. */
  49989. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49990. var activeCamera = this.getScene().activeCamera;
  49991. if (!activeCamera) {
  49992. return;
  49993. }
  49994. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49995. };
  49996. PointLight.prototype._buildUniformLayout = function () {
  49997. this._uniformBuffer.addUniform("vLightData", 4);
  49998. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49999. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50000. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50001. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50002. this._uniformBuffer.addUniform("depthValues", 2);
  50003. this._uniformBuffer.create();
  50004. };
  50005. /**
  50006. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50007. * @param effect The effect to update
  50008. * @param lightIndex The index of the light in the effect to update
  50009. * @returns The point light
  50010. */
  50011. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50012. if (this.computeTransformedInformation()) {
  50013. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50014. }
  50015. else {
  50016. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50017. }
  50018. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  50019. return this;
  50020. };
  50021. /**
  50022. * Prepares the list of defines specific to the light type.
  50023. * @param defines the list of defines
  50024. * @param lightIndex defines the index of the light for the effect
  50025. */
  50026. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50027. defines["POINTLIGHT" + lightIndex] = true;
  50028. };
  50029. __decorate([
  50030. BABYLON.serialize()
  50031. ], PointLight.prototype, "shadowAngle", null);
  50032. return PointLight;
  50033. }(BABYLON.ShadowLight));
  50034. BABYLON.PointLight = PointLight;
  50035. })(BABYLON || (BABYLON = {}));
  50036. //# sourceMappingURL=babylon.pointLight.js.map
  50037. var BABYLON;
  50038. (function (BABYLON) {
  50039. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  50040. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  50041. });
  50042. /**
  50043. * A directional light is defined by a direction (what a surprise!).
  50044. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50045. * 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.
  50046. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50047. */
  50048. var DirectionalLight = /** @class */ (function (_super) {
  50049. __extends(DirectionalLight, _super);
  50050. /**
  50051. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50052. * The directional light is emitted from everywhere in the given direction.
  50053. * It can cast shadows.
  50054. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50055. * @param name The friendly name of the light
  50056. * @param direction The direction of the light
  50057. * @param scene The scene the light belongs to
  50058. */
  50059. function DirectionalLight(name, direction, scene) {
  50060. var _this = _super.call(this, name, scene) || this;
  50061. _this._shadowFrustumSize = 0;
  50062. _this._shadowOrthoScale = 0.1;
  50063. /**
  50064. * Automatically compute the projection matrix to best fit (including all the casters)
  50065. * on each frame.
  50066. */
  50067. _this.autoUpdateExtends = true;
  50068. // Cache
  50069. _this._orthoLeft = Number.MAX_VALUE;
  50070. _this._orthoRight = Number.MIN_VALUE;
  50071. _this._orthoTop = Number.MIN_VALUE;
  50072. _this._orthoBottom = Number.MAX_VALUE;
  50073. _this.position = direction.scale(-1.0);
  50074. _this.direction = direction;
  50075. return _this;
  50076. }
  50077. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50078. /**
  50079. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50080. */
  50081. get: function () {
  50082. return this._shadowFrustumSize;
  50083. },
  50084. /**
  50085. * Specifies a fix frustum size for the shadow generation.
  50086. */
  50087. set: function (value) {
  50088. this._shadowFrustumSize = value;
  50089. this.forceProjectionMatrixCompute();
  50090. },
  50091. enumerable: true,
  50092. configurable: true
  50093. });
  50094. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50095. /**
  50096. * Gets the shadow projection scale against the optimal computed one.
  50097. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50098. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50099. */
  50100. get: function () {
  50101. return this._shadowOrthoScale;
  50102. },
  50103. /**
  50104. * Sets the shadow projection scale against the optimal computed one.
  50105. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50106. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50107. */
  50108. set: function (value) {
  50109. this._shadowOrthoScale = value;
  50110. this.forceProjectionMatrixCompute();
  50111. },
  50112. enumerable: true,
  50113. configurable: true
  50114. });
  50115. /**
  50116. * Returns the string "DirectionalLight".
  50117. * @return The class name
  50118. */
  50119. DirectionalLight.prototype.getClassName = function () {
  50120. return "DirectionalLight";
  50121. };
  50122. /**
  50123. * Returns the integer 1.
  50124. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50125. */
  50126. DirectionalLight.prototype.getTypeID = function () {
  50127. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50128. };
  50129. /**
  50130. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50131. * Returns the DirectionalLight Shadow projection matrix.
  50132. */
  50133. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50134. if (this.shadowFrustumSize > 0) {
  50135. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50136. }
  50137. else {
  50138. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50139. }
  50140. };
  50141. /**
  50142. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50143. * Returns the DirectionalLight Shadow projection matrix.
  50144. */
  50145. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50146. var activeCamera = this.getScene().activeCamera;
  50147. if (!activeCamera) {
  50148. return;
  50149. }
  50150. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50151. };
  50152. /**
  50153. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50154. * Returns the DirectionalLight Shadow projection matrix.
  50155. */
  50156. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50157. var activeCamera = this.getScene().activeCamera;
  50158. if (!activeCamera) {
  50159. return;
  50160. }
  50161. // Check extends
  50162. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50163. var tempVector3 = BABYLON.Vector3.Zero();
  50164. this._orthoLeft = Number.MAX_VALUE;
  50165. this._orthoRight = Number.MIN_VALUE;
  50166. this._orthoTop = Number.MIN_VALUE;
  50167. this._orthoBottom = Number.MAX_VALUE;
  50168. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50169. var mesh = renderList[meshIndex];
  50170. if (!mesh) {
  50171. continue;
  50172. }
  50173. var boundingInfo = mesh.getBoundingInfo();
  50174. var boundingBox = boundingInfo.boundingBox;
  50175. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50176. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50177. if (tempVector3.x < this._orthoLeft)
  50178. this._orthoLeft = tempVector3.x;
  50179. if (tempVector3.y < this._orthoBottom)
  50180. this._orthoBottom = tempVector3.y;
  50181. if (tempVector3.x > this._orthoRight)
  50182. this._orthoRight = tempVector3.x;
  50183. if (tempVector3.y > this._orthoTop)
  50184. this._orthoTop = tempVector3.y;
  50185. }
  50186. }
  50187. }
  50188. var xOffset = this._orthoRight - this._orthoLeft;
  50189. var yOffset = this._orthoTop - this._orthoBottom;
  50190. 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);
  50191. };
  50192. DirectionalLight.prototype._buildUniformLayout = function () {
  50193. this._uniformBuffer.addUniform("vLightData", 4);
  50194. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50195. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50196. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50197. this._uniformBuffer.addUniform("depthValues", 2);
  50198. this._uniformBuffer.create();
  50199. };
  50200. /**
  50201. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50202. * @param effect The effect to update
  50203. * @param lightIndex The index of the light in the effect to update
  50204. * @returns The directional light
  50205. */
  50206. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50207. if (this.computeTransformedInformation()) {
  50208. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50209. return this;
  50210. }
  50211. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50212. return this;
  50213. };
  50214. /**
  50215. * Gets the minZ used for shadow according to both the scene and the light.
  50216. *
  50217. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50218. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50219. * @param activeCamera The camera we are returning the min for
  50220. * @returns the depth min z
  50221. */
  50222. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50223. return 1;
  50224. };
  50225. /**
  50226. * Gets the maxZ used for shadow according to both the scene and the light.
  50227. *
  50228. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50229. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50230. * @param activeCamera The camera we are returning the max for
  50231. * @returns the depth max z
  50232. */
  50233. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50234. return 1;
  50235. };
  50236. /**
  50237. * Prepares the list of defines specific to the light type.
  50238. * @param defines the list of defines
  50239. * @param lightIndex defines the index of the light for the effect
  50240. */
  50241. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50242. defines["DIRLIGHT" + lightIndex] = true;
  50243. };
  50244. __decorate([
  50245. BABYLON.serialize()
  50246. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50247. __decorate([
  50248. BABYLON.serialize()
  50249. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50250. __decorate([
  50251. BABYLON.serialize()
  50252. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50253. return DirectionalLight;
  50254. }(BABYLON.ShadowLight));
  50255. BABYLON.DirectionalLight = DirectionalLight;
  50256. })(BABYLON || (BABYLON = {}));
  50257. //# sourceMappingURL=babylon.directionalLight.js.map
  50258. var BABYLON;
  50259. (function (BABYLON) {
  50260. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  50261. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  50262. });
  50263. /**
  50264. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50265. * These values define a cone of light starting from the position, emitting toward the direction.
  50266. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50267. * and the exponent defines the speed of the decay of the light with distance (reach).
  50268. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50269. */
  50270. var SpotLight = /** @class */ (function (_super) {
  50271. __extends(SpotLight, _super);
  50272. /**
  50273. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50274. * It can cast shadows.
  50275. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50276. * @param name The light friendly name
  50277. * @param position The position of the spot light in the scene
  50278. * @param direction The direction of the light in the scene
  50279. * @param angle The cone angle of the light in Radians
  50280. * @param exponent The light decay speed with the distance from the emission spot
  50281. * @param scene The scene the lights belongs to
  50282. */
  50283. function SpotLight(name, position, direction, angle, exponent, scene) {
  50284. var _this = _super.call(this, name, scene) || this;
  50285. _this._innerAngle = 0;
  50286. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50287. _this._projectionTextureLightNear = 1e-6;
  50288. _this._projectionTextureLightFar = 1000.0;
  50289. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50290. _this._projectionTextureViewLightDirty = true;
  50291. _this._projectionTextureProjectionLightDirty = true;
  50292. _this._projectionTextureDirty = true;
  50293. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50294. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50295. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50296. _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);
  50297. _this.position = position;
  50298. _this.direction = direction;
  50299. _this.angle = angle;
  50300. _this.exponent = exponent;
  50301. return _this;
  50302. }
  50303. Object.defineProperty(SpotLight.prototype, "angle", {
  50304. /**
  50305. * Gets the cone angle of the spot light in Radians.
  50306. */
  50307. get: function () {
  50308. return this._angle;
  50309. },
  50310. /**
  50311. * Sets the cone angle of the spot light in Radians.
  50312. */
  50313. set: function (value) {
  50314. this._angle = value;
  50315. this._cosHalfAngle = Math.cos(value * 0.5);
  50316. this._projectionTextureProjectionLightDirty = true;
  50317. this.forceProjectionMatrixCompute();
  50318. this._computeAngleValues();
  50319. },
  50320. enumerable: true,
  50321. configurable: true
  50322. });
  50323. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  50324. /**
  50325. * Only used in gltf falloff mode, this defines the angle where
  50326. * the directional falloff will start before cutting at angle which could be seen
  50327. * as outer angle.
  50328. */
  50329. get: function () {
  50330. return this._innerAngle;
  50331. },
  50332. /**
  50333. * Only used in gltf falloff mode, this defines the angle where
  50334. * the directional falloff will start before cutting at angle which could be seen
  50335. * as outer angle.
  50336. */
  50337. set: function (value) {
  50338. this._innerAngle = value;
  50339. this._computeAngleValues();
  50340. },
  50341. enumerable: true,
  50342. configurable: true
  50343. });
  50344. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50345. /**
  50346. * Allows scaling the angle of the light for shadow generation only.
  50347. */
  50348. get: function () {
  50349. return this._shadowAngleScale;
  50350. },
  50351. /**
  50352. * Allows scaling the angle of the light for shadow generation only.
  50353. */
  50354. set: function (value) {
  50355. this._shadowAngleScale = value;
  50356. this.forceProjectionMatrixCompute();
  50357. },
  50358. enumerable: true,
  50359. configurable: true
  50360. });
  50361. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50362. /**
  50363. * Allows reading the projecton texture
  50364. */
  50365. get: function () {
  50366. return this._projectionTextureMatrix;
  50367. },
  50368. enumerable: true,
  50369. configurable: true
  50370. });
  50371. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50372. /**
  50373. * Gets the near clip of the Spotlight for texture projection.
  50374. */
  50375. get: function () {
  50376. return this._projectionTextureLightNear;
  50377. },
  50378. /**
  50379. * Sets the near clip of the Spotlight for texture projection.
  50380. */
  50381. set: function (value) {
  50382. this._projectionTextureLightNear = value;
  50383. this._projectionTextureProjectionLightDirty = true;
  50384. },
  50385. enumerable: true,
  50386. configurable: true
  50387. });
  50388. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50389. /**
  50390. * Gets the far clip of the Spotlight for texture projection.
  50391. */
  50392. get: function () {
  50393. return this._projectionTextureLightFar;
  50394. },
  50395. /**
  50396. * Sets the far clip of the Spotlight for texture projection.
  50397. */
  50398. set: function (value) {
  50399. this._projectionTextureLightFar = value;
  50400. this._projectionTextureProjectionLightDirty = true;
  50401. },
  50402. enumerable: true,
  50403. configurable: true
  50404. });
  50405. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50406. /**
  50407. * Gets the Up vector of the Spotlight for texture projection.
  50408. */
  50409. get: function () {
  50410. return this._projectionTextureUpDirection;
  50411. },
  50412. /**
  50413. * Sets the Up vector of the Spotlight for texture projection.
  50414. */
  50415. set: function (value) {
  50416. this._projectionTextureUpDirection = value;
  50417. this._projectionTextureProjectionLightDirty = true;
  50418. },
  50419. enumerable: true,
  50420. configurable: true
  50421. });
  50422. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50423. /**
  50424. * Gets the projection texture of the light.
  50425. */
  50426. get: function () {
  50427. return this._projectionTexture;
  50428. },
  50429. /**
  50430. * Sets the projection texture of the light.
  50431. */
  50432. set: function (value) {
  50433. this._projectionTexture = value;
  50434. this._projectionTextureDirty = true;
  50435. },
  50436. enumerable: true,
  50437. configurable: true
  50438. });
  50439. /**
  50440. * Returns the string "SpotLight".
  50441. * @returns the class name
  50442. */
  50443. SpotLight.prototype.getClassName = function () {
  50444. return "SpotLight";
  50445. };
  50446. /**
  50447. * Returns the integer 2.
  50448. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50449. */
  50450. SpotLight.prototype.getTypeID = function () {
  50451. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50452. };
  50453. /**
  50454. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50455. */
  50456. SpotLight.prototype._setDirection = function (value) {
  50457. _super.prototype._setDirection.call(this, value);
  50458. this._projectionTextureViewLightDirty = true;
  50459. };
  50460. /**
  50461. * Overrides the position setter to recompute the projection texture view light Matrix.
  50462. */
  50463. SpotLight.prototype._setPosition = function (value) {
  50464. _super.prototype._setPosition.call(this, value);
  50465. this._projectionTextureViewLightDirty = true;
  50466. };
  50467. /**
  50468. * 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.
  50469. * Returns the SpotLight.
  50470. */
  50471. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50472. var activeCamera = this.getScene().activeCamera;
  50473. if (!activeCamera) {
  50474. return;
  50475. }
  50476. this._shadowAngleScale = this._shadowAngleScale || 1;
  50477. var angle = this._shadowAngleScale * this._angle;
  50478. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50479. };
  50480. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50481. this._projectionTextureViewLightDirty = false;
  50482. this._projectionTextureDirty = true;
  50483. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50484. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50485. };
  50486. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50487. this._projectionTextureProjectionLightDirty = false;
  50488. this._projectionTextureDirty = true;
  50489. var light_far = this.projectionTextureLightFar;
  50490. var light_near = this.projectionTextureLightNear;
  50491. var P = light_far / (light_far - light_near);
  50492. var Q = -P * light_near;
  50493. var S = 1.0 / Math.tan(this._angle / 2.0);
  50494. var A = 1.0;
  50495. 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);
  50496. };
  50497. /**
  50498. * Main function for light texture projection matrix computing.
  50499. */
  50500. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50501. this._projectionTextureDirty = false;
  50502. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50503. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50504. };
  50505. SpotLight.prototype._buildUniformLayout = function () {
  50506. this._uniformBuffer.addUniform("vLightData", 4);
  50507. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50508. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50509. this._uniformBuffer.addUniform("vLightDirection", 3);
  50510. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50511. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50512. this._uniformBuffer.addUniform("depthValues", 2);
  50513. this._uniformBuffer.create();
  50514. };
  50515. SpotLight.prototype._computeAngleValues = function () {
  50516. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50517. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50518. };
  50519. /**
  50520. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50521. * @param effect The effect to update
  50522. * @param lightIndex The index of the light in the effect to update
  50523. * @returns The spot light
  50524. */
  50525. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50526. var normalizeDirection;
  50527. if (this.computeTransformedInformation()) {
  50528. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50529. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50530. }
  50531. else {
  50532. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50533. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50534. }
  50535. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  50536. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  50537. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50538. if (this._projectionTextureViewLightDirty) {
  50539. this._computeProjectionTextureViewLightMatrix();
  50540. }
  50541. if (this._projectionTextureProjectionLightDirty) {
  50542. this._computeProjectionTextureProjectionLightMatrix();
  50543. }
  50544. if (this._projectionTextureDirty) {
  50545. this._computeProjectionTextureMatrix();
  50546. }
  50547. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50548. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50549. }
  50550. return this;
  50551. };
  50552. /**
  50553. * Disposes the light and the associated resources.
  50554. */
  50555. SpotLight.prototype.dispose = function () {
  50556. _super.prototype.dispose.call(this);
  50557. if (this._projectionTexture) {
  50558. this._projectionTexture.dispose();
  50559. }
  50560. };
  50561. /**
  50562. * Prepares the list of defines specific to the light type.
  50563. * @param defines the list of defines
  50564. * @param lightIndex defines the index of the light for the effect
  50565. */
  50566. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50567. defines["SPOTLIGHT" + lightIndex] = true;
  50568. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  50569. };
  50570. __decorate([
  50571. BABYLON.serialize()
  50572. ], SpotLight.prototype, "angle", null);
  50573. __decorate([
  50574. BABYLON.serialize()
  50575. ], SpotLight.prototype, "innerAngle", null);
  50576. __decorate([
  50577. BABYLON.serialize()
  50578. ], SpotLight.prototype, "shadowAngleScale", null);
  50579. __decorate([
  50580. BABYLON.serialize()
  50581. ], SpotLight.prototype, "exponent", void 0);
  50582. __decorate([
  50583. BABYLON.serialize()
  50584. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50585. __decorate([
  50586. BABYLON.serialize()
  50587. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50588. __decorate([
  50589. BABYLON.serialize()
  50590. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50591. __decorate([
  50592. BABYLON.serializeAsTexture("projectedLightTexture")
  50593. ], SpotLight.prototype, "_projectionTexture", void 0);
  50594. return SpotLight;
  50595. }(BABYLON.ShadowLight));
  50596. BABYLON.SpotLight = SpotLight;
  50597. })(BABYLON || (BABYLON = {}));
  50598. //# sourceMappingURL=babylon.spotLight.js.map
  50599. var BABYLON;
  50600. (function (BABYLON) {
  50601. /**
  50602. * Class used to override all child animations of a given target
  50603. */
  50604. var AnimationPropertiesOverride = /** @class */ (function () {
  50605. function AnimationPropertiesOverride() {
  50606. /**
  50607. * Gets or sets a value indicating if animation blending must be used
  50608. */
  50609. this.enableBlending = false;
  50610. /**
  50611. * Gets or sets the blending speed to use when enableBlending is true
  50612. */
  50613. this.blendingSpeed = 0.01;
  50614. /**
  50615. * Gets or sets the default loop mode to use
  50616. */
  50617. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50618. }
  50619. return AnimationPropertiesOverride;
  50620. }());
  50621. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50622. })(BABYLON || (BABYLON = {}));
  50623. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50624. var BABYLON;
  50625. (function (BABYLON) {
  50626. /**
  50627. * Represents the range of an animation
  50628. */
  50629. var AnimationRange = /** @class */ (function () {
  50630. /**
  50631. * Initializes the range of an animation
  50632. * @param name The name of the animation range
  50633. * @param from The starting frame of the animation
  50634. * @param to The ending frame of the animation
  50635. */
  50636. function AnimationRange(
  50637. /**The name of the animation range**/
  50638. name,
  50639. /**The starting frame of the animation */
  50640. from,
  50641. /**The ending frame of the animation*/
  50642. to) {
  50643. this.name = name;
  50644. this.from = from;
  50645. this.to = to;
  50646. }
  50647. /**
  50648. * Makes a copy of the animation range
  50649. * @returns A copy of the animation range
  50650. */
  50651. AnimationRange.prototype.clone = function () {
  50652. return new AnimationRange(this.name, this.from, this.to);
  50653. };
  50654. return AnimationRange;
  50655. }());
  50656. BABYLON.AnimationRange = AnimationRange;
  50657. /**
  50658. * Composed of a frame, and an action function
  50659. */
  50660. var AnimationEvent = /** @class */ (function () {
  50661. /**
  50662. * Initializes the animation event
  50663. * @param frame The frame for which the event is triggered
  50664. * @param action The event to perform when triggered
  50665. * @param onlyOnce Specifies if the event should be triggered only once
  50666. */
  50667. function AnimationEvent(
  50668. /** The frame for which the event is triggered **/
  50669. frame,
  50670. /** The event to perform when triggered **/
  50671. action,
  50672. /** Specifies if the event should be triggered only once**/
  50673. onlyOnce) {
  50674. this.frame = frame;
  50675. this.action = action;
  50676. this.onlyOnce = onlyOnce;
  50677. /**
  50678. * Specifies if the animation event is done
  50679. */
  50680. this.isDone = false;
  50681. }
  50682. /** @hidden */
  50683. AnimationEvent.prototype._clone = function () {
  50684. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50685. };
  50686. return AnimationEvent;
  50687. }());
  50688. BABYLON.AnimationEvent = AnimationEvent;
  50689. /**
  50690. * A cursor which tracks a point on a path
  50691. */
  50692. var PathCursor = /** @class */ (function () {
  50693. /**
  50694. * Initializes the path cursor
  50695. * @param path The path to track
  50696. */
  50697. function PathCursor(path) {
  50698. this.path = path;
  50699. /**
  50700. * Stores path cursor callbacks for when an onchange event is triggered
  50701. */
  50702. this._onchange = new Array();
  50703. /**
  50704. * The value of the path cursor
  50705. */
  50706. this.value = 0;
  50707. /**
  50708. * The animation array of the path cursor
  50709. */
  50710. this.animations = new Array();
  50711. }
  50712. /**
  50713. * Gets the cursor point on the path
  50714. * @returns A point on the path cursor at the cursor location
  50715. */
  50716. PathCursor.prototype.getPoint = function () {
  50717. var point = this.path.getPointAtLengthPosition(this.value);
  50718. return new BABYLON.Vector3(point.x, 0, point.y);
  50719. };
  50720. /**
  50721. * Moves the cursor ahead by the step amount
  50722. * @param step The amount to move the cursor forward
  50723. * @returns This path cursor
  50724. */
  50725. PathCursor.prototype.moveAhead = function (step) {
  50726. if (step === void 0) { step = 0.002; }
  50727. this.move(step);
  50728. return this;
  50729. };
  50730. /**
  50731. * Moves the cursor behind by the step amount
  50732. * @param step The amount to move the cursor back
  50733. * @returns This path cursor
  50734. */
  50735. PathCursor.prototype.moveBack = function (step) {
  50736. if (step === void 0) { step = 0.002; }
  50737. this.move(-step);
  50738. return this;
  50739. };
  50740. /**
  50741. * Moves the cursor by the step amount
  50742. * If the step amount is greater than one, an exception is thrown
  50743. * @param step The amount to move the cursor
  50744. * @returns This path cursor
  50745. */
  50746. PathCursor.prototype.move = function (step) {
  50747. if (Math.abs(step) > 1) {
  50748. throw "step size should be less than 1.";
  50749. }
  50750. this.value += step;
  50751. this.ensureLimits();
  50752. this.raiseOnChange();
  50753. return this;
  50754. };
  50755. /**
  50756. * Ensures that the value is limited between zero and one
  50757. * @returns This path cursor
  50758. */
  50759. PathCursor.prototype.ensureLimits = function () {
  50760. while (this.value > 1) {
  50761. this.value -= 1;
  50762. }
  50763. while (this.value < 0) {
  50764. this.value += 1;
  50765. }
  50766. return this;
  50767. };
  50768. /**
  50769. * Runs onchange callbacks on change (used by the animation engine)
  50770. * @returns This path cursor
  50771. */
  50772. PathCursor.prototype.raiseOnChange = function () {
  50773. var _this = this;
  50774. this._onchange.forEach(function (f) { return f(_this); });
  50775. return this;
  50776. };
  50777. /**
  50778. * Executes a function on change
  50779. * @param f A path cursor onchange callback
  50780. * @returns This path cursor
  50781. */
  50782. PathCursor.prototype.onchange = function (f) {
  50783. this._onchange.push(f);
  50784. return this;
  50785. };
  50786. return PathCursor;
  50787. }());
  50788. BABYLON.PathCursor = PathCursor;
  50789. /**
  50790. * Enum for the animation key frame interpolation type
  50791. */
  50792. var AnimationKeyInterpolation;
  50793. (function (AnimationKeyInterpolation) {
  50794. /**
  50795. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50796. */
  50797. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50798. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50799. /**
  50800. * Class used to store any kind of animation
  50801. */
  50802. var Animation = /** @class */ (function () {
  50803. /**
  50804. * Initializes the animation
  50805. * @param name Name of the animation
  50806. * @param targetProperty Property to animate
  50807. * @param framePerSecond The frames per second of the animation
  50808. * @param dataType The data type of the animation
  50809. * @param loopMode The loop mode of the animation
  50810. * @param enableBlendings Specifies if blending should be enabled
  50811. */
  50812. function Animation(
  50813. /**Name of the animation */
  50814. name,
  50815. /**Property to animate */
  50816. targetProperty,
  50817. /**The frames per second of the animation */
  50818. framePerSecond,
  50819. /**The data type of the animation */
  50820. dataType,
  50821. /**The loop mode of the animation */
  50822. loopMode,
  50823. /**Specifies if blending should be enabled */
  50824. enableBlending) {
  50825. this.name = name;
  50826. this.targetProperty = targetProperty;
  50827. this.framePerSecond = framePerSecond;
  50828. this.dataType = dataType;
  50829. this.loopMode = loopMode;
  50830. this.enableBlending = enableBlending;
  50831. /**
  50832. * @hidden Internal use only
  50833. */
  50834. this._runtimeAnimations = new Array();
  50835. /**
  50836. * The set of event that will be linked to this animation
  50837. */
  50838. this._events = new Array();
  50839. /**
  50840. * Stores the blending speed of the animation
  50841. */
  50842. this.blendingSpeed = 0.01;
  50843. /**
  50844. * Stores the animation ranges for the animation
  50845. */
  50846. this._ranges = {};
  50847. this.targetPropertyPath = targetProperty.split(".");
  50848. this.dataType = dataType;
  50849. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50850. }
  50851. /**
  50852. * @hidden Internal use
  50853. */
  50854. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50855. var dataType = undefined;
  50856. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50857. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50858. }
  50859. else if (from instanceof BABYLON.Quaternion) {
  50860. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50861. }
  50862. else if (from instanceof BABYLON.Vector3) {
  50863. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50864. }
  50865. else if (from instanceof BABYLON.Vector2) {
  50866. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50867. }
  50868. else if (from instanceof BABYLON.Color3) {
  50869. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50870. }
  50871. else if (from instanceof BABYLON.Size) {
  50872. dataType = Animation.ANIMATIONTYPE_SIZE;
  50873. }
  50874. if (dataType == undefined) {
  50875. return null;
  50876. }
  50877. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50878. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50879. animation.setKeys(keys);
  50880. if (easingFunction !== undefined) {
  50881. animation.setEasingFunction(easingFunction);
  50882. }
  50883. return animation;
  50884. };
  50885. /**
  50886. * Sets up an animation
  50887. * @param property The property to animate
  50888. * @param animationType The animation type to apply
  50889. * @param framePerSecond The frames per second of the animation
  50890. * @param easingFunction The easing function used in the animation
  50891. * @returns The created animation
  50892. */
  50893. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50894. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50895. animation.setEasingFunction(easingFunction);
  50896. return animation;
  50897. };
  50898. /**
  50899. * Create and start an animation on a node
  50900. * @param name defines the name of the global animation that will be run on all nodes
  50901. * @param node defines the root node where the animation will take place
  50902. * @param targetProperty defines property to animate
  50903. * @param framePerSecond defines the number of frame per second yo use
  50904. * @param totalFrame defines the number of frames in total
  50905. * @param from defines the initial value
  50906. * @param to defines the final value
  50907. * @param loopMode defines which loop mode you want to use (off by default)
  50908. * @param easingFunction defines the easing function to use (linear by default)
  50909. * @param onAnimationEnd defines the callback to call when animation end
  50910. * @returns the animatable created for this animation
  50911. */
  50912. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50913. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50914. if (!animation) {
  50915. return null;
  50916. }
  50917. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50918. };
  50919. /**
  50920. * Create and start an animation on a node and its descendants
  50921. * @param name defines the name of the global animation that will be run on all nodes
  50922. * @param node defines the root node where the animation will take place
  50923. * @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
  50924. * @param targetProperty defines property to animate
  50925. * @param framePerSecond defines the number of frame per second to use
  50926. * @param totalFrame defines the number of frames in total
  50927. * @param from defines the initial value
  50928. * @param to defines the final value
  50929. * @param loopMode defines which loop mode you want to use (off by default)
  50930. * @param easingFunction defines the easing function to use (linear by default)
  50931. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50932. * @returns the list of animatables created for all nodes
  50933. * @example https://www.babylonjs-playground.com/#MH0VLI
  50934. */
  50935. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50936. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50937. if (!animation) {
  50938. return null;
  50939. }
  50940. var scene = node.getScene();
  50941. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50942. };
  50943. /**
  50944. * Creates a new animation, merges it with the existing animations and starts it
  50945. * @param name Name of the animation
  50946. * @param node Node which contains the scene that begins the animations
  50947. * @param targetProperty Specifies which property to animate
  50948. * @param framePerSecond The frames per second of the animation
  50949. * @param totalFrame The total number of frames
  50950. * @param from The frame at the beginning of the animation
  50951. * @param to The frame at the end of the animation
  50952. * @param loopMode Specifies the loop mode of the animation
  50953. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50954. * @param onAnimationEnd Callback to run once the animation is complete
  50955. * @returns Nullable animation
  50956. */
  50957. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50958. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50959. if (!animation) {
  50960. return null;
  50961. }
  50962. node.animations.push(animation);
  50963. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50964. };
  50965. /**
  50966. * Transition property of an host to the target Value
  50967. * @param property The property to transition
  50968. * @param targetValue The target Value of the property
  50969. * @param host The object where the property to animate belongs
  50970. * @param scene Scene used to run the animation
  50971. * @param frameRate Framerate (in frame/s) to use
  50972. * @param transition The transition type we want to use
  50973. * @param duration The duration of the animation, in milliseconds
  50974. * @param onAnimationEnd Callback trigger at the end of the animation
  50975. * @returns Nullable animation
  50976. */
  50977. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50978. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50979. if (duration <= 0) {
  50980. host[property] = targetValue;
  50981. if (onAnimationEnd) {
  50982. onAnimationEnd();
  50983. }
  50984. return null;
  50985. }
  50986. var endFrame = frameRate * (duration / 1000);
  50987. transition.setKeys([{
  50988. frame: 0,
  50989. value: host[property].clone ? host[property].clone() : host[property]
  50990. },
  50991. {
  50992. frame: endFrame,
  50993. value: targetValue
  50994. }]);
  50995. if (!host.animations) {
  50996. host.animations = [];
  50997. }
  50998. host.animations.push(transition);
  50999. var animation = scene.beginAnimation(host, 0, endFrame, false);
  51000. animation.onAnimationEnd = onAnimationEnd;
  51001. return animation;
  51002. };
  51003. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  51004. /**
  51005. * Return the array of runtime animations currently using this animation
  51006. */
  51007. get: function () {
  51008. return this._runtimeAnimations;
  51009. },
  51010. enumerable: true,
  51011. configurable: true
  51012. });
  51013. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51014. /**
  51015. * Specifies if any of the runtime animations are currently running
  51016. */
  51017. get: function () {
  51018. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51019. var runtimeAnimation = _a[_i];
  51020. if (!runtimeAnimation.isStopped) {
  51021. return true;
  51022. }
  51023. }
  51024. return false;
  51025. },
  51026. enumerable: true,
  51027. configurable: true
  51028. });
  51029. // Methods
  51030. /**
  51031. * Converts the animation to a string
  51032. * @param fullDetails support for multiple levels of logging within scene loading
  51033. * @returns String form of the animation
  51034. */
  51035. Animation.prototype.toString = function (fullDetails) {
  51036. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51037. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51038. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51039. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51040. if (fullDetails) {
  51041. ret += ", Ranges: {";
  51042. var first = true;
  51043. for (var name in this._ranges) {
  51044. if (first) {
  51045. ret += ", ";
  51046. first = false;
  51047. }
  51048. ret += name;
  51049. }
  51050. ret += "}";
  51051. }
  51052. return ret;
  51053. };
  51054. /**
  51055. * Add an event to this animation
  51056. * @param event Event to add
  51057. */
  51058. Animation.prototype.addEvent = function (event) {
  51059. this._events.push(event);
  51060. };
  51061. /**
  51062. * Remove all events found at the given frame
  51063. * @param frame The frame to remove events from
  51064. */
  51065. Animation.prototype.removeEvents = function (frame) {
  51066. for (var index = 0; index < this._events.length; index++) {
  51067. if (this._events[index].frame === frame) {
  51068. this._events.splice(index, 1);
  51069. index--;
  51070. }
  51071. }
  51072. };
  51073. /**
  51074. * Retrieves all the events from the animation
  51075. * @returns Events from the animation
  51076. */
  51077. Animation.prototype.getEvents = function () {
  51078. return this._events;
  51079. };
  51080. /**
  51081. * Creates an animation range
  51082. * @param name Name of the animation range
  51083. * @param from Starting frame of the animation range
  51084. * @param to Ending frame of the animation
  51085. */
  51086. Animation.prototype.createRange = function (name, from, to) {
  51087. // check name not already in use; could happen for bones after serialized
  51088. if (!this._ranges[name]) {
  51089. this._ranges[name] = new AnimationRange(name, from, to);
  51090. }
  51091. };
  51092. /**
  51093. * Deletes an animation range by name
  51094. * @param name Name of the animation range to delete
  51095. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51096. */
  51097. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51098. if (deleteFrames === void 0) { deleteFrames = true; }
  51099. var range = this._ranges[name];
  51100. if (!range) {
  51101. return;
  51102. }
  51103. if (deleteFrames) {
  51104. var from = range.from;
  51105. var to = range.to;
  51106. // this loop MUST go high to low for multiple splices to work
  51107. for (var key = this._keys.length - 1; key >= 0; key--) {
  51108. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51109. this._keys.splice(key, 1);
  51110. }
  51111. }
  51112. }
  51113. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51114. };
  51115. /**
  51116. * Gets the animation range by name, or null if not defined
  51117. * @param name Name of the animation range
  51118. * @returns Nullable animation range
  51119. */
  51120. Animation.prototype.getRange = function (name) {
  51121. return this._ranges[name];
  51122. };
  51123. /**
  51124. * Gets the key frames from the animation
  51125. * @returns The key frames of the animation
  51126. */
  51127. Animation.prototype.getKeys = function () {
  51128. return this._keys;
  51129. };
  51130. /**
  51131. * Gets the highest frame rate of the animation
  51132. * @returns Highest frame rate of the animation
  51133. */
  51134. Animation.prototype.getHighestFrame = function () {
  51135. var ret = 0;
  51136. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51137. if (ret < this._keys[key].frame) {
  51138. ret = this._keys[key].frame;
  51139. }
  51140. }
  51141. return ret;
  51142. };
  51143. /**
  51144. * Gets the easing function of the animation
  51145. * @returns Easing function of the animation
  51146. */
  51147. Animation.prototype.getEasingFunction = function () {
  51148. return this._easingFunction;
  51149. };
  51150. /**
  51151. * Sets the easing function of the animation
  51152. * @param easingFunction A custom mathematical formula for animation
  51153. */
  51154. Animation.prototype.setEasingFunction = function (easingFunction) {
  51155. this._easingFunction = easingFunction;
  51156. };
  51157. /**
  51158. * Interpolates a scalar linearly
  51159. * @param startValue Start value of the animation curve
  51160. * @param endValue End value of the animation curve
  51161. * @param gradient Scalar amount to interpolate
  51162. * @returns Interpolated scalar value
  51163. */
  51164. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51165. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51166. };
  51167. /**
  51168. * Interpolates a scalar cubically
  51169. * @param startValue Start value of the animation curve
  51170. * @param outTangent End tangent of the animation
  51171. * @param endValue End value of the animation curve
  51172. * @param inTangent Start tangent of the animation curve
  51173. * @param gradient Scalar amount to interpolate
  51174. * @returns Interpolated scalar value
  51175. */
  51176. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51177. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51178. };
  51179. /**
  51180. * Interpolates a quaternion using a spherical linear interpolation
  51181. * @param startValue Start value of the animation curve
  51182. * @param endValue End value of the animation curve
  51183. * @param gradient Scalar amount to interpolate
  51184. * @returns Interpolated quaternion value
  51185. */
  51186. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51187. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51188. };
  51189. /**
  51190. * Interpolates a quaternion cubically
  51191. * @param startValue Start value of the animation curve
  51192. * @param outTangent End tangent of the animation curve
  51193. * @param endValue End value of the animation curve
  51194. * @param inTangent Start tangent of the animation curve
  51195. * @param gradient Scalar amount to interpolate
  51196. * @returns Interpolated quaternion value
  51197. */
  51198. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51199. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51200. };
  51201. /**
  51202. * Interpolates a Vector3 linearl
  51203. * @param startValue Start value of the animation curve
  51204. * @param endValue End value of the animation curve
  51205. * @param gradient Scalar amount to interpolate
  51206. * @returns Interpolated scalar value
  51207. */
  51208. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51209. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51210. };
  51211. /**
  51212. * Interpolates a Vector3 cubically
  51213. * @param startValue Start value of the animation curve
  51214. * @param outTangent End tangent of the animation
  51215. * @param endValue End value of the animation curve
  51216. * @param inTangent Start tangent of the animation curve
  51217. * @param gradient Scalar amount to interpolate
  51218. * @returns InterpolatedVector3 value
  51219. */
  51220. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51221. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51222. };
  51223. /**
  51224. * Interpolates a Vector2 linearly
  51225. * @param startValue Start value of the animation curve
  51226. * @param endValue End value of the animation curve
  51227. * @param gradient Scalar amount to interpolate
  51228. * @returns Interpolated Vector2 value
  51229. */
  51230. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51231. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51232. };
  51233. /**
  51234. * Interpolates a Vector2 cubically
  51235. * @param startValue Start value of the animation curve
  51236. * @param outTangent End tangent of the animation
  51237. * @param endValue End value of the animation curve
  51238. * @param inTangent Start tangent of the animation curve
  51239. * @param gradient Scalar amount to interpolate
  51240. * @returns Interpolated Vector2 value
  51241. */
  51242. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51243. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51244. };
  51245. /**
  51246. * Interpolates a size linearly
  51247. * @param startValue Start value of the animation curve
  51248. * @param endValue End value of the animation curve
  51249. * @param gradient Scalar amount to interpolate
  51250. * @returns Interpolated Size value
  51251. */
  51252. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51253. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51254. };
  51255. /**
  51256. * Interpolates a Color3 linearly
  51257. * @param startValue Start value of the animation curve
  51258. * @param endValue End value of the animation curve
  51259. * @param gradient Scalar amount to interpolate
  51260. * @returns Interpolated Color3 value
  51261. */
  51262. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51263. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51264. };
  51265. /**
  51266. * @hidden Internal use only
  51267. */
  51268. Animation.prototype._getKeyValue = function (value) {
  51269. if (typeof value === "function") {
  51270. return value();
  51271. }
  51272. return value;
  51273. };
  51274. /**
  51275. * @hidden Internal use only
  51276. */
  51277. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51278. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51279. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51280. }
  51281. var keys = this.getKeys();
  51282. // Try to get a hash to find the right key
  51283. 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));
  51284. if (keys[startKeyIndex].frame >= currentFrame) {
  51285. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51286. startKeyIndex--;
  51287. }
  51288. }
  51289. for (var key = startKeyIndex; key < keys.length; key++) {
  51290. var endKey = keys[key + 1];
  51291. if (endKey.frame >= currentFrame) {
  51292. var startKey = keys[key];
  51293. var startValue = this._getKeyValue(startKey.value);
  51294. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51295. return startValue;
  51296. }
  51297. var endValue = this._getKeyValue(endKey.value);
  51298. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51299. var frameDelta = endKey.frame - startKey.frame;
  51300. // gradient : percent of currentFrame between the frame inf and the frame sup
  51301. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51302. // check for easingFunction and correction of gradient
  51303. var easingFunction = this.getEasingFunction();
  51304. if (easingFunction != null) {
  51305. gradient = easingFunction.ease(gradient);
  51306. }
  51307. switch (this.dataType) {
  51308. // Float
  51309. case Animation.ANIMATIONTYPE_FLOAT:
  51310. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51311. switch (loopMode) {
  51312. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51313. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51314. return floatValue;
  51315. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51316. return offsetValue * repeatCount + floatValue;
  51317. }
  51318. break;
  51319. // Quaternion
  51320. case Animation.ANIMATIONTYPE_QUATERNION:
  51321. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51322. switch (loopMode) {
  51323. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51324. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51325. return quatValue;
  51326. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51327. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51328. }
  51329. return quatValue;
  51330. // Vector3
  51331. case Animation.ANIMATIONTYPE_VECTOR3:
  51332. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51333. switch (loopMode) {
  51334. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51335. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51336. return vec3Value;
  51337. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51338. return vec3Value.add(offsetValue.scale(repeatCount));
  51339. }
  51340. // Vector2
  51341. case Animation.ANIMATIONTYPE_VECTOR2:
  51342. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51343. switch (loopMode) {
  51344. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51345. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51346. return vec2Value;
  51347. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51348. return vec2Value.add(offsetValue.scale(repeatCount));
  51349. }
  51350. // Size
  51351. case Animation.ANIMATIONTYPE_SIZE:
  51352. switch (loopMode) {
  51353. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51354. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51355. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51356. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51357. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51358. }
  51359. // Color3
  51360. case Animation.ANIMATIONTYPE_COLOR3:
  51361. switch (loopMode) {
  51362. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51363. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51364. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51365. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51366. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51367. }
  51368. // Matrix
  51369. case Animation.ANIMATIONTYPE_MATRIX:
  51370. switch (loopMode) {
  51371. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51372. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51373. if (Animation.AllowMatricesInterpolation) {
  51374. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51375. }
  51376. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51377. return startValue;
  51378. }
  51379. default:
  51380. break;
  51381. }
  51382. break;
  51383. }
  51384. }
  51385. return this._getKeyValue(keys[keys.length - 1].value);
  51386. };
  51387. /**
  51388. * Defines the function to use to interpolate matrices
  51389. * @param startValue defines the start matrix
  51390. * @param endValue defines the end matrix
  51391. * @param gradient defines the gradient between both matrices
  51392. * @param result defines an optional target matrix where to store the interpolation
  51393. * @returns the interpolated matrix
  51394. */
  51395. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51396. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51397. if (result) {
  51398. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51399. return result;
  51400. }
  51401. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51402. }
  51403. if (result) {
  51404. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51405. return result;
  51406. }
  51407. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51408. };
  51409. /**
  51410. * Makes a copy of the animation
  51411. * @returns Cloned animation
  51412. */
  51413. Animation.prototype.clone = function () {
  51414. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51415. clone.enableBlending = this.enableBlending;
  51416. clone.blendingSpeed = this.blendingSpeed;
  51417. if (this._keys) {
  51418. clone.setKeys(this._keys);
  51419. }
  51420. if (this._ranges) {
  51421. clone._ranges = {};
  51422. for (var name in this._ranges) {
  51423. var range = this._ranges[name];
  51424. if (!range) {
  51425. continue;
  51426. }
  51427. clone._ranges[name] = range.clone();
  51428. }
  51429. }
  51430. return clone;
  51431. };
  51432. /**
  51433. * Sets the key frames of the animation
  51434. * @param values The animation key frames to set
  51435. */
  51436. Animation.prototype.setKeys = function (values) {
  51437. this._keys = values.slice(0);
  51438. };
  51439. /**
  51440. * Serializes the animation to an object
  51441. * @returns Serialized object
  51442. */
  51443. Animation.prototype.serialize = function () {
  51444. var serializationObject = {};
  51445. serializationObject.name = this.name;
  51446. serializationObject.property = this.targetProperty;
  51447. serializationObject.framePerSecond = this.framePerSecond;
  51448. serializationObject.dataType = this.dataType;
  51449. serializationObject.loopBehavior = this.loopMode;
  51450. serializationObject.enableBlending = this.enableBlending;
  51451. serializationObject.blendingSpeed = this.blendingSpeed;
  51452. var dataType = this.dataType;
  51453. serializationObject.keys = [];
  51454. var keys = this.getKeys();
  51455. for (var index = 0; index < keys.length; index++) {
  51456. var animationKey = keys[index];
  51457. var key = {};
  51458. key.frame = animationKey.frame;
  51459. switch (dataType) {
  51460. case Animation.ANIMATIONTYPE_FLOAT:
  51461. key.values = [animationKey.value];
  51462. break;
  51463. case Animation.ANIMATIONTYPE_QUATERNION:
  51464. case Animation.ANIMATIONTYPE_MATRIX:
  51465. case Animation.ANIMATIONTYPE_VECTOR3:
  51466. case Animation.ANIMATIONTYPE_COLOR3:
  51467. key.values = animationKey.value.asArray();
  51468. break;
  51469. }
  51470. serializationObject.keys.push(key);
  51471. }
  51472. serializationObject.ranges = [];
  51473. for (var name in this._ranges) {
  51474. var source = this._ranges[name];
  51475. if (!source) {
  51476. continue;
  51477. }
  51478. var range = {};
  51479. range.name = name;
  51480. range.from = source.from;
  51481. range.to = source.to;
  51482. serializationObject.ranges.push(range);
  51483. }
  51484. return serializationObject;
  51485. };
  51486. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51487. /**
  51488. * Get the float animation type
  51489. */
  51490. get: function () {
  51491. return Animation._ANIMATIONTYPE_FLOAT;
  51492. },
  51493. enumerable: true,
  51494. configurable: true
  51495. });
  51496. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51497. /**
  51498. * Get the Vector3 animation type
  51499. */
  51500. get: function () {
  51501. return Animation._ANIMATIONTYPE_VECTOR3;
  51502. },
  51503. enumerable: true,
  51504. configurable: true
  51505. });
  51506. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51507. /**
  51508. * Get the Vector2 animation type
  51509. */
  51510. get: function () {
  51511. return Animation._ANIMATIONTYPE_VECTOR2;
  51512. },
  51513. enumerable: true,
  51514. configurable: true
  51515. });
  51516. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51517. /**
  51518. * Get the Size animation type
  51519. */
  51520. get: function () {
  51521. return Animation._ANIMATIONTYPE_SIZE;
  51522. },
  51523. enumerable: true,
  51524. configurable: true
  51525. });
  51526. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51527. /**
  51528. * Get the Quaternion animation type
  51529. */
  51530. get: function () {
  51531. return Animation._ANIMATIONTYPE_QUATERNION;
  51532. },
  51533. enumerable: true,
  51534. configurable: true
  51535. });
  51536. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51537. /**
  51538. * Get the Matrix animation type
  51539. */
  51540. get: function () {
  51541. return Animation._ANIMATIONTYPE_MATRIX;
  51542. },
  51543. enumerable: true,
  51544. configurable: true
  51545. });
  51546. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51547. /**
  51548. * Get the Color3 animation type
  51549. */
  51550. get: function () {
  51551. return Animation._ANIMATIONTYPE_COLOR3;
  51552. },
  51553. enumerable: true,
  51554. configurable: true
  51555. });
  51556. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51557. /**
  51558. * Get the Relative Loop Mode
  51559. */
  51560. get: function () {
  51561. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51562. },
  51563. enumerable: true,
  51564. configurable: true
  51565. });
  51566. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51567. /**
  51568. * Get the Cycle Loop Mode
  51569. */
  51570. get: function () {
  51571. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51572. },
  51573. enumerable: true,
  51574. configurable: true
  51575. });
  51576. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51577. /**
  51578. * Get the Constant Loop Mode
  51579. */
  51580. get: function () {
  51581. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51582. },
  51583. enumerable: true,
  51584. configurable: true
  51585. });
  51586. /** @hidden */
  51587. Animation._UniversalLerp = function (left, right, amount) {
  51588. var constructor = left.constructor;
  51589. if (constructor.Lerp) { // Lerp supported
  51590. return constructor.Lerp(left, right, amount);
  51591. }
  51592. else if (constructor.Slerp) { // Slerp supported
  51593. return constructor.Slerp(left, right, amount);
  51594. }
  51595. else if (left.toFixed) { // Number
  51596. return left * (1.0 - amount) + amount * right;
  51597. }
  51598. else { // Blending not supported
  51599. return right;
  51600. }
  51601. };
  51602. /**
  51603. * Parses an animation object and creates an animation
  51604. * @param parsedAnimation Parsed animation object
  51605. * @returns Animation object
  51606. */
  51607. Animation.Parse = function (parsedAnimation) {
  51608. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51609. var dataType = parsedAnimation.dataType;
  51610. var keys = [];
  51611. var data;
  51612. var index;
  51613. if (parsedAnimation.enableBlending) {
  51614. animation.enableBlending = parsedAnimation.enableBlending;
  51615. }
  51616. if (parsedAnimation.blendingSpeed) {
  51617. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51618. }
  51619. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51620. var key = parsedAnimation.keys[index];
  51621. var inTangent;
  51622. var outTangent;
  51623. switch (dataType) {
  51624. case Animation.ANIMATIONTYPE_FLOAT:
  51625. data = key.values[0];
  51626. if (key.values.length >= 1) {
  51627. inTangent = key.values[1];
  51628. }
  51629. if (key.values.length >= 2) {
  51630. outTangent = key.values[2];
  51631. }
  51632. break;
  51633. case Animation.ANIMATIONTYPE_QUATERNION:
  51634. data = BABYLON.Quaternion.FromArray(key.values);
  51635. if (key.values.length >= 8) {
  51636. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51637. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51638. inTangent = _inTangent;
  51639. }
  51640. }
  51641. if (key.values.length >= 12) {
  51642. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51643. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51644. outTangent = _outTangent;
  51645. }
  51646. }
  51647. break;
  51648. case Animation.ANIMATIONTYPE_MATRIX:
  51649. data = BABYLON.Matrix.FromArray(key.values);
  51650. break;
  51651. case Animation.ANIMATIONTYPE_COLOR3:
  51652. data = BABYLON.Color3.FromArray(key.values);
  51653. break;
  51654. case Animation.ANIMATIONTYPE_VECTOR3:
  51655. default:
  51656. data = BABYLON.Vector3.FromArray(key.values);
  51657. break;
  51658. }
  51659. var keyData = {};
  51660. keyData.frame = key.frame;
  51661. keyData.value = data;
  51662. if (inTangent != undefined) {
  51663. keyData.inTangent = inTangent;
  51664. }
  51665. if (outTangent != undefined) {
  51666. keyData.outTangent = outTangent;
  51667. }
  51668. keys.push(keyData);
  51669. }
  51670. animation.setKeys(keys);
  51671. if (parsedAnimation.ranges) {
  51672. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51673. data = parsedAnimation.ranges[index];
  51674. animation.createRange(data.name, data.from, data.to);
  51675. }
  51676. }
  51677. return animation;
  51678. };
  51679. /**
  51680. * Appends the serialized animations from the source animations
  51681. * @param source Source containing the animations
  51682. * @param destination Target to store the animations
  51683. */
  51684. Animation.AppendSerializedAnimations = function (source, destination) {
  51685. if (source.animations) {
  51686. destination.animations = [];
  51687. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51688. var animation = source.animations[animationIndex];
  51689. destination.animations.push(animation.serialize());
  51690. }
  51691. }
  51692. };
  51693. /**
  51694. * Use matrix interpolation instead of using direct key value when animating matrices
  51695. */
  51696. Animation.AllowMatricesInterpolation = false;
  51697. /**
  51698. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51699. */
  51700. Animation.AllowMatrixDecomposeForInterpolation = true;
  51701. // Statics
  51702. /**
  51703. * Float animation type
  51704. */
  51705. Animation._ANIMATIONTYPE_FLOAT = 0;
  51706. /**
  51707. * Vector3 animation type
  51708. */
  51709. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51710. /**
  51711. * Quaternion animation type
  51712. */
  51713. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51714. /**
  51715. * Matrix animation type
  51716. */
  51717. Animation._ANIMATIONTYPE_MATRIX = 3;
  51718. /**
  51719. * Color3 animation type
  51720. */
  51721. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51722. /**
  51723. * Vector2 animation type
  51724. */
  51725. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51726. /**
  51727. * Size animation type
  51728. */
  51729. Animation._ANIMATIONTYPE_SIZE = 6;
  51730. /**
  51731. * Relative Loop Mode
  51732. */
  51733. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51734. /**
  51735. * Cycle Loop Mode
  51736. */
  51737. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51738. /**
  51739. * Constant Loop Mode
  51740. */
  51741. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51742. return Animation;
  51743. }());
  51744. BABYLON.Animation = Animation;
  51745. })(BABYLON || (BABYLON = {}));
  51746. //# sourceMappingURL=babylon.animation.js.map
  51747. var BABYLON;
  51748. (function (BABYLON) {
  51749. /**
  51750. * This class defines the direct association between an animation and a target
  51751. */
  51752. var TargetedAnimation = /** @class */ (function () {
  51753. function TargetedAnimation() {
  51754. }
  51755. return TargetedAnimation;
  51756. }());
  51757. BABYLON.TargetedAnimation = TargetedAnimation;
  51758. /**
  51759. * Use this class to create coordinated animations on multiple targets
  51760. */
  51761. var AnimationGroup = /** @class */ (function () {
  51762. /**
  51763. * Instantiates a new Animation Group.
  51764. * This helps managing several animations at once.
  51765. * @see http://doc.babylonjs.com/how_to/group
  51766. * @param name Defines the name of the group
  51767. * @param scene Defines the scene the group belongs to
  51768. */
  51769. function AnimationGroup(
  51770. /** The name of the animation group */
  51771. name, scene) {
  51772. if (scene === void 0) { scene = null; }
  51773. this.name = name;
  51774. this._targetedAnimations = new Array();
  51775. this._animatables = new Array();
  51776. this._from = Number.MAX_VALUE;
  51777. this._to = -Number.MAX_VALUE;
  51778. this._speedRatio = 1;
  51779. /**
  51780. * This observable will notify when one animation have ended.
  51781. */
  51782. this.onAnimationEndObservable = new BABYLON.Observable();
  51783. /**
  51784. * This observable will notify when all animations have ended.
  51785. */
  51786. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51787. /**
  51788. * This observable will notify when all animations have paused.
  51789. */
  51790. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  51791. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51792. this._scene.animationGroups.push(this);
  51793. }
  51794. Object.defineProperty(AnimationGroup.prototype, "from", {
  51795. /**
  51796. * Gets the first frame
  51797. */
  51798. get: function () {
  51799. return this._from;
  51800. },
  51801. enumerable: true,
  51802. configurable: true
  51803. });
  51804. Object.defineProperty(AnimationGroup.prototype, "to", {
  51805. /**
  51806. * Gets the last frame
  51807. */
  51808. get: function () {
  51809. return this._to;
  51810. },
  51811. enumerable: true,
  51812. configurable: true
  51813. });
  51814. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51815. /**
  51816. * Define if the animations are started
  51817. */
  51818. get: function () {
  51819. return this._isStarted;
  51820. },
  51821. enumerable: true,
  51822. configurable: true
  51823. });
  51824. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51825. /**
  51826. * Gets or sets the speed ratio to use for all animations
  51827. */
  51828. get: function () {
  51829. return this._speedRatio;
  51830. },
  51831. /**
  51832. * Gets or sets the speed ratio to use for all animations
  51833. */
  51834. set: function (value) {
  51835. if (this._speedRatio === value) {
  51836. return;
  51837. }
  51838. this._speedRatio = value;
  51839. for (var index = 0; index < this._animatables.length; index++) {
  51840. var animatable = this._animatables[index];
  51841. animatable.speedRatio = this._speedRatio;
  51842. }
  51843. },
  51844. enumerable: true,
  51845. configurable: true
  51846. });
  51847. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51848. /**
  51849. * Gets the targeted animations for this animation group
  51850. */
  51851. get: function () {
  51852. return this._targetedAnimations;
  51853. },
  51854. enumerable: true,
  51855. configurable: true
  51856. });
  51857. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51858. /**
  51859. * returning the list of animatables controlled by this animation group.
  51860. */
  51861. get: function () {
  51862. return this._animatables;
  51863. },
  51864. enumerable: true,
  51865. configurable: true
  51866. });
  51867. /**
  51868. * Add an animation (with its target) in the group
  51869. * @param animation defines the animation we want to add
  51870. * @param target defines the target of the animation
  51871. * @returns the {BABYLON.TargetedAnimation} object
  51872. */
  51873. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51874. var targetedAnimation = {
  51875. animation: animation,
  51876. target: target
  51877. };
  51878. var keys = animation.getKeys();
  51879. if (this._from > keys[0].frame) {
  51880. this._from = keys[0].frame;
  51881. }
  51882. if (this._to < keys[keys.length - 1].frame) {
  51883. this._to = keys[keys.length - 1].frame;
  51884. }
  51885. this._targetedAnimations.push(targetedAnimation);
  51886. return targetedAnimation;
  51887. };
  51888. /**
  51889. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51890. * It can add constant keys at begin or end
  51891. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51892. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51893. * @returns the animation group
  51894. */
  51895. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51896. if (beginFrame === void 0) { beginFrame = null; }
  51897. if (endFrame === void 0) { endFrame = null; }
  51898. if (beginFrame == null)
  51899. beginFrame = this._from;
  51900. if (endFrame == null)
  51901. endFrame = this._to;
  51902. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51903. var targetedAnimation = this._targetedAnimations[index];
  51904. var keys = targetedAnimation.animation.getKeys();
  51905. var startKey = keys[0];
  51906. var endKey = keys[keys.length - 1];
  51907. if (startKey.frame > beginFrame) {
  51908. var newKey = {
  51909. frame: beginFrame,
  51910. value: startKey.value,
  51911. inTangent: startKey.inTangent,
  51912. outTangent: startKey.outTangent,
  51913. interpolation: startKey.interpolation
  51914. };
  51915. keys.splice(0, 0, newKey);
  51916. }
  51917. if (endKey.frame < endFrame) {
  51918. var newKey = {
  51919. frame: endFrame,
  51920. value: endKey.value,
  51921. inTangent: endKey.outTangent,
  51922. outTangent: endKey.outTangent,
  51923. interpolation: endKey.interpolation
  51924. };
  51925. keys.push(newKey);
  51926. }
  51927. }
  51928. this._from = beginFrame;
  51929. this._to = endFrame;
  51930. return this;
  51931. };
  51932. /**
  51933. * Start all animations on given targets
  51934. * @param loop defines if animations must loop
  51935. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51936. * @param from defines the from key (optional)
  51937. * @param to defines the to key (optional)
  51938. * @returns the current animation group
  51939. */
  51940. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51941. var _this = this;
  51942. if (loop === void 0) { loop = false; }
  51943. if (speedRatio === void 0) { speedRatio = 1; }
  51944. if (this._isStarted || this._targetedAnimations.length === 0) {
  51945. return this;
  51946. }
  51947. var _loop_1 = function (targetedAnimation) {
  51948. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51949. animatable.onAnimationEnd = function () {
  51950. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51951. _this._checkAnimationGroupEnded(animatable);
  51952. };
  51953. this_1._animatables.push(animatable);
  51954. };
  51955. var this_1 = this;
  51956. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51957. var targetedAnimation = _a[_i];
  51958. _loop_1(targetedAnimation);
  51959. }
  51960. this._speedRatio = speedRatio;
  51961. this._isStarted = true;
  51962. return this;
  51963. };
  51964. /**
  51965. * Pause all animations
  51966. * @returns the animation group
  51967. */
  51968. AnimationGroup.prototype.pause = function () {
  51969. if (!this._isStarted) {
  51970. return this;
  51971. }
  51972. for (var index = 0; index < this._animatables.length; index++) {
  51973. var animatable = this._animatables[index];
  51974. animatable.pause();
  51975. }
  51976. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51977. return this;
  51978. };
  51979. /**
  51980. * Play all animations to initial state
  51981. * This function will start() the animations if they were not started or will restart() them if they were paused
  51982. * @param loop defines if animations must loop
  51983. * @returns the animation group
  51984. */
  51985. AnimationGroup.prototype.play = function (loop) {
  51986. // only if all animatables are ready and exist
  51987. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51988. if (loop !== undefined) {
  51989. for (var index = 0; index < this._animatables.length; index++) {
  51990. var animatable = this._animatables[index];
  51991. animatable.loopAnimation = loop;
  51992. }
  51993. }
  51994. this.restart();
  51995. }
  51996. else {
  51997. this.stop();
  51998. this.start(loop, this._speedRatio);
  51999. }
  52000. return this;
  52001. };
  52002. /**
  52003. * Reset all animations to initial state
  52004. * @returns the animation group
  52005. */
  52006. AnimationGroup.prototype.reset = function () {
  52007. if (!this._isStarted) {
  52008. return this;
  52009. }
  52010. for (var index = 0; index < this._animatables.length; index++) {
  52011. var animatable = this._animatables[index];
  52012. animatable.reset();
  52013. }
  52014. return this;
  52015. };
  52016. /**
  52017. * Restart animations from key 0
  52018. * @returns the animation group
  52019. */
  52020. AnimationGroup.prototype.restart = function () {
  52021. if (!this._isStarted) {
  52022. return this;
  52023. }
  52024. for (var index = 0; index < this._animatables.length; index++) {
  52025. var animatable = this._animatables[index];
  52026. animatable.restart();
  52027. }
  52028. return this;
  52029. };
  52030. /**
  52031. * Stop all animations
  52032. * @returns the animation group
  52033. */
  52034. AnimationGroup.prototype.stop = function () {
  52035. if (!this._isStarted) {
  52036. return this;
  52037. }
  52038. var list = this._animatables.slice();
  52039. for (var index = 0; index < list.length; index++) {
  52040. list[index].stop();
  52041. }
  52042. this._isStarted = false;
  52043. return this;
  52044. };
  52045. /**
  52046. * Set animation weight for all animatables
  52047. * @param weight defines the weight to use
  52048. * @return the animationGroup
  52049. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52050. */
  52051. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52052. for (var index = 0; index < this._animatables.length; index++) {
  52053. var animatable = this._animatables[index];
  52054. animatable.weight = weight;
  52055. }
  52056. return this;
  52057. };
  52058. /**
  52059. * Synchronize and normalize all animatables with a source animatable
  52060. * @param root defines the root animatable to synchronize with
  52061. * @return the animationGroup
  52062. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52063. */
  52064. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52065. for (var index = 0; index < this._animatables.length; index++) {
  52066. var animatable = this._animatables[index];
  52067. animatable.syncWith(root);
  52068. }
  52069. return this;
  52070. };
  52071. /**
  52072. * Goes to a specific frame in this animation group
  52073. * @param frame the frame number to go to
  52074. * @return the animationGroup
  52075. */
  52076. AnimationGroup.prototype.goToFrame = function (frame) {
  52077. if (!this._isStarted) {
  52078. return this;
  52079. }
  52080. for (var index = 0; index < this._animatables.length; index++) {
  52081. var animatable = this._animatables[index];
  52082. animatable.goToFrame(frame);
  52083. }
  52084. return this;
  52085. };
  52086. /**
  52087. * Dispose all associated resources
  52088. */
  52089. AnimationGroup.prototype.dispose = function () {
  52090. this._targetedAnimations = [];
  52091. this._animatables = [];
  52092. var index = this._scene.animationGroups.indexOf(this);
  52093. if (index > -1) {
  52094. this._scene.animationGroups.splice(index, 1);
  52095. }
  52096. };
  52097. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52098. // animatable should be taken out of the array
  52099. var idx = this._animatables.indexOf(animatable);
  52100. if (idx > -1) {
  52101. this._animatables.splice(idx, 1);
  52102. }
  52103. // all animatables were removed? animation group ended!
  52104. if (this._animatables.length === 0) {
  52105. this._isStarted = false;
  52106. this.onAnimationGroupEndObservable.notifyObservers(this);
  52107. }
  52108. };
  52109. // Statics
  52110. /**
  52111. * Returns a new AnimationGroup object parsed from the source provided.
  52112. * @param parsedAnimationGroup defines the source
  52113. * @param scene defines the scene that will receive the animationGroup
  52114. * @returns a new AnimationGroup
  52115. */
  52116. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  52117. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  52118. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  52119. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  52120. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  52121. var id = targetedAnimation.targetId;
  52122. var targetNode = scene.getNodeByID(id);
  52123. if (targetNode != null)
  52124. animationGroup.addTargetedAnimation(animation, targetNode);
  52125. }
  52126. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  52127. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  52128. return animationGroup;
  52129. };
  52130. /**
  52131. * Returns the string "AnimationGroup"
  52132. * @returns "AnimationGroup"
  52133. */
  52134. AnimationGroup.prototype.getClassName = function () {
  52135. return "AnimationGroup";
  52136. };
  52137. /**
  52138. * Creates a detailled string about the object
  52139. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  52140. * @returns a string representing the object
  52141. */
  52142. AnimationGroup.prototype.toString = function (fullDetails) {
  52143. var ret = "Name: " + this.name;
  52144. ret += ", type: " + this.getClassName();
  52145. if (fullDetails) {
  52146. ret += ", from: " + this._from;
  52147. ret += ", to: " + this._to;
  52148. ret += ", isStarted: " + this._isStarted;
  52149. ret += ", speedRatio: " + this._speedRatio;
  52150. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  52151. ret += ", animatables length: " + this._animatables;
  52152. }
  52153. return ret;
  52154. };
  52155. return AnimationGroup;
  52156. }());
  52157. BABYLON.AnimationGroup = AnimationGroup;
  52158. })(BABYLON || (BABYLON = {}));
  52159. //# sourceMappingURL=babylon.animationGroup.js.map
  52160. var BABYLON;
  52161. (function (BABYLON) {
  52162. // Static values to help the garbage collector
  52163. // Quaternion
  52164. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  52165. // Vector3
  52166. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  52167. // Vector2
  52168. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  52169. // Size
  52170. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  52171. // Color3
  52172. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  52173. /**
  52174. * Defines a runtime animation
  52175. */
  52176. var RuntimeAnimation = /** @class */ (function () {
  52177. /**
  52178. * Create a new RuntimeAnimation object
  52179. * @param target defines the target of the animation
  52180. * @param animation defines the source animation object
  52181. * @param scene defines the hosting scene
  52182. * @param host defines the initiating Animatable
  52183. */
  52184. function RuntimeAnimation(target, animation, scene, host) {
  52185. var _this = this;
  52186. this._events = new Array();
  52187. /**
  52188. * The current frame of the runtime animation
  52189. */
  52190. this._currentFrame = 0;
  52191. /**
  52192. * The original value of the runtime animation
  52193. */
  52194. this._originalValue = new Array();
  52195. /**
  52196. * The offsets cache of the runtime animation
  52197. */
  52198. this._offsetsCache = {};
  52199. /**
  52200. * The high limits cache of the runtime animation
  52201. */
  52202. this._highLimitsCache = {};
  52203. /**
  52204. * Specifies if the runtime animation has been stopped
  52205. */
  52206. this._stopped = false;
  52207. /**
  52208. * The blending factor of the runtime animation
  52209. */
  52210. this._blendingFactor = 0;
  52211. /**
  52212. * The target path of the runtime animation
  52213. */
  52214. this._targetPath = "";
  52215. /**
  52216. * The weight of the runtime animation
  52217. */
  52218. this._weight = 1.0;
  52219. /**
  52220. * The ratio offset of the runtime animation
  52221. */
  52222. this._ratioOffset = 0;
  52223. /**
  52224. * The previous delay of the runtime animation
  52225. */
  52226. this._previousDelay = 0;
  52227. /**
  52228. * The previous ratio of the runtime animation
  52229. */
  52230. this._previousRatio = 0;
  52231. this._animation = animation;
  52232. this._target = target;
  52233. this._scene = scene;
  52234. this._host = host;
  52235. animation._runtimeAnimations.push(this);
  52236. // Cloning events locally
  52237. var events = animation.getEvents();
  52238. if (events && events.length > 0) {
  52239. events.forEach(function (e) {
  52240. _this._events.push(e._clone());
  52241. });
  52242. }
  52243. }
  52244. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52245. /**
  52246. * Gets the current frame of the runtime animation
  52247. */
  52248. get: function () {
  52249. return this._currentFrame;
  52250. },
  52251. enumerable: true,
  52252. configurable: true
  52253. });
  52254. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52255. /**
  52256. * Gets the weight of the runtime animation
  52257. */
  52258. get: function () {
  52259. return this._weight;
  52260. },
  52261. enumerable: true,
  52262. configurable: true
  52263. });
  52264. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52265. /**
  52266. * Gets the current value of the runtime animation
  52267. */
  52268. get: function () {
  52269. return this._currentValue;
  52270. },
  52271. enumerable: true,
  52272. configurable: true
  52273. });
  52274. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52275. /**
  52276. * Gets the target path of the runtime animation
  52277. */
  52278. get: function () {
  52279. return this._targetPath;
  52280. },
  52281. enumerable: true,
  52282. configurable: true
  52283. });
  52284. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52285. /**
  52286. * Gets the actual target of the runtime animation
  52287. */
  52288. get: function () {
  52289. return this._activeTarget;
  52290. },
  52291. enumerable: true,
  52292. configurable: true
  52293. });
  52294. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52295. /**
  52296. * Gets the animation from the runtime animation
  52297. */
  52298. get: function () {
  52299. return this._animation;
  52300. },
  52301. enumerable: true,
  52302. configurable: true
  52303. });
  52304. /**
  52305. * Resets the runtime animation to the beginning
  52306. * @param restoreOriginal defines whether to restore the target property to the original value
  52307. */
  52308. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52309. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52310. if (restoreOriginal) {
  52311. if (this._target instanceof Array) {
  52312. var index = 0;
  52313. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52314. var target = _a[_i];
  52315. if (this._originalValue[index] !== undefined) {
  52316. this._setValue(target, this._originalValue[index], -1);
  52317. }
  52318. index++;
  52319. }
  52320. }
  52321. else {
  52322. if (this._originalValue[0] !== undefined) {
  52323. this._setValue(this._target, this._originalValue[0], -1);
  52324. }
  52325. }
  52326. }
  52327. this._offsetsCache = {};
  52328. this._highLimitsCache = {};
  52329. this._currentFrame = 0;
  52330. this._blendingFactor = 0;
  52331. this._originalValue = new Array();
  52332. // Events
  52333. for (var index = 0; index < this._events.length; index++) {
  52334. this._events[index].isDone = false;
  52335. }
  52336. };
  52337. /**
  52338. * Specifies if the runtime animation is stopped
  52339. * @returns Boolean specifying if the runtime animation is stopped
  52340. */
  52341. RuntimeAnimation.prototype.isStopped = function () {
  52342. return this._stopped;
  52343. };
  52344. /**
  52345. * Disposes of the runtime animation
  52346. */
  52347. RuntimeAnimation.prototype.dispose = function () {
  52348. var index = this._animation.runtimeAnimations.indexOf(this);
  52349. if (index > -1) {
  52350. this._animation.runtimeAnimations.splice(index, 1);
  52351. }
  52352. };
  52353. /**
  52354. * Interpolates the animation from the current frame
  52355. * @param currentFrame The frame to interpolate the animation to
  52356. * @param repeatCount The number of times that the animation should loop
  52357. * @param loopMode The type of looping mode to use
  52358. * @param offsetValue Animation offset value
  52359. * @param highLimitValue The high limit value
  52360. * @returns The interpolated value
  52361. */
  52362. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52363. this._currentFrame = currentFrame;
  52364. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52365. this._workValue = BABYLON.Matrix.Zero();
  52366. }
  52367. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52368. };
  52369. /**
  52370. * Apply the interpolated value to the target
  52371. * @param currentValue defines the value computed by the animation
  52372. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52373. */
  52374. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52375. if (weight === void 0) { weight = 1.0; }
  52376. if (this._target instanceof Array) {
  52377. var index = 0;
  52378. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52379. var target = _a[_i];
  52380. this._setValue(target, currentValue, weight, index);
  52381. index++;
  52382. }
  52383. }
  52384. else {
  52385. this._setValue(this._target, currentValue, weight);
  52386. }
  52387. };
  52388. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52389. if (targetIndex === void 0) { targetIndex = 0; }
  52390. // Set value
  52391. var path;
  52392. var destination;
  52393. var targetPropertyPath = this._animation.targetPropertyPath;
  52394. if (targetPropertyPath.length > 1) {
  52395. var property = target[targetPropertyPath[0]];
  52396. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52397. property = property[targetPropertyPath[index]];
  52398. }
  52399. path = targetPropertyPath[targetPropertyPath.length - 1];
  52400. destination = property;
  52401. }
  52402. else {
  52403. path = targetPropertyPath[0];
  52404. destination = target;
  52405. }
  52406. this._targetPath = path;
  52407. this._activeTarget = destination;
  52408. this._weight = weight;
  52409. if (this._originalValue[targetIndex] === undefined) {
  52410. var originalValue = void 0;
  52411. if (destination.getRestPose && path === "_matrix") { // For bones
  52412. originalValue = destination.getRestPose();
  52413. }
  52414. else {
  52415. originalValue = destination[path];
  52416. }
  52417. if (originalValue && originalValue.clone) {
  52418. this._originalValue[targetIndex] = originalValue.clone();
  52419. }
  52420. else {
  52421. this._originalValue[targetIndex] = originalValue;
  52422. }
  52423. }
  52424. // Blending
  52425. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52426. if (enableBlending && this._blendingFactor <= 1.0) {
  52427. if (!this._originalBlendValue) {
  52428. var originalValue = destination[path];
  52429. if (originalValue.clone) {
  52430. this._originalBlendValue = originalValue.clone();
  52431. }
  52432. else {
  52433. this._originalBlendValue = originalValue;
  52434. }
  52435. }
  52436. if (this._originalBlendValue.m) { // Matrix
  52437. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52438. if (this._currentValue) {
  52439. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52440. }
  52441. else {
  52442. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52443. }
  52444. }
  52445. else {
  52446. if (this._currentValue) {
  52447. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52448. }
  52449. else {
  52450. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52451. }
  52452. }
  52453. }
  52454. else {
  52455. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52456. }
  52457. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52458. this._blendingFactor += blendingSpeed;
  52459. }
  52460. else {
  52461. this._currentValue = currentValue;
  52462. }
  52463. if (weight !== -1.0) {
  52464. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52465. }
  52466. else {
  52467. destination[path] = this._currentValue;
  52468. }
  52469. if (target.markAsDirty) {
  52470. target.markAsDirty(this._animation.targetProperty);
  52471. }
  52472. };
  52473. /**
  52474. * Gets the loop pmode of the runtime animation
  52475. * @returns Loop Mode
  52476. */
  52477. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52478. if (this._target && this._target.animationPropertiesOverride) {
  52479. return this._target.animationPropertiesOverride.loopMode;
  52480. }
  52481. return this._animation.loopMode;
  52482. };
  52483. /**
  52484. * Move the current animation to a given frame
  52485. * @param frame defines the frame to move to
  52486. */
  52487. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52488. var keys = this._animation.getKeys();
  52489. if (frame < keys[0].frame) {
  52490. frame = keys[0].frame;
  52491. }
  52492. else if (frame > keys[keys.length - 1].frame) {
  52493. frame = keys[keys.length - 1].frame;
  52494. }
  52495. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52496. this.setValue(currentValue, -1);
  52497. };
  52498. /**
  52499. * @hidden Internal use only
  52500. */
  52501. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52502. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52503. this._ratioOffset = this._previousRatio - newRatio;
  52504. };
  52505. /**
  52506. * Execute the current animation
  52507. * @param delay defines the delay to add to the current frame
  52508. * @param from defines the lower bound of the animation range
  52509. * @param to defines the upper bound of the animation range
  52510. * @param loop defines if the current animation must loop
  52511. * @param speedRatio defines the current speed ratio
  52512. * @param weight defines the weight of the animation (default is -1 so no weight)
  52513. * @returns a boolean indicating if the animation is running
  52514. */
  52515. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52516. if (weight === void 0) { weight = -1.0; }
  52517. var targetPropertyPath = this._animation.targetPropertyPath;
  52518. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52519. this._stopped = true;
  52520. return false;
  52521. }
  52522. var returnValue = true;
  52523. var keys = this._animation.getKeys();
  52524. // Adding a start key at frame 0 if missing
  52525. if (keys[0].frame !== 0) {
  52526. var newKey = { frame: 0, value: keys[0].value };
  52527. keys.splice(0, 0, newKey);
  52528. }
  52529. // Adding a duplicate key when there is only one key at frame zero
  52530. else if (keys.length === 1) {
  52531. var newKey = { frame: 0.001, value: keys[0].value };
  52532. keys.push(newKey);
  52533. }
  52534. // Check limits
  52535. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52536. from = keys[0].frame;
  52537. }
  52538. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52539. to = keys[keys.length - 1].frame;
  52540. }
  52541. //to and from cannot be the same key
  52542. if (from === to) {
  52543. if (from > keys[0].frame) {
  52544. from--;
  52545. }
  52546. else if (to < keys[keys.length - 1].frame) {
  52547. to++;
  52548. }
  52549. }
  52550. // Compute ratio
  52551. var range = to - from;
  52552. var offsetValue;
  52553. // ratio represents the frame delta between from and to
  52554. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52555. var highLimitValue = 0;
  52556. this._previousDelay = delay;
  52557. this._previousRatio = ratio;
  52558. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52559. returnValue = false;
  52560. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52561. }
  52562. else {
  52563. // Get max value if required
  52564. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52565. var keyOffset = to.toString() + from.toString();
  52566. if (!this._offsetsCache[keyOffset]) {
  52567. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52568. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52569. switch (this._animation.dataType) {
  52570. // Float
  52571. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52572. this._offsetsCache[keyOffset] = toValue - fromValue;
  52573. break;
  52574. // Quaternion
  52575. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52576. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52577. break;
  52578. // Vector3
  52579. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52580. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52581. // Vector2
  52582. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52583. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52584. // Size
  52585. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52586. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52587. // Color3
  52588. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52589. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52590. default:
  52591. break;
  52592. }
  52593. this._highLimitsCache[keyOffset] = toValue;
  52594. }
  52595. highLimitValue = this._highLimitsCache[keyOffset];
  52596. offsetValue = this._offsetsCache[keyOffset];
  52597. }
  52598. }
  52599. if (offsetValue === undefined) {
  52600. switch (this._animation.dataType) {
  52601. // Float
  52602. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52603. offsetValue = 0;
  52604. break;
  52605. // Quaternion
  52606. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52607. offsetValue = _staticOffsetValueQuaternion;
  52608. break;
  52609. // Vector3
  52610. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52611. offsetValue = _staticOffsetValueVector3;
  52612. break;
  52613. // Vector2
  52614. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52615. offsetValue = _staticOffsetValueVector2;
  52616. break;
  52617. // Size
  52618. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52619. offsetValue = _staticOffsetValueSize;
  52620. break;
  52621. // Color3
  52622. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52623. offsetValue = _staticOffsetValueColor3;
  52624. }
  52625. }
  52626. // Compute value
  52627. var repeatCount = (ratio / range) >> 0;
  52628. var currentFrame = returnValue ? from + ratio % range : to;
  52629. // Need to normalize?
  52630. if (this._host && this._host.syncRoot) {
  52631. var syncRoot = this._host.syncRoot;
  52632. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52633. currentFrame = from + (to - from) * hostNormalizedFrame;
  52634. }
  52635. // Reset events if looping
  52636. var events = this._events;
  52637. if (range > 0 && this.currentFrame > currentFrame ||
  52638. range < 0 && this.currentFrame < currentFrame) {
  52639. // Need to reset animation events
  52640. for (var index = 0; index < events.length; index++) {
  52641. if (!events[index].onlyOnce) {
  52642. // reset event, the animation is looping
  52643. events[index].isDone = false;
  52644. }
  52645. }
  52646. }
  52647. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52648. // Set value
  52649. this.setValue(currentValue, weight);
  52650. // Check events
  52651. for (var index = 0; index < events.length; index++) {
  52652. // Make sure current frame has passed event frame and that event frame is within the current range
  52653. // Also, handle both forward and reverse animations
  52654. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52655. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52656. var event = events[index];
  52657. if (!event.isDone) {
  52658. // If event should be done only once, remove it.
  52659. if (event.onlyOnce) {
  52660. events.splice(index, 1);
  52661. index--;
  52662. }
  52663. event.isDone = true;
  52664. event.action(currentFrame);
  52665. } // Don't do anything if the event has already be done.
  52666. }
  52667. }
  52668. if (!returnValue) {
  52669. this._stopped = true;
  52670. }
  52671. return returnValue;
  52672. };
  52673. return RuntimeAnimation;
  52674. }());
  52675. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52676. })(BABYLON || (BABYLON = {}));
  52677. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52678. var BABYLON;
  52679. (function (BABYLON) {
  52680. /**
  52681. * Class used to store an actual running animation
  52682. */
  52683. var Animatable = /** @class */ (function () {
  52684. /**
  52685. * Creates a new Animatable
  52686. * @param scene defines the hosting scene
  52687. * @param target defines the target object
  52688. * @param fromFrame defines the starting frame number (default is 0)
  52689. * @param toFrame defines the ending frame number (default is 100)
  52690. * @param loopAnimation defines if the animation must loop (default is false)
  52691. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  52692. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  52693. * @param animations defines a group of animation to add to the new Animatable
  52694. */
  52695. function Animatable(scene,
  52696. /** defines the target object */
  52697. target,
  52698. /** defines the starting frame number (default is 0) */
  52699. fromFrame,
  52700. /** defines the ending frame number (default is 100) */
  52701. toFrame,
  52702. /** defines if the animation must loop (default is false) */
  52703. loopAnimation, speedRatio,
  52704. /** defines a callback to call when animation ends if it is not looping */
  52705. onAnimationEnd, animations) {
  52706. if (fromFrame === void 0) { fromFrame = 0; }
  52707. if (toFrame === void 0) { toFrame = 100; }
  52708. if (loopAnimation === void 0) { loopAnimation = false; }
  52709. if (speedRatio === void 0) { speedRatio = 1.0; }
  52710. this.target = target;
  52711. this.fromFrame = fromFrame;
  52712. this.toFrame = toFrame;
  52713. this.loopAnimation = loopAnimation;
  52714. this.onAnimationEnd = onAnimationEnd;
  52715. this._localDelayOffset = null;
  52716. this._pausedDelay = null;
  52717. this._runtimeAnimations = new Array();
  52718. this._paused = false;
  52719. this._speedRatio = 1;
  52720. this._weight = -1.0;
  52721. /**
  52722. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  52723. * This will only apply for non looping animation (default is true)
  52724. */
  52725. this.disposeOnEnd = true;
  52726. /**
  52727. * Gets a boolean indicating if the animation has started
  52728. */
  52729. this.animationStarted = false;
  52730. /**
  52731. * Observer raised when the animation ends
  52732. */
  52733. this.onAnimationEndObservable = new BABYLON.Observable();
  52734. this._scene = scene;
  52735. if (animations) {
  52736. this.appendAnimations(target, animations);
  52737. }
  52738. this._speedRatio = speedRatio;
  52739. scene._activeAnimatables.push(this);
  52740. }
  52741. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52742. /**
  52743. * Gets the root Animatable used to synchronize and normalize animations
  52744. */
  52745. get: function () {
  52746. return this._syncRoot;
  52747. },
  52748. enumerable: true,
  52749. configurable: true
  52750. });
  52751. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52752. /**
  52753. * Gets the current frame of the first RuntimeAnimation
  52754. * Used to synchronize Animatables
  52755. */
  52756. get: function () {
  52757. if (this._runtimeAnimations.length === 0) {
  52758. return 0;
  52759. }
  52760. return this._runtimeAnimations[0].currentFrame;
  52761. },
  52762. enumerable: true,
  52763. configurable: true
  52764. });
  52765. Object.defineProperty(Animatable.prototype, "weight", {
  52766. /**
  52767. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52768. */
  52769. get: function () {
  52770. return this._weight;
  52771. },
  52772. set: function (value) {
  52773. if (value === -1) { // -1 is ok and means no weight
  52774. this._weight = -1;
  52775. return;
  52776. }
  52777. // Else weight must be in [0, 1] range
  52778. this._weight = Math.min(Math.max(value, 0), 1.0);
  52779. },
  52780. enumerable: true,
  52781. configurable: true
  52782. });
  52783. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52784. /**
  52785. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52786. */
  52787. get: function () {
  52788. return this._speedRatio;
  52789. },
  52790. set: function (value) {
  52791. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52792. var animation = this._runtimeAnimations[index];
  52793. animation._prepareForSpeedRatioChange(value);
  52794. }
  52795. this._speedRatio = value;
  52796. },
  52797. enumerable: true,
  52798. configurable: true
  52799. });
  52800. // Methods
  52801. /**
  52802. * Synchronize and normalize current Animatable with a source Animatable
  52803. * This is useful when using animation weights and when animations are not of the same length
  52804. * @param root defines the root Animatable to synchronize with
  52805. * @returns the current Animatable
  52806. */
  52807. Animatable.prototype.syncWith = function (root) {
  52808. this._syncRoot = root;
  52809. if (root) {
  52810. // Make sure this animatable will animate after the root
  52811. var index = this._scene._activeAnimatables.indexOf(this);
  52812. if (index > -1) {
  52813. this._scene._activeAnimatables.splice(index, 1);
  52814. this._scene._activeAnimatables.push(this);
  52815. }
  52816. }
  52817. return this;
  52818. };
  52819. /**
  52820. * Gets the list of runtime animations
  52821. * @returns an array of RuntimeAnimation
  52822. */
  52823. Animatable.prototype.getAnimations = function () {
  52824. return this._runtimeAnimations;
  52825. };
  52826. /**
  52827. * Adds more animations to the current animatable
  52828. * @param target defines the target of the animations
  52829. * @param animations defines the new animations to add
  52830. */
  52831. Animatable.prototype.appendAnimations = function (target, animations) {
  52832. for (var index = 0; index < animations.length; index++) {
  52833. var animation = animations[index];
  52834. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52835. }
  52836. };
  52837. /**
  52838. * Gets the source animation for a specific property
  52839. * @param property defines the propertyu to look for
  52840. * @returns null or the source animation for the given property
  52841. */
  52842. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52843. var runtimeAnimations = this._runtimeAnimations;
  52844. for (var index = 0; index < runtimeAnimations.length; index++) {
  52845. if (runtimeAnimations[index].animation.targetProperty === property) {
  52846. return runtimeAnimations[index].animation;
  52847. }
  52848. }
  52849. return null;
  52850. };
  52851. /**
  52852. * Gets the runtime animation for a specific property
  52853. * @param property defines the propertyu to look for
  52854. * @returns null or the runtime animation for the given property
  52855. */
  52856. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52857. var runtimeAnimations = this._runtimeAnimations;
  52858. for (var index = 0; index < runtimeAnimations.length; index++) {
  52859. if (runtimeAnimations[index].animation.targetProperty === property) {
  52860. return runtimeAnimations[index];
  52861. }
  52862. }
  52863. return null;
  52864. };
  52865. /**
  52866. * Resets the animatable to its original state
  52867. */
  52868. Animatable.prototype.reset = function () {
  52869. var runtimeAnimations = this._runtimeAnimations;
  52870. for (var index = 0; index < runtimeAnimations.length; index++) {
  52871. runtimeAnimations[index].reset(true);
  52872. }
  52873. this._localDelayOffset = null;
  52874. this._pausedDelay = null;
  52875. };
  52876. /**
  52877. * Allows the animatable to blend with current running animations
  52878. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52879. * @param blendingSpeed defines the blending speed to use
  52880. */
  52881. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52882. var runtimeAnimations = this._runtimeAnimations;
  52883. for (var index = 0; index < runtimeAnimations.length; index++) {
  52884. runtimeAnimations[index].animation.enableBlending = true;
  52885. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52886. }
  52887. };
  52888. /**
  52889. * Disable animation blending
  52890. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52891. */
  52892. Animatable.prototype.disableBlending = function () {
  52893. var runtimeAnimations = this._runtimeAnimations;
  52894. for (var index = 0; index < runtimeAnimations.length; index++) {
  52895. runtimeAnimations[index].animation.enableBlending = false;
  52896. }
  52897. };
  52898. /**
  52899. * Jump directly to a given frame
  52900. * @param frame defines the frame to jump to
  52901. */
  52902. Animatable.prototype.goToFrame = function (frame) {
  52903. var runtimeAnimations = this._runtimeAnimations;
  52904. if (runtimeAnimations[0]) {
  52905. var fps = runtimeAnimations[0].animation.framePerSecond;
  52906. var currentFrame = runtimeAnimations[0].currentFrame;
  52907. var adjustTime = frame - currentFrame;
  52908. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52909. if (this._localDelayOffset === null) {
  52910. this._localDelayOffset = 0;
  52911. }
  52912. this._localDelayOffset -= delay;
  52913. }
  52914. for (var index = 0; index < runtimeAnimations.length; index++) {
  52915. runtimeAnimations[index].goToFrame(frame);
  52916. }
  52917. };
  52918. /**
  52919. * Pause the animation
  52920. */
  52921. Animatable.prototype.pause = function () {
  52922. if (this._paused) {
  52923. return;
  52924. }
  52925. this._paused = true;
  52926. };
  52927. /**
  52928. * Restart the animation
  52929. */
  52930. Animatable.prototype.restart = function () {
  52931. this._paused = false;
  52932. };
  52933. Animatable.prototype._raiseOnAnimationEnd = function () {
  52934. if (this.onAnimationEnd) {
  52935. this.onAnimationEnd();
  52936. }
  52937. this.onAnimationEndObservable.notifyObservers(this);
  52938. };
  52939. /**
  52940. * Stop and delete the current animation
  52941. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52942. * @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)
  52943. */
  52944. Animatable.prototype.stop = function (animationName, targetMask) {
  52945. if (animationName || targetMask) {
  52946. var idx = this._scene._activeAnimatables.indexOf(this);
  52947. if (idx > -1) {
  52948. var runtimeAnimations = this._runtimeAnimations;
  52949. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52950. var runtimeAnimation = runtimeAnimations[index];
  52951. if (animationName && runtimeAnimation.animation.name != animationName) {
  52952. continue;
  52953. }
  52954. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52955. continue;
  52956. }
  52957. runtimeAnimation.dispose();
  52958. runtimeAnimations.splice(index, 1);
  52959. }
  52960. if (runtimeAnimations.length == 0) {
  52961. this._scene._activeAnimatables.splice(idx, 1);
  52962. this._raiseOnAnimationEnd();
  52963. }
  52964. }
  52965. }
  52966. else {
  52967. var index = this._scene._activeAnimatables.indexOf(this);
  52968. if (index > -1) {
  52969. this._scene._activeAnimatables.splice(index, 1);
  52970. var runtimeAnimations = this._runtimeAnimations;
  52971. for (var index = 0; index < runtimeAnimations.length; index++) {
  52972. runtimeAnimations[index].dispose();
  52973. }
  52974. this._raiseOnAnimationEnd();
  52975. }
  52976. }
  52977. };
  52978. /**
  52979. * Wait asynchronously for the animation to end
  52980. * @returns a promise which will be fullfilled when the animation ends
  52981. */
  52982. Animatable.prototype.waitAsync = function () {
  52983. var _this = this;
  52984. return new Promise(function (resolve, reject) {
  52985. _this.onAnimationEndObservable.add(function () {
  52986. resolve(_this);
  52987. }, undefined, undefined, _this, true);
  52988. });
  52989. };
  52990. /** @hidden */
  52991. Animatable.prototype._animate = function (delay) {
  52992. if (this._paused) {
  52993. this.animationStarted = false;
  52994. if (this._pausedDelay === null) {
  52995. this._pausedDelay = delay;
  52996. }
  52997. return true;
  52998. }
  52999. if (this._localDelayOffset === null) {
  53000. this._localDelayOffset = delay;
  53001. this._pausedDelay = null;
  53002. }
  53003. else if (this._pausedDelay !== null) {
  53004. this._localDelayOffset += delay - this._pausedDelay;
  53005. this._pausedDelay = null;
  53006. }
  53007. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  53008. return true;
  53009. }
  53010. // Animating
  53011. var running = false;
  53012. var runtimeAnimations = this._runtimeAnimations;
  53013. var index;
  53014. for (index = 0; index < runtimeAnimations.length; index++) {
  53015. var animation = runtimeAnimations[index];
  53016. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  53017. running = running || isRunning;
  53018. }
  53019. this.animationStarted = running;
  53020. if (!running) {
  53021. if (this.disposeOnEnd) {
  53022. // Remove from active animatables
  53023. index = this._scene._activeAnimatables.indexOf(this);
  53024. this._scene._activeAnimatables.splice(index, 1);
  53025. // Dispose all runtime animations
  53026. for (index = 0; index < runtimeAnimations.length; index++) {
  53027. runtimeAnimations[index].dispose();
  53028. }
  53029. }
  53030. this._raiseOnAnimationEnd();
  53031. if (this.disposeOnEnd) {
  53032. this.onAnimationEnd = null;
  53033. this.onAnimationEndObservable.clear();
  53034. }
  53035. }
  53036. return running;
  53037. };
  53038. return Animatable;
  53039. }());
  53040. BABYLON.Animatable = Animatable;
  53041. })(BABYLON || (BABYLON = {}));
  53042. //# sourceMappingURL=babylon.animatable.js.map
  53043. var BABYLON;
  53044. (function (BABYLON) {
  53045. /**
  53046. * Base class used for every default easing function.
  53047. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53048. */
  53049. var EasingFunction = /** @class */ (function () {
  53050. function EasingFunction() {
  53051. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  53052. }
  53053. /**
  53054. * Sets the easing mode of the current function.
  53055. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  53056. */
  53057. EasingFunction.prototype.setEasingMode = function (easingMode) {
  53058. var n = Math.min(Math.max(easingMode, 0), 2);
  53059. this._easingMode = n;
  53060. };
  53061. /**
  53062. * Gets the current easing mode.
  53063. * @returns the easing mode
  53064. */
  53065. EasingFunction.prototype.getEasingMode = function () {
  53066. return this._easingMode;
  53067. };
  53068. /**
  53069. * @hidden
  53070. */
  53071. EasingFunction.prototype.easeInCore = function (gradient) {
  53072. throw new Error('You must implement this method');
  53073. };
  53074. /**
  53075. * Given an input gradient between 0 and 1, this returns the corrseponding value
  53076. * of the easing function.
  53077. * @param gradient Defines the value between 0 and 1 we want the easing value for
  53078. * @returns the corresponding value on the curve defined by the easing function
  53079. */
  53080. EasingFunction.prototype.ease = function (gradient) {
  53081. switch (this._easingMode) {
  53082. case EasingFunction.EASINGMODE_EASEIN:
  53083. return this.easeInCore(gradient);
  53084. case EasingFunction.EASINGMODE_EASEOUT:
  53085. return (1 - this.easeInCore(1 - gradient));
  53086. }
  53087. if (gradient >= 0.5) {
  53088. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  53089. }
  53090. return (this.easeInCore(gradient * 2) * 0.5);
  53091. };
  53092. /**
  53093. * Interpolation follows the mathematical formula associated with the easing function.
  53094. */
  53095. EasingFunction.EASINGMODE_EASEIN = 0;
  53096. /**
  53097. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  53098. */
  53099. EasingFunction.EASINGMODE_EASEOUT = 1;
  53100. /**
  53101. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  53102. */
  53103. EasingFunction.EASINGMODE_EASEINOUT = 2;
  53104. return EasingFunction;
  53105. }());
  53106. BABYLON.EasingFunction = EasingFunction;
  53107. /**
  53108. * Easing function with a circle shape (see link below).
  53109. * @see https://easings.net/#easeInCirc
  53110. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53111. */
  53112. var CircleEase = /** @class */ (function (_super) {
  53113. __extends(CircleEase, _super);
  53114. function CircleEase() {
  53115. return _super !== null && _super.apply(this, arguments) || this;
  53116. }
  53117. /** @hidden */
  53118. CircleEase.prototype.easeInCore = function (gradient) {
  53119. gradient = Math.max(0, Math.min(1, gradient));
  53120. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  53121. };
  53122. return CircleEase;
  53123. }(EasingFunction));
  53124. BABYLON.CircleEase = CircleEase;
  53125. /**
  53126. * Easing function with a ease back shape (see link below).
  53127. * @see https://easings.net/#easeInBack
  53128. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53129. */
  53130. var BackEase = /** @class */ (function (_super) {
  53131. __extends(BackEase, _super);
  53132. /**
  53133. * Instantiates a back ease easing
  53134. * @see https://easings.net/#easeInBack
  53135. * @param amplitude Defines the amplitude of the function
  53136. */
  53137. function BackEase(
  53138. /** Defines the amplitude of the function */
  53139. amplitude) {
  53140. if (amplitude === void 0) { amplitude = 1; }
  53141. var _this = _super.call(this) || this;
  53142. _this.amplitude = amplitude;
  53143. return _this;
  53144. }
  53145. /** @hidden */
  53146. BackEase.prototype.easeInCore = function (gradient) {
  53147. var num = Math.max(0, this.amplitude);
  53148. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  53149. };
  53150. return BackEase;
  53151. }(EasingFunction));
  53152. BABYLON.BackEase = BackEase;
  53153. /**
  53154. * Easing function with a bouncing shape (see link below).
  53155. * @see https://easings.net/#easeInBounce
  53156. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53157. */
  53158. var BounceEase = /** @class */ (function (_super) {
  53159. __extends(BounceEase, _super);
  53160. /**
  53161. * Instantiates a bounce easing
  53162. * @see https://easings.net/#easeInBounce
  53163. * @param bounces Defines the number of bounces
  53164. * @param bounciness Defines the amplitude of the bounce
  53165. */
  53166. function BounceEase(
  53167. /** Defines the number of bounces */
  53168. bounces,
  53169. /** Defines the amplitude of the bounce */
  53170. bounciness) {
  53171. if (bounces === void 0) { bounces = 3; }
  53172. if (bounciness === void 0) { bounciness = 2; }
  53173. var _this = _super.call(this) || this;
  53174. _this.bounces = bounces;
  53175. _this.bounciness = bounciness;
  53176. return _this;
  53177. }
  53178. /** @hidden */
  53179. BounceEase.prototype.easeInCore = function (gradient) {
  53180. var y = Math.max(0.0, this.bounces);
  53181. var bounciness = this.bounciness;
  53182. if (bounciness <= 1.0) {
  53183. bounciness = 1.001;
  53184. }
  53185. var num9 = Math.pow(bounciness, y);
  53186. var num5 = 1.0 - bounciness;
  53187. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  53188. var num15 = gradient * num4;
  53189. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  53190. var num3 = Math.floor(num65);
  53191. var num13 = num3 + 1.0;
  53192. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  53193. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  53194. var num7 = (num8 + num12) * 0.5;
  53195. var num6 = gradient - num7;
  53196. var num2 = num7 - num8;
  53197. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  53198. };
  53199. return BounceEase;
  53200. }(EasingFunction));
  53201. BABYLON.BounceEase = BounceEase;
  53202. /**
  53203. * Easing function with a power of 3 shape (see link below).
  53204. * @see https://easings.net/#easeInCubic
  53205. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53206. */
  53207. var CubicEase = /** @class */ (function (_super) {
  53208. __extends(CubicEase, _super);
  53209. function CubicEase() {
  53210. return _super !== null && _super.apply(this, arguments) || this;
  53211. }
  53212. /** @hidden */
  53213. CubicEase.prototype.easeInCore = function (gradient) {
  53214. return (gradient * gradient * gradient);
  53215. };
  53216. return CubicEase;
  53217. }(EasingFunction));
  53218. BABYLON.CubicEase = CubicEase;
  53219. /**
  53220. * Easing function with an elastic shape (see link below).
  53221. * @see https://easings.net/#easeInElastic
  53222. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53223. */
  53224. var ElasticEase = /** @class */ (function (_super) {
  53225. __extends(ElasticEase, _super);
  53226. /**
  53227. * Instantiates an elastic easing function
  53228. * @see https://easings.net/#easeInElastic
  53229. * @param oscillations Defines the number of oscillations
  53230. * @param springiness Defines the amplitude of the oscillations
  53231. */
  53232. function ElasticEase(
  53233. /** Defines the number of oscillations*/
  53234. oscillations,
  53235. /** Defines the amplitude of the oscillations*/
  53236. springiness) {
  53237. if (oscillations === void 0) { oscillations = 3; }
  53238. if (springiness === void 0) { springiness = 3; }
  53239. var _this = _super.call(this) || this;
  53240. _this.oscillations = oscillations;
  53241. _this.springiness = springiness;
  53242. return _this;
  53243. }
  53244. /** @hidden */
  53245. ElasticEase.prototype.easeInCore = function (gradient) {
  53246. var num2;
  53247. var num3 = Math.max(0.0, this.oscillations);
  53248. var num = Math.max(0.0, this.springiness);
  53249. if (num == 0) {
  53250. num2 = gradient;
  53251. }
  53252. else {
  53253. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53254. }
  53255. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53256. };
  53257. return ElasticEase;
  53258. }(EasingFunction));
  53259. BABYLON.ElasticEase = ElasticEase;
  53260. /**
  53261. * Easing function with an exponential shape (see link below).
  53262. * @see https://easings.net/#easeInExpo
  53263. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53264. */
  53265. var ExponentialEase = /** @class */ (function (_super) {
  53266. __extends(ExponentialEase, _super);
  53267. /**
  53268. * Instantiates an exponential easing function
  53269. * @see https://easings.net/#easeInExpo
  53270. * @param exponent Defines the exponent of the function
  53271. */
  53272. function ExponentialEase(
  53273. /** Defines the exponent of the function */
  53274. exponent) {
  53275. if (exponent === void 0) { exponent = 2; }
  53276. var _this = _super.call(this) || this;
  53277. _this.exponent = exponent;
  53278. return _this;
  53279. }
  53280. /** @hidden */
  53281. ExponentialEase.prototype.easeInCore = function (gradient) {
  53282. if (this.exponent <= 0) {
  53283. return gradient;
  53284. }
  53285. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53286. };
  53287. return ExponentialEase;
  53288. }(EasingFunction));
  53289. BABYLON.ExponentialEase = ExponentialEase;
  53290. /**
  53291. * Easing function with a power shape (see link below).
  53292. * @see https://easings.net/#easeInQuad
  53293. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53294. */
  53295. var PowerEase = /** @class */ (function (_super) {
  53296. __extends(PowerEase, _super);
  53297. /**
  53298. * Instantiates an power base easing function
  53299. * @see https://easings.net/#easeInQuad
  53300. * @param power Defines the power of the function
  53301. */
  53302. function PowerEase(
  53303. /** Defines the power of the function */
  53304. power) {
  53305. if (power === void 0) { power = 2; }
  53306. var _this = _super.call(this) || this;
  53307. _this.power = power;
  53308. return _this;
  53309. }
  53310. /** @hidden */
  53311. PowerEase.prototype.easeInCore = function (gradient) {
  53312. var y = Math.max(0.0, this.power);
  53313. return Math.pow(gradient, y);
  53314. };
  53315. return PowerEase;
  53316. }(EasingFunction));
  53317. BABYLON.PowerEase = PowerEase;
  53318. /**
  53319. * Easing function with a power of 2 shape (see link below).
  53320. * @see https://easings.net/#easeInQuad
  53321. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53322. */
  53323. var QuadraticEase = /** @class */ (function (_super) {
  53324. __extends(QuadraticEase, _super);
  53325. function QuadraticEase() {
  53326. return _super !== null && _super.apply(this, arguments) || this;
  53327. }
  53328. /** @hidden */
  53329. QuadraticEase.prototype.easeInCore = function (gradient) {
  53330. return (gradient * gradient);
  53331. };
  53332. return QuadraticEase;
  53333. }(EasingFunction));
  53334. BABYLON.QuadraticEase = QuadraticEase;
  53335. /**
  53336. * Easing function with a power of 4 shape (see link below).
  53337. * @see https://easings.net/#easeInQuart
  53338. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53339. */
  53340. var QuarticEase = /** @class */ (function (_super) {
  53341. __extends(QuarticEase, _super);
  53342. function QuarticEase() {
  53343. return _super !== null && _super.apply(this, arguments) || this;
  53344. }
  53345. /** @hidden */
  53346. QuarticEase.prototype.easeInCore = function (gradient) {
  53347. return (gradient * gradient * gradient * gradient);
  53348. };
  53349. return QuarticEase;
  53350. }(EasingFunction));
  53351. BABYLON.QuarticEase = QuarticEase;
  53352. /**
  53353. * Easing function with a power of 5 shape (see link below).
  53354. * @see https://easings.net/#easeInQuint
  53355. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53356. */
  53357. var QuinticEase = /** @class */ (function (_super) {
  53358. __extends(QuinticEase, _super);
  53359. function QuinticEase() {
  53360. return _super !== null && _super.apply(this, arguments) || this;
  53361. }
  53362. /** @hidden */
  53363. QuinticEase.prototype.easeInCore = function (gradient) {
  53364. return (gradient * gradient * gradient * gradient * gradient);
  53365. };
  53366. return QuinticEase;
  53367. }(EasingFunction));
  53368. BABYLON.QuinticEase = QuinticEase;
  53369. /**
  53370. * Easing function with a sin shape (see link below).
  53371. * @see https://easings.net/#easeInSine
  53372. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53373. */
  53374. var SineEase = /** @class */ (function (_super) {
  53375. __extends(SineEase, _super);
  53376. function SineEase() {
  53377. return _super !== null && _super.apply(this, arguments) || this;
  53378. }
  53379. /** @hidden */
  53380. SineEase.prototype.easeInCore = function (gradient) {
  53381. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53382. };
  53383. return SineEase;
  53384. }(EasingFunction));
  53385. BABYLON.SineEase = SineEase;
  53386. /**
  53387. * Easing function with a bezier shape (see link below).
  53388. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53389. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53390. */
  53391. var BezierCurveEase = /** @class */ (function (_super) {
  53392. __extends(BezierCurveEase, _super);
  53393. /**
  53394. * Instantiates a bezier function
  53395. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53396. * @param x1 Defines the x component of the start tangent in the bezier curve
  53397. * @param y1 Defines the y component of the start tangent in the bezier curve
  53398. * @param x2 Defines the x component of the end tangent in the bezier curve
  53399. * @param y2 Defines the y component of the end tangent in the bezier curve
  53400. */
  53401. function BezierCurveEase(
  53402. /** Defines the x component of the start tangent in the bezier curve */
  53403. x1,
  53404. /** Defines the y component of the start tangent in the bezier curve */
  53405. y1,
  53406. /** Defines the x component of the end tangent in the bezier curve */
  53407. x2,
  53408. /** Defines the y component of the end tangent in the bezier curve */
  53409. y2) {
  53410. if (x1 === void 0) { x1 = 0; }
  53411. if (y1 === void 0) { y1 = 0; }
  53412. if (x2 === void 0) { x2 = 1; }
  53413. if (y2 === void 0) { y2 = 1; }
  53414. var _this = _super.call(this) || this;
  53415. _this.x1 = x1;
  53416. _this.y1 = y1;
  53417. _this.x2 = x2;
  53418. _this.y2 = y2;
  53419. return _this;
  53420. }
  53421. /** @hidden */
  53422. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53423. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53424. };
  53425. return BezierCurveEase;
  53426. }(EasingFunction));
  53427. BABYLON.BezierCurveEase = BezierCurveEase;
  53428. })(BABYLON || (BABYLON = {}));
  53429. //# sourceMappingURL=babylon.easing.js.map
  53430. var BABYLON;
  53431. (function (BABYLON) {
  53432. /**
  53433. * A Condition applied to an Action
  53434. */
  53435. var Condition = /** @class */ (function () {
  53436. /**
  53437. * Creates a new Condition
  53438. * @param actionManager the manager of the action the condition is applied to
  53439. */
  53440. function Condition(actionManager) {
  53441. this._actionManager = actionManager;
  53442. }
  53443. /**
  53444. * Check if the current condition is valid
  53445. * @returns a boolean
  53446. */
  53447. Condition.prototype.isValid = function () {
  53448. return true;
  53449. };
  53450. /**
  53451. * Internal only
  53452. * @hidden
  53453. */
  53454. Condition.prototype._getProperty = function (propertyPath) {
  53455. return this._actionManager._getProperty(propertyPath);
  53456. };
  53457. /**
  53458. * Internal only
  53459. * @hidden
  53460. */
  53461. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53462. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53463. };
  53464. /**
  53465. * Serialize placeholder for child classes
  53466. * @returns the serialized object
  53467. */
  53468. Condition.prototype.serialize = function () {
  53469. };
  53470. /**
  53471. * Internal only
  53472. * @hidden
  53473. */
  53474. Condition.prototype._serialize = function (serializedCondition) {
  53475. return {
  53476. type: 2,
  53477. children: [],
  53478. name: serializedCondition.name,
  53479. properties: serializedCondition.properties
  53480. };
  53481. };
  53482. return Condition;
  53483. }());
  53484. BABYLON.Condition = Condition;
  53485. /**
  53486. * Defines specific conditional operators as extensions of Condition
  53487. */
  53488. var ValueCondition = /** @class */ (function (_super) {
  53489. __extends(ValueCondition, _super);
  53490. /**
  53491. * Creates a new ValueCondition
  53492. * @param actionManager manager for the action the condition applies to
  53493. * @param target for the action
  53494. * @param propertyPath path to specify the property of the target the conditional operator uses
  53495. * @param value the value compared by the conditional operator against the current value of the property
  53496. * @param operator the conditional operator, default ValueCondition.IsEqual
  53497. */
  53498. function ValueCondition(actionManager, target,
  53499. /** path to specify the property of the target the conditional operator uses */
  53500. propertyPath,
  53501. /** the value compared by the conditional operator against the current value of the property */
  53502. value,
  53503. /** the conditional operator, default ValueCondition.IsEqual */
  53504. operator) {
  53505. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53506. var _this = _super.call(this, actionManager) || this;
  53507. _this.propertyPath = propertyPath;
  53508. _this.value = value;
  53509. _this.operator = operator;
  53510. _this._target = target;
  53511. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53512. _this._property = _this._getProperty(_this.propertyPath);
  53513. return _this;
  53514. }
  53515. Object.defineProperty(ValueCondition, "IsEqual", {
  53516. /**
  53517. * returns the number for IsEqual
  53518. */
  53519. get: function () {
  53520. return ValueCondition._IsEqual;
  53521. },
  53522. enumerable: true,
  53523. configurable: true
  53524. });
  53525. Object.defineProperty(ValueCondition, "IsDifferent", {
  53526. /**
  53527. * Returns the number for IsDifferent
  53528. */
  53529. get: function () {
  53530. return ValueCondition._IsDifferent;
  53531. },
  53532. enumerable: true,
  53533. configurable: true
  53534. });
  53535. Object.defineProperty(ValueCondition, "IsGreater", {
  53536. /**
  53537. * Returns the number for IsGreater
  53538. */
  53539. get: function () {
  53540. return ValueCondition._IsGreater;
  53541. },
  53542. enumerable: true,
  53543. configurable: true
  53544. });
  53545. Object.defineProperty(ValueCondition, "IsLesser", {
  53546. /**
  53547. * Returns the number for IsLesser
  53548. */
  53549. get: function () {
  53550. return ValueCondition._IsLesser;
  53551. },
  53552. enumerable: true,
  53553. configurable: true
  53554. });
  53555. /**
  53556. * Compares the given value with the property value for the specified conditional operator
  53557. * @returns the result of the comparison
  53558. */
  53559. ValueCondition.prototype.isValid = function () {
  53560. switch (this.operator) {
  53561. case ValueCondition.IsGreater:
  53562. return this._effectiveTarget[this._property] > this.value;
  53563. case ValueCondition.IsLesser:
  53564. return this._effectiveTarget[this._property] < this.value;
  53565. case ValueCondition.IsEqual:
  53566. case ValueCondition.IsDifferent:
  53567. var check;
  53568. if (this.value.equals) {
  53569. check = this.value.equals(this._effectiveTarget[this._property]);
  53570. }
  53571. else {
  53572. check = this.value === this._effectiveTarget[this._property];
  53573. }
  53574. return this.operator === ValueCondition.IsEqual ? check : !check;
  53575. }
  53576. return false;
  53577. };
  53578. /**
  53579. * Serialize the ValueCondition into a JSON compatible object
  53580. * @returns serialization object
  53581. */
  53582. ValueCondition.prototype.serialize = function () {
  53583. return this._serialize({
  53584. name: "ValueCondition",
  53585. properties: [
  53586. BABYLON.Action._GetTargetProperty(this._target),
  53587. { name: "propertyPath", value: this.propertyPath },
  53588. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53589. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53590. ]
  53591. });
  53592. };
  53593. /**
  53594. * Gets the name of the conditional operator for the ValueCondition
  53595. * @param operator the conditional operator
  53596. * @returns the name
  53597. */
  53598. ValueCondition.GetOperatorName = function (operator) {
  53599. switch (operator) {
  53600. case ValueCondition._IsEqual: return "IsEqual";
  53601. case ValueCondition._IsDifferent: return "IsDifferent";
  53602. case ValueCondition._IsGreater: return "IsGreater";
  53603. case ValueCondition._IsLesser: return "IsLesser";
  53604. default: return "";
  53605. }
  53606. };
  53607. /**
  53608. * Internal only
  53609. * @hidden
  53610. */
  53611. ValueCondition._IsEqual = 0;
  53612. /**
  53613. * Internal only
  53614. * @hidden
  53615. */
  53616. ValueCondition._IsDifferent = 1;
  53617. /**
  53618. * Internal only
  53619. * @hidden
  53620. */
  53621. ValueCondition._IsGreater = 2;
  53622. /**
  53623. * Internal only
  53624. * @hidden
  53625. */
  53626. ValueCondition._IsLesser = 3;
  53627. return ValueCondition;
  53628. }(Condition));
  53629. BABYLON.ValueCondition = ValueCondition;
  53630. /**
  53631. * Defines a predicate condition as an extension of Condition
  53632. */
  53633. var PredicateCondition = /** @class */ (function (_super) {
  53634. __extends(PredicateCondition, _super);
  53635. /**
  53636. * Creates a new PredicateCondition
  53637. * @param actionManager manager for the action the condition applies to
  53638. * @param predicate defines the predicate function used to validate the condition
  53639. */
  53640. function PredicateCondition(actionManager,
  53641. /** defines the predicate function used to validate the condition */
  53642. predicate) {
  53643. var _this = _super.call(this, actionManager) || this;
  53644. _this.predicate = predicate;
  53645. return _this;
  53646. }
  53647. /**
  53648. * @returns the validity of the predicate condition
  53649. */
  53650. PredicateCondition.prototype.isValid = function () {
  53651. return this.predicate();
  53652. };
  53653. return PredicateCondition;
  53654. }(Condition));
  53655. BABYLON.PredicateCondition = PredicateCondition;
  53656. /**
  53657. * Defines a state condition as an extension of Condition
  53658. */
  53659. var StateCondition = /** @class */ (function (_super) {
  53660. __extends(StateCondition, _super);
  53661. /**
  53662. * Creates a new StateCondition
  53663. * @param actionManager manager for the action the condition applies to
  53664. * @param target of the condition
  53665. * @param value to compare with target state
  53666. */
  53667. function StateCondition(actionManager, target, value) {
  53668. var _this = _super.call(this, actionManager) || this;
  53669. _this.value = value;
  53670. _this._target = target;
  53671. return _this;
  53672. }
  53673. /**
  53674. * @returns the validity of the state
  53675. */
  53676. StateCondition.prototype.isValid = function () {
  53677. return this._target.state === this.value;
  53678. };
  53679. /**
  53680. * Serialize the StateCondition into a JSON compatible object
  53681. * @returns serialization object
  53682. */
  53683. StateCondition.prototype.serialize = function () {
  53684. return this._serialize({
  53685. name: "StateCondition",
  53686. properties: [
  53687. BABYLON.Action._GetTargetProperty(this._target),
  53688. { name: "value", value: this.value }
  53689. ]
  53690. });
  53691. };
  53692. return StateCondition;
  53693. }(Condition));
  53694. BABYLON.StateCondition = StateCondition;
  53695. })(BABYLON || (BABYLON = {}));
  53696. //# sourceMappingURL=babylon.condition.js.map
  53697. var BABYLON;
  53698. (function (BABYLON) {
  53699. /**
  53700. * The action to be carried out following a trigger
  53701. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53702. */
  53703. var Action = /** @class */ (function () {
  53704. /**
  53705. * Creates a new Action
  53706. * @param triggerOptions the trigger, with or without parameters, for the action
  53707. * @param condition an optional determinant of action
  53708. */
  53709. function Action(
  53710. /** the trigger, with or without parameters, for the action */
  53711. triggerOptions, condition) {
  53712. this.triggerOptions = triggerOptions;
  53713. /**
  53714. * An event triggered prior to action being executed.
  53715. */
  53716. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53717. if (triggerOptions.parameter) {
  53718. this.trigger = triggerOptions.trigger;
  53719. this._triggerParameter = triggerOptions.parameter;
  53720. }
  53721. else if (triggerOptions.trigger) {
  53722. this.trigger = triggerOptions.trigger;
  53723. }
  53724. else {
  53725. this.trigger = triggerOptions;
  53726. }
  53727. this._nextActiveAction = this;
  53728. this._condition = condition;
  53729. }
  53730. /**
  53731. * Internal only
  53732. * @hidden
  53733. */
  53734. Action.prototype._prepare = function () {
  53735. };
  53736. /**
  53737. * Gets the trigger parameters
  53738. * @returns the trigger parameters
  53739. */
  53740. Action.prototype.getTriggerParameter = function () {
  53741. return this._triggerParameter;
  53742. };
  53743. /**
  53744. * Internal only - executes current action event
  53745. * @hidden
  53746. */
  53747. Action.prototype._executeCurrent = function (evt) {
  53748. if (this._nextActiveAction._condition) {
  53749. var condition = this._nextActiveAction._condition;
  53750. var currentRenderId = this._actionManager.getScene().getRenderId();
  53751. // We cache the current evaluation for the current frame
  53752. if (condition._evaluationId === currentRenderId) {
  53753. if (!condition._currentResult) {
  53754. return;
  53755. }
  53756. }
  53757. else {
  53758. condition._evaluationId = currentRenderId;
  53759. if (!condition.isValid()) {
  53760. condition._currentResult = false;
  53761. return;
  53762. }
  53763. condition._currentResult = true;
  53764. }
  53765. }
  53766. this.onBeforeExecuteObservable.notifyObservers(this);
  53767. this._nextActiveAction.execute(evt);
  53768. this.skipToNextActiveAction();
  53769. };
  53770. /**
  53771. * Execute placeholder for child classes
  53772. * @param evt optional action event
  53773. */
  53774. Action.prototype.execute = function (evt) {
  53775. };
  53776. /**
  53777. * Skips to next active action
  53778. */
  53779. Action.prototype.skipToNextActiveAction = function () {
  53780. if (this._nextActiveAction._child) {
  53781. if (!this._nextActiveAction._child._actionManager) {
  53782. this._nextActiveAction._child._actionManager = this._actionManager;
  53783. }
  53784. this._nextActiveAction = this._nextActiveAction._child;
  53785. }
  53786. else {
  53787. this._nextActiveAction = this;
  53788. }
  53789. };
  53790. /**
  53791. * Adds action to chain of actions, may be a DoNothingAction
  53792. * @param action defines the next action to execute
  53793. * @returns The action passed in
  53794. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53795. */
  53796. Action.prototype.then = function (action) {
  53797. this._child = action;
  53798. action._actionManager = this._actionManager;
  53799. action._prepare();
  53800. return action;
  53801. };
  53802. /**
  53803. * Internal only
  53804. * @hidden
  53805. */
  53806. Action.prototype._getProperty = function (propertyPath) {
  53807. return this._actionManager._getProperty(propertyPath);
  53808. };
  53809. /**
  53810. * Internal only
  53811. * @hidden
  53812. */
  53813. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53814. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53815. };
  53816. /**
  53817. * Serialize placeholder for child classes
  53818. * @param parent of child
  53819. * @returns the serialized object
  53820. */
  53821. Action.prototype.serialize = function (parent) {
  53822. };
  53823. /**
  53824. * Internal only called by serialize
  53825. * @hidden
  53826. */
  53827. Action.prototype._serialize = function (serializedAction, parent) {
  53828. var serializationObject = {
  53829. type: 1,
  53830. children: [],
  53831. name: serializedAction.name,
  53832. properties: serializedAction.properties || []
  53833. };
  53834. // Serialize child
  53835. if (this._child) {
  53836. this._child.serialize(serializationObject);
  53837. }
  53838. // Check if "this" has a condition
  53839. if (this._condition) {
  53840. var serializedCondition = this._condition.serialize();
  53841. serializedCondition.children.push(serializationObject);
  53842. if (parent) {
  53843. parent.children.push(serializedCondition);
  53844. }
  53845. return serializedCondition;
  53846. }
  53847. if (parent) {
  53848. parent.children.push(serializationObject);
  53849. }
  53850. return serializationObject;
  53851. };
  53852. /**
  53853. * Internal only
  53854. * @hidden
  53855. */
  53856. Action._SerializeValueAsString = function (value) {
  53857. if (typeof value === "number") {
  53858. return value.toString();
  53859. }
  53860. if (typeof value === "boolean") {
  53861. return value ? "true" : "false";
  53862. }
  53863. if (value instanceof BABYLON.Vector2) {
  53864. return value.x + ", " + value.y;
  53865. }
  53866. if (value instanceof BABYLON.Vector3) {
  53867. return value.x + ", " + value.y + ", " + value.z;
  53868. }
  53869. if (value instanceof BABYLON.Color3) {
  53870. return value.r + ", " + value.g + ", " + value.b;
  53871. }
  53872. if (value instanceof BABYLON.Color4) {
  53873. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53874. }
  53875. return value; // string
  53876. };
  53877. /**
  53878. * Internal only
  53879. * @hidden
  53880. */
  53881. Action._GetTargetProperty = function (target) {
  53882. return {
  53883. name: "target",
  53884. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53885. : target instanceof BABYLON.Light ? "LightProperties"
  53886. : target instanceof BABYLON.Camera ? "CameraProperties"
  53887. : "SceneProperties",
  53888. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53889. };
  53890. };
  53891. return Action;
  53892. }());
  53893. BABYLON.Action = Action;
  53894. })(BABYLON || (BABYLON = {}));
  53895. //# sourceMappingURL=babylon.action.js.map
  53896. var BABYLON;
  53897. (function (BABYLON) {
  53898. /**
  53899. * ActionEvent is the event being sent when an action is triggered.
  53900. */
  53901. var ActionEvent = /** @class */ (function () {
  53902. /**
  53903. * Creates a new ActionEvent
  53904. * @param source The mesh or sprite that triggered the action
  53905. * @param pointerX The X mouse cursor position at the time of the event
  53906. * @param pointerY The Y mouse cursor position at the time of the event
  53907. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53908. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53909. * @param additionalData additional data for the event
  53910. */
  53911. function ActionEvent(
  53912. /** The mesh or sprite that triggered the action */
  53913. source,
  53914. /** The X mouse cursor position at the time of the event */
  53915. pointerX,
  53916. /** The Y mouse cursor position at the time of the event */
  53917. pointerY,
  53918. /** The mesh that is currently pointed at (can be null) */
  53919. meshUnderPointer,
  53920. /** the original (browser) event that triggered the ActionEvent */
  53921. sourceEvent,
  53922. /** additional data for the event */
  53923. additionalData) {
  53924. this.source = source;
  53925. this.pointerX = pointerX;
  53926. this.pointerY = pointerY;
  53927. this.meshUnderPointer = meshUnderPointer;
  53928. this.sourceEvent = sourceEvent;
  53929. this.additionalData = additionalData;
  53930. }
  53931. /**
  53932. * Helper function to auto-create an ActionEvent from a source mesh.
  53933. * @param source The source mesh that triggered the event
  53934. * @param evt The original (browser) event
  53935. * @param additionalData additional data for the event
  53936. * @returns the new ActionEvent
  53937. */
  53938. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53939. var scene = source.getScene();
  53940. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53941. };
  53942. /**
  53943. * Helper function to auto-create an ActionEvent from a source sprite
  53944. * @param source The source sprite that triggered the event
  53945. * @param scene Scene associated with the sprite
  53946. * @param evt The original (browser) event
  53947. * @param additionalData additional data for the event
  53948. * @returns the new ActionEvent
  53949. */
  53950. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53951. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53952. };
  53953. /**
  53954. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53955. * @param scene the scene where the event occurred
  53956. * @param evt The original (browser) event
  53957. * @returns the new ActionEvent
  53958. */
  53959. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53960. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53961. };
  53962. /**
  53963. * Helper function to auto-create an ActionEvent from a primitive
  53964. * @param prim defines the target primitive
  53965. * @param pointerPos defines the pointer position
  53966. * @param evt The original (browser) event
  53967. * @param additionalData additional data for the event
  53968. * @returns the new ActionEvent
  53969. */
  53970. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53971. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53972. };
  53973. return ActionEvent;
  53974. }());
  53975. BABYLON.ActionEvent = ActionEvent;
  53976. /**
  53977. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53978. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53979. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53980. */
  53981. var ActionManager = /** @class */ (function () {
  53982. /**
  53983. * Creates a new action manager
  53984. * @param scene defines the hosting scene
  53985. */
  53986. function ActionManager(scene) {
  53987. // Members
  53988. /** Gets the list of actions */
  53989. this.actions = new Array();
  53990. /** Gets the cursor to use when hovering items */
  53991. this.hoverCursor = '';
  53992. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53993. scene.actionManagers.push(this);
  53994. }
  53995. // Methods
  53996. /**
  53997. * Releases all associated resources
  53998. */
  53999. ActionManager.prototype.dispose = function () {
  54000. var index = this._scene.actionManagers.indexOf(this);
  54001. for (var i = 0; i < this.actions.length; i++) {
  54002. var action = this.actions[i];
  54003. ActionManager.Triggers[action.trigger]--;
  54004. if (ActionManager.Triggers[action.trigger] === 0) {
  54005. delete ActionManager.Triggers[action.trigger];
  54006. }
  54007. }
  54008. if (index > -1) {
  54009. this._scene.actionManagers.splice(index, 1);
  54010. }
  54011. };
  54012. /**
  54013. * Gets hosting scene
  54014. * @returns the hosting scene
  54015. */
  54016. ActionManager.prototype.getScene = function () {
  54017. return this._scene;
  54018. };
  54019. /**
  54020. * Does this action manager handles actions of any of the given triggers
  54021. * @param triggers defines the triggers to be tested
  54022. * @return a boolean indicating whether one (or more) of the triggers is handled
  54023. */
  54024. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  54025. for (var index = 0; index < this.actions.length; index++) {
  54026. var action = this.actions[index];
  54027. if (triggers.indexOf(action.trigger) > -1) {
  54028. return true;
  54029. }
  54030. }
  54031. return false;
  54032. };
  54033. /**
  54034. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  54035. * speed.
  54036. * @param triggerA defines the trigger to be tested
  54037. * @param triggerB defines the trigger to be tested
  54038. * @return a boolean indicating whether one (or more) of the triggers is handled
  54039. */
  54040. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  54041. for (var index = 0; index < this.actions.length; index++) {
  54042. var action = this.actions[index];
  54043. if (triggerA == action.trigger || triggerB == action.trigger) {
  54044. return true;
  54045. }
  54046. }
  54047. return false;
  54048. };
  54049. /**
  54050. * Does this action manager handles actions of a given trigger
  54051. * @param trigger defines the trigger to be tested
  54052. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  54053. * @return whether the trigger is handled
  54054. */
  54055. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  54056. for (var index = 0; index < this.actions.length; index++) {
  54057. var action = this.actions[index];
  54058. if (action.trigger === trigger) {
  54059. if (parameterPredicate) {
  54060. if (parameterPredicate(action.getTriggerParameter())) {
  54061. return true;
  54062. }
  54063. }
  54064. else {
  54065. return true;
  54066. }
  54067. }
  54068. }
  54069. return false;
  54070. };
  54071. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  54072. /**
  54073. * Does this action manager has pointer triggers
  54074. */
  54075. get: function () {
  54076. for (var index = 0; index < this.actions.length; index++) {
  54077. var action = this.actions[index];
  54078. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  54079. return true;
  54080. }
  54081. }
  54082. return false;
  54083. },
  54084. enumerable: true,
  54085. configurable: true
  54086. });
  54087. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  54088. /**
  54089. * Does this action manager has pick triggers
  54090. */
  54091. get: function () {
  54092. for (var index = 0; index < this.actions.length; index++) {
  54093. var action = this.actions[index];
  54094. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  54095. return true;
  54096. }
  54097. }
  54098. return false;
  54099. },
  54100. enumerable: true,
  54101. configurable: true
  54102. });
  54103. Object.defineProperty(ActionManager, "HasTriggers", {
  54104. /**
  54105. * Does exist one action manager with at least one trigger
  54106. **/
  54107. get: function () {
  54108. for (var t in ActionManager.Triggers) {
  54109. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54110. return true;
  54111. }
  54112. }
  54113. return false;
  54114. },
  54115. enumerable: true,
  54116. configurable: true
  54117. });
  54118. Object.defineProperty(ActionManager, "HasPickTriggers", {
  54119. /**
  54120. * Does exist one action manager with at least one pick trigger
  54121. **/
  54122. get: function () {
  54123. for (var t in ActionManager.Triggers) {
  54124. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54125. var t_int = parseInt(t);
  54126. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  54127. return true;
  54128. }
  54129. }
  54130. }
  54131. return false;
  54132. },
  54133. enumerable: true,
  54134. configurable: true
  54135. });
  54136. /**
  54137. * Does exist one action manager that handles actions of a given trigger
  54138. * @param trigger defines the trigger to be tested
  54139. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  54140. **/
  54141. ActionManager.HasSpecificTrigger = function (trigger) {
  54142. for (var t in ActionManager.Triggers) {
  54143. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54144. var t_int = parseInt(t);
  54145. if (t_int === trigger) {
  54146. return true;
  54147. }
  54148. }
  54149. }
  54150. return false;
  54151. };
  54152. /**
  54153. * Registers an action to this action manager
  54154. * @param action defines the action to be registered
  54155. * @return the action amended (prepared) after registration
  54156. */
  54157. ActionManager.prototype.registerAction = function (action) {
  54158. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54159. if (this.getScene().actionManager !== this) {
  54160. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54161. return null;
  54162. }
  54163. }
  54164. this.actions.push(action);
  54165. if (ActionManager.Triggers[action.trigger]) {
  54166. ActionManager.Triggers[action.trigger]++;
  54167. }
  54168. else {
  54169. ActionManager.Triggers[action.trigger] = 1;
  54170. }
  54171. action._actionManager = this;
  54172. action._prepare();
  54173. return action;
  54174. };
  54175. /**
  54176. * Unregisters an action to this action manager
  54177. * @param action defines the action to be unregistered
  54178. * @return a boolean indicating whether the action has been unregistered
  54179. */
  54180. ActionManager.prototype.unregisterAction = function (action) {
  54181. var index = this.actions.indexOf(action);
  54182. if (index !== -1) {
  54183. this.actions.splice(index, 1);
  54184. ActionManager.Triggers[action.trigger] -= 1;
  54185. if (ActionManager.Triggers[action.trigger] === 0) {
  54186. delete ActionManager.Triggers[action.trigger];
  54187. }
  54188. delete action._actionManager;
  54189. return true;
  54190. }
  54191. return false;
  54192. };
  54193. /**
  54194. * Process a specific trigger
  54195. * @param trigger defines the trigger to process
  54196. * @param evt defines the event details to be processed
  54197. */
  54198. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54199. for (var index = 0; index < this.actions.length; index++) {
  54200. var action = this.actions[index];
  54201. if (action.trigger === trigger) {
  54202. if (evt) {
  54203. if (trigger === ActionManager.OnKeyUpTrigger
  54204. || trigger === ActionManager.OnKeyDownTrigger) {
  54205. var parameter = action.getTriggerParameter();
  54206. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54207. if (!parameter.toLowerCase) {
  54208. continue;
  54209. }
  54210. var lowerCase = parameter.toLowerCase();
  54211. if (lowerCase !== evt.sourceEvent.key) {
  54212. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54213. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54214. if (actualkey !== lowerCase) {
  54215. continue;
  54216. }
  54217. }
  54218. }
  54219. }
  54220. }
  54221. action._executeCurrent(evt);
  54222. }
  54223. }
  54224. };
  54225. /** @hidden */
  54226. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54227. var properties = propertyPath.split(".");
  54228. for (var index = 0; index < properties.length - 1; index++) {
  54229. target = target[properties[index]];
  54230. }
  54231. return target;
  54232. };
  54233. /** @hidden */
  54234. ActionManager.prototype._getProperty = function (propertyPath) {
  54235. var properties = propertyPath.split(".");
  54236. return properties[properties.length - 1];
  54237. };
  54238. /**
  54239. * Serialize this manager to a JSON object
  54240. * @param name defines the property name to store this manager
  54241. * @returns a JSON representation of this manager
  54242. */
  54243. ActionManager.prototype.serialize = function (name) {
  54244. var root = {
  54245. children: new Array(),
  54246. name: name,
  54247. type: 3,
  54248. properties: new Array() // Empty for root but required
  54249. };
  54250. for (var i = 0; i < this.actions.length; i++) {
  54251. var triggerObject = {
  54252. type: 0,
  54253. children: new Array(),
  54254. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54255. properties: new Array()
  54256. };
  54257. var triggerOptions = this.actions[i].triggerOptions;
  54258. if (triggerOptions && typeof triggerOptions !== "number") {
  54259. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54260. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54261. }
  54262. else {
  54263. var parameter = {};
  54264. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54265. if (triggerOptions.parameter.mesh) {
  54266. parameter._meshId = triggerOptions.parameter.mesh.id;
  54267. }
  54268. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54269. }
  54270. }
  54271. // Serialize child action, recursively
  54272. this.actions[i].serialize(triggerObject);
  54273. // Add serialized trigger
  54274. root.children.push(triggerObject);
  54275. }
  54276. return root;
  54277. };
  54278. /**
  54279. * Creates a new ActionManager from a JSON data
  54280. * @param parsedActions defines the JSON data to read from
  54281. * @param object defines the hosting mesh
  54282. * @param scene defines the hosting scene
  54283. */
  54284. ActionManager.Parse = function (parsedActions, object, scene) {
  54285. var actionManager = new ActionManager(scene);
  54286. if (object === null)
  54287. scene.actionManager = actionManager;
  54288. else
  54289. object.actionManager = actionManager;
  54290. // instanciate a new object
  54291. var instanciate = function (name, params) {
  54292. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54293. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54294. newInstance.constructor.apply(newInstance, params);
  54295. return newInstance;
  54296. };
  54297. var parseParameter = function (name, value, target, propertyPath) {
  54298. if (propertyPath === null) {
  54299. // String, boolean or float
  54300. var floatValue = parseFloat(value);
  54301. if (value === "true" || value === "false")
  54302. return value === "true";
  54303. else
  54304. return isNaN(floatValue) ? value : floatValue;
  54305. }
  54306. var effectiveTarget = propertyPath.split(".");
  54307. var values = value.split(",");
  54308. // Get effective Target
  54309. for (var i = 0; i < effectiveTarget.length; i++) {
  54310. target = target[effectiveTarget[i]];
  54311. }
  54312. // Return appropriate value with its type
  54313. if (typeof (target) === "boolean")
  54314. return values[0] === "true";
  54315. if (typeof (target) === "string")
  54316. return values[0];
  54317. // Parameters with multiple values such as Vector3 etc.
  54318. var split = new Array();
  54319. for (var i = 0; i < values.length; i++)
  54320. split.push(parseFloat(values[i]));
  54321. if (target instanceof BABYLON.Vector3)
  54322. return BABYLON.Vector3.FromArray(split);
  54323. if (target instanceof BABYLON.Vector4)
  54324. return BABYLON.Vector4.FromArray(split);
  54325. if (target instanceof BABYLON.Color3)
  54326. return BABYLON.Color3.FromArray(split);
  54327. if (target instanceof BABYLON.Color4)
  54328. return BABYLON.Color4.FromArray(split);
  54329. return parseFloat(values[0]);
  54330. };
  54331. // traverse graph per trigger
  54332. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54333. if (combineArray === void 0) { combineArray = null; }
  54334. if (parsedAction.detached)
  54335. return;
  54336. var parameters = new Array();
  54337. var target = null;
  54338. var propertyPath = null;
  54339. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54340. // Parameters
  54341. if (parsedAction.type === 2)
  54342. parameters.push(actionManager);
  54343. else
  54344. parameters.push(trigger);
  54345. if (combine) {
  54346. var actions = new Array();
  54347. for (var j = 0; j < parsedAction.combine.length; j++) {
  54348. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54349. }
  54350. parameters.push(actions);
  54351. }
  54352. else {
  54353. for (var i = 0; i < parsedAction.properties.length; i++) {
  54354. var value = parsedAction.properties[i].value;
  54355. var name = parsedAction.properties[i].name;
  54356. var targetType = parsedAction.properties[i].targetType;
  54357. if (name === "target")
  54358. if (targetType !== null && targetType === "SceneProperties")
  54359. value = target = scene;
  54360. else
  54361. value = target = scene.getNodeByName(value);
  54362. else if (name === "parent")
  54363. value = scene.getNodeByName(value);
  54364. else if (name === "sound") {
  54365. // Can not externalize to component, so only checks for the presence off the API.
  54366. if (scene.getSoundByName) {
  54367. value = scene.getSoundByName(value);
  54368. }
  54369. }
  54370. else if (name !== "propertyPath") {
  54371. if (parsedAction.type === 2 && name === "operator")
  54372. value = BABYLON.ValueCondition[value];
  54373. else
  54374. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54375. }
  54376. else {
  54377. propertyPath = value;
  54378. }
  54379. parameters.push(value);
  54380. }
  54381. }
  54382. if (combineArray === null) {
  54383. parameters.push(condition);
  54384. }
  54385. else {
  54386. parameters.push(null);
  54387. }
  54388. // If interpolate value action
  54389. if (parsedAction.name === "InterpolateValueAction") {
  54390. var param = parameters[parameters.length - 2];
  54391. parameters[parameters.length - 1] = param;
  54392. parameters[parameters.length - 2] = condition;
  54393. }
  54394. // Action or condition(s) and not CombineAction
  54395. var newAction = instanciate(parsedAction.name, parameters);
  54396. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54397. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54398. if (action)
  54399. action.then(nothing);
  54400. else
  54401. actionManager.registerAction(nothing);
  54402. action = nothing;
  54403. }
  54404. if (combineArray === null) {
  54405. if (newAction instanceof BABYLON.Condition) {
  54406. condition = newAction;
  54407. newAction = action;
  54408. }
  54409. else {
  54410. condition = null;
  54411. if (action)
  54412. action.then(newAction);
  54413. else
  54414. actionManager.registerAction(newAction);
  54415. }
  54416. }
  54417. else {
  54418. combineArray.push(newAction);
  54419. }
  54420. for (var i = 0; i < parsedAction.children.length; i++)
  54421. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54422. };
  54423. // triggers
  54424. for (var i = 0; i < parsedActions.children.length; i++) {
  54425. var triggerParams;
  54426. var trigger = parsedActions.children[i];
  54427. if (trigger.properties.length > 0) {
  54428. var param = trigger.properties[0].value;
  54429. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54430. if (value._meshId) {
  54431. value.mesh = scene.getMeshByID(value._meshId);
  54432. }
  54433. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54434. }
  54435. else
  54436. triggerParams = ActionManager[trigger.name];
  54437. for (var j = 0; j < trigger.children.length; j++) {
  54438. if (!trigger.detached)
  54439. traverse(trigger.children[j], triggerParams, null, null);
  54440. }
  54441. }
  54442. };
  54443. /**
  54444. * Get a trigger name by index
  54445. * @param trigger defines the trigger index
  54446. * @returns a trigger name
  54447. */
  54448. ActionManager.GetTriggerName = function (trigger) {
  54449. switch (trigger) {
  54450. case 0: return "NothingTrigger";
  54451. case 1: return "OnPickTrigger";
  54452. case 2: return "OnLeftPickTrigger";
  54453. case 3: return "OnRightPickTrigger";
  54454. case 4: return "OnCenterPickTrigger";
  54455. case 5: return "OnPickDownTrigger";
  54456. case 6: return "OnPickUpTrigger";
  54457. case 7: return "OnLongPressTrigger";
  54458. case 8: return "OnPointerOverTrigger";
  54459. case 9: return "OnPointerOutTrigger";
  54460. case 10: return "OnEveryFrameTrigger";
  54461. case 11: return "OnIntersectionEnterTrigger";
  54462. case 12: return "OnIntersectionExitTrigger";
  54463. case 13: return "OnKeyDownTrigger";
  54464. case 14: return "OnKeyUpTrigger";
  54465. case 15: return "OnPickOutTrigger";
  54466. default: return "";
  54467. }
  54468. };
  54469. /**
  54470. * Nothing
  54471. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54472. */
  54473. ActionManager.NothingTrigger = 0;
  54474. /**
  54475. * On pick
  54476. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54477. */
  54478. ActionManager.OnPickTrigger = 1;
  54479. /**
  54480. * On left pick
  54481. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54482. */
  54483. ActionManager.OnLeftPickTrigger = 2;
  54484. /**
  54485. * On right pick
  54486. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54487. */
  54488. ActionManager.OnRightPickTrigger = 3;
  54489. /**
  54490. * On center pick
  54491. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54492. */
  54493. ActionManager.OnCenterPickTrigger = 4;
  54494. /**
  54495. * On pick down
  54496. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54497. */
  54498. ActionManager.OnPickDownTrigger = 5;
  54499. /**
  54500. * On double pick
  54501. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54502. */
  54503. ActionManager.OnDoublePickTrigger = 6;
  54504. /**
  54505. * On pick up
  54506. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54507. */
  54508. ActionManager.OnPickUpTrigger = 7;
  54509. /**
  54510. * On pick out.
  54511. * This trigger will only be raised if you also declared a OnPickDown
  54512. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54513. */
  54514. ActionManager.OnPickOutTrigger = 16;
  54515. /**
  54516. * On long press
  54517. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54518. */
  54519. ActionManager.OnLongPressTrigger = 8;
  54520. /**
  54521. * On pointer over
  54522. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54523. */
  54524. ActionManager.OnPointerOverTrigger = 9;
  54525. /**
  54526. * On pointer out
  54527. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54528. */
  54529. ActionManager.OnPointerOutTrigger = 10;
  54530. /**
  54531. * On every frame
  54532. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54533. */
  54534. ActionManager.OnEveryFrameTrigger = 11;
  54535. /**
  54536. * On intersection enter
  54537. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54538. */
  54539. ActionManager.OnIntersectionEnterTrigger = 12;
  54540. /**
  54541. * On intersection exit
  54542. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54543. */
  54544. ActionManager.OnIntersectionExitTrigger = 13;
  54545. /**
  54546. * On key down
  54547. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54548. */
  54549. ActionManager.OnKeyDownTrigger = 14;
  54550. /**
  54551. * On key up
  54552. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54553. */
  54554. ActionManager.OnKeyUpTrigger = 15;
  54555. /** Gets the list of active triggers */
  54556. ActionManager.Triggers = {};
  54557. return ActionManager;
  54558. }());
  54559. BABYLON.ActionManager = ActionManager;
  54560. })(BABYLON || (BABYLON = {}));
  54561. //# sourceMappingURL=babylon.actionManager.js.map
  54562. var BABYLON;
  54563. (function (BABYLON) {
  54564. /**
  54565. * This defines an action responsible to change the value of a property
  54566. * by interpolating between its current value and the newly set one once triggered.
  54567. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54568. */
  54569. var InterpolateValueAction = /** @class */ (function (_super) {
  54570. __extends(InterpolateValueAction, _super);
  54571. /**
  54572. * Instantiate the action
  54573. * @param triggerOptions defines the trigger options
  54574. * @param target defines the object containing the value to interpolate
  54575. * @param propertyPath defines the path to the property in the target object
  54576. * @param value defines the target value at the end of the interpolation
  54577. * @param duration deines the time it will take for the property to interpolate to the value.
  54578. * @param condition defines the trigger related conditions
  54579. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  54580. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  54581. */
  54582. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54583. if (duration === void 0) { duration = 1000; }
  54584. var _this = _super.call(this, triggerOptions, condition) || this;
  54585. /**
  54586. * Defines the time it will take for the property to interpolate to the value.
  54587. */
  54588. _this.duration = 1000;
  54589. /**
  54590. * Observable triggered once the interpolation animation has been done.
  54591. */
  54592. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54593. _this.propertyPath = propertyPath;
  54594. _this.value = value;
  54595. _this.duration = duration;
  54596. _this.stopOtherAnimations = stopOtherAnimations;
  54597. _this.onInterpolationDone = onInterpolationDone;
  54598. _this._target = _this._effectiveTarget = target;
  54599. return _this;
  54600. }
  54601. /** @hidden */
  54602. InterpolateValueAction.prototype._prepare = function () {
  54603. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54604. this._property = this._getProperty(this.propertyPath);
  54605. };
  54606. /**
  54607. * Execute the action starts the value interpolation.
  54608. */
  54609. InterpolateValueAction.prototype.execute = function () {
  54610. var _this = this;
  54611. var scene = this._actionManager.getScene();
  54612. var keys = [
  54613. {
  54614. frame: 0,
  54615. value: this._effectiveTarget[this._property]
  54616. }, {
  54617. frame: 100,
  54618. value: this.value
  54619. }
  54620. ];
  54621. var dataType;
  54622. if (typeof this.value === "number") {
  54623. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54624. }
  54625. else if (this.value instanceof BABYLON.Color3) {
  54626. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54627. }
  54628. else if (this.value instanceof BABYLON.Vector3) {
  54629. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54630. }
  54631. else if (this.value instanceof BABYLON.Matrix) {
  54632. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54633. }
  54634. else if (this.value instanceof BABYLON.Quaternion) {
  54635. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54636. }
  54637. else {
  54638. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54639. return;
  54640. }
  54641. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54642. animation.setKeys(keys);
  54643. if (this.stopOtherAnimations) {
  54644. scene.stopAnimation(this._effectiveTarget);
  54645. }
  54646. var wrapper = function () {
  54647. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54648. if (_this.onInterpolationDone) {
  54649. _this.onInterpolationDone();
  54650. }
  54651. };
  54652. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54653. };
  54654. /**
  54655. * Serializes the actions and its related information.
  54656. * @param parent defines the object to serialize in
  54657. * @returns the serialized object
  54658. */
  54659. InterpolateValueAction.prototype.serialize = function (parent) {
  54660. return _super.prototype._serialize.call(this, {
  54661. name: "InterpolateValueAction",
  54662. properties: [
  54663. BABYLON.Action._GetTargetProperty(this._target),
  54664. { name: "propertyPath", value: this.propertyPath },
  54665. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54666. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54667. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54668. ]
  54669. }, parent);
  54670. };
  54671. return InterpolateValueAction;
  54672. }(BABYLON.Action));
  54673. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54674. })(BABYLON || (BABYLON = {}));
  54675. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54676. var BABYLON;
  54677. (function (BABYLON) {
  54678. /**
  54679. * This defines an action responsible to toggle a boolean once triggered.
  54680. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54681. */
  54682. var SwitchBooleanAction = /** @class */ (function (_super) {
  54683. __extends(SwitchBooleanAction, _super);
  54684. /**
  54685. * Instantiate the action
  54686. * @param triggerOptions defines the trigger options
  54687. * @param target defines the object containing the boolean
  54688. * @param propertyPath defines the path to the boolean property in the target object
  54689. * @param condition defines the trigger related conditions
  54690. */
  54691. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54692. var _this = _super.call(this, triggerOptions, condition) || this;
  54693. _this.propertyPath = propertyPath;
  54694. _this._target = _this._effectiveTarget = target;
  54695. return _this;
  54696. }
  54697. /** @hidden */
  54698. SwitchBooleanAction.prototype._prepare = function () {
  54699. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54700. this._property = this._getProperty(this.propertyPath);
  54701. };
  54702. /**
  54703. * Execute the action toggle the boolean value.
  54704. */
  54705. SwitchBooleanAction.prototype.execute = function () {
  54706. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54707. };
  54708. /**
  54709. * Serializes the actions and its related information.
  54710. * @param parent defines the object to serialize in
  54711. * @returns the serialized object
  54712. */
  54713. SwitchBooleanAction.prototype.serialize = function (parent) {
  54714. return _super.prototype._serialize.call(this, {
  54715. name: "SwitchBooleanAction",
  54716. properties: [
  54717. BABYLON.Action._GetTargetProperty(this._target),
  54718. { name: "propertyPath", value: this.propertyPath }
  54719. ]
  54720. }, parent);
  54721. };
  54722. return SwitchBooleanAction;
  54723. }(BABYLON.Action));
  54724. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54725. /**
  54726. * This defines an action responsible to set a the state field of the target
  54727. * to a desired value once triggered.
  54728. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54729. */
  54730. var SetStateAction = /** @class */ (function (_super) {
  54731. __extends(SetStateAction, _super);
  54732. /**
  54733. * Instantiate the action
  54734. * @param triggerOptions defines the trigger options
  54735. * @param target defines the object containing the state property
  54736. * @param value defines the value to store in the state field
  54737. * @param condition defines the trigger related conditions
  54738. */
  54739. function SetStateAction(triggerOptions, target, value, condition) {
  54740. var _this = _super.call(this, triggerOptions, condition) || this;
  54741. _this.value = value;
  54742. _this._target = target;
  54743. return _this;
  54744. }
  54745. /**
  54746. * Execute the action and store the value on the target state property.
  54747. */
  54748. SetStateAction.prototype.execute = function () {
  54749. this._target.state = this.value;
  54750. };
  54751. /**
  54752. * Serializes the actions and its related information.
  54753. * @param parent defines the object to serialize in
  54754. * @returns the serialized object
  54755. */
  54756. SetStateAction.prototype.serialize = function (parent) {
  54757. return _super.prototype._serialize.call(this, {
  54758. name: "SetStateAction",
  54759. properties: [
  54760. BABYLON.Action._GetTargetProperty(this._target),
  54761. { name: "value", value: this.value }
  54762. ]
  54763. }, parent);
  54764. };
  54765. return SetStateAction;
  54766. }(BABYLON.Action));
  54767. BABYLON.SetStateAction = SetStateAction;
  54768. /**
  54769. * This defines an action responsible to set a property of the target
  54770. * to a desired value once triggered.
  54771. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54772. */
  54773. var SetValueAction = /** @class */ (function (_super) {
  54774. __extends(SetValueAction, _super);
  54775. /**
  54776. * Instantiate the action
  54777. * @param triggerOptions defines the trigger options
  54778. * @param target defines the object containing the property
  54779. * @param propertyPath defines the path of the property to set in the target
  54780. * @param value defines the value to set in the property
  54781. * @param condition defines the trigger related conditions
  54782. */
  54783. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54784. var _this = _super.call(this, triggerOptions, condition) || this;
  54785. _this.propertyPath = propertyPath;
  54786. _this.value = value;
  54787. _this._target = _this._effectiveTarget = target;
  54788. return _this;
  54789. }
  54790. /** @hidden */
  54791. SetValueAction.prototype._prepare = function () {
  54792. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54793. this._property = this._getProperty(this.propertyPath);
  54794. };
  54795. /**
  54796. * Execute the action and set the targetted property to the desired value.
  54797. */
  54798. SetValueAction.prototype.execute = function () {
  54799. this._effectiveTarget[this._property] = this.value;
  54800. if (this._target.markAsDirty) {
  54801. this._target.markAsDirty(this._property);
  54802. }
  54803. };
  54804. /**
  54805. * Serializes the actions and its related information.
  54806. * @param parent defines the object to serialize in
  54807. * @returns the serialized object
  54808. */
  54809. SetValueAction.prototype.serialize = function (parent) {
  54810. return _super.prototype._serialize.call(this, {
  54811. name: "SetValueAction",
  54812. properties: [
  54813. BABYLON.Action._GetTargetProperty(this._target),
  54814. { name: "propertyPath", value: this.propertyPath },
  54815. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54816. ]
  54817. }, parent);
  54818. };
  54819. return SetValueAction;
  54820. }(BABYLON.Action));
  54821. BABYLON.SetValueAction = SetValueAction;
  54822. /**
  54823. * This defines an action responsible to increment the target value
  54824. * to a desired value once triggered.
  54825. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54826. */
  54827. var IncrementValueAction = /** @class */ (function (_super) {
  54828. __extends(IncrementValueAction, _super);
  54829. /**
  54830. * Instantiate the action
  54831. * @param triggerOptions defines the trigger options
  54832. * @param target defines the object containing the property
  54833. * @param propertyPath defines the path of the property to increment in the target
  54834. * @param value defines the value value we should increment the property by
  54835. * @param condition defines the trigger related conditions
  54836. */
  54837. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54838. var _this = _super.call(this, triggerOptions, condition) || this;
  54839. _this.propertyPath = propertyPath;
  54840. _this.value = value;
  54841. _this._target = _this._effectiveTarget = target;
  54842. return _this;
  54843. }
  54844. /** @hidden */
  54845. IncrementValueAction.prototype._prepare = function () {
  54846. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54847. this._property = this._getProperty(this.propertyPath);
  54848. if (typeof this._effectiveTarget[this._property] !== "number") {
  54849. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54850. }
  54851. };
  54852. /**
  54853. * Execute the action and increment the target of the value amount.
  54854. */
  54855. IncrementValueAction.prototype.execute = function () {
  54856. this._effectiveTarget[this._property] += this.value;
  54857. if (this._target.markAsDirty) {
  54858. this._target.markAsDirty(this._property);
  54859. }
  54860. };
  54861. /**
  54862. * Serializes the actions and its related information.
  54863. * @param parent defines the object to serialize in
  54864. * @returns the serialized object
  54865. */
  54866. IncrementValueAction.prototype.serialize = function (parent) {
  54867. return _super.prototype._serialize.call(this, {
  54868. name: "IncrementValueAction",
  54869. properties: [
  54870. BABYLON.Action._GetTargetProperty(this._target),
  54871. { name: "propertyPath", value: this.propertyPath },
  54872. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54873. ]
  54874. }, parent);
  54875. };
  54876. return IncrementValueAction;
  54877. }(BABYLON.Action));
  54878. BABYLON.IncrementValueAction = IncrementValueAction;
  54879. /**
  54880. * This defines an action responsible to start an animation once triggered.
  54881. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54882. */
  54883. var PlayAnimationAction = /** @class */ (function (_super) {
  54884. __extends(PlayAnimationAction, _super);
  54885. /**
  54886. * Instantiate the action
  54887. * @param triggerOptions defines the trigger options
  54888. * @param target defines the target animation or animation name
  54889. * @param from defines from where the animation should start (animation frame)
  54890. * @param end defines where the animation should stop (animation frame)
  54891. * @param loop defines if the animation should loop or stop after the first play
  54892. * @param condition defines the trigger related conditions
  54893. */
  54894. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54895. var _this = _super.call(this, triggerOptions, condition) || this;
  54896. _this.from = from;
  54897. _this.to = to;
  54898. _this.loop = loop;
  54899. _this._target = target;
  54900. return _this;
  54901. }
  54902. /** @hidden */
  54903. PlayAnimationAction.prototype._prepare = function () {
  54904. };
  54905. /**
  54906. * Execute the action and play the animation.
  54907. */
  54908. PlayAnimationAction.prototype.execute = function () {
  54909. var scene = this._actionManager.getScene();
  54910. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54911. };
  54912. /**
  54913. * Serializes the actions and its related information.
  54914. * @param parent defines the object to serialize in
  54915. * @returns the serialized object
  54916. */
  54917. PlayAnimationAction.prototype.serialize = function (parent) {
  54918. return _super.prototype._serialize.call(this, {
  54919. name: "PlayAnimationAction",
  54920. properties: [
  54921. BABYLON.Action._GetTargetProperty(this._target),
  54922. { name: "from", value: String(this.from) },
  54923. { name: "to", value: String(this.to) },
  54924. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54925. ]
  54926. }, parent);
  54927. };
  54928. return PlayAnimationAction;
  54929. }(BABYLON.Action));
  54930. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54931. /**
  54932. * This defines an action responsible to stop an animation once triggered.
  54933. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54934. */
  54935. var StopAnimationAction = /** @class */ (function (_super) {
  54936. __extends(StopAnimationAction, _super);
  54937. /**
  54938. * Instantiate the action
  54939. * @param triggerOptions defines the trigger options
  54940. * @param target defines the target animation or animation name
  54941. * @param condition defines the trigger related conditions
  54942. */
  54943. function StopAnimationAction(triggerOptions, target, condition) {
  54944. var _this = _super.call(this, triggerOptions, condition) || this;
  54945. _this._target = target;
  54946. return _this;
  54947. }
  54948. /** @hidden */
  54949. StopAnimationAction.prototype._prepare = function () {
  54950. };
  54951. /**
  54952. * Execute the action and stop the animation.
  54953. */
  54954. StopAnimationAction.prototype.execute = function () {
  54955. var scene = this._actionManager.getScene();
  54956. scene.stopAnimation(this._target);
  54957. };
  54958. /**
  54959. * Serializes the actions and its related information.
  54960. * @param parent defines the object to serialize in
  54961. * @returns the serialized object
  54962. */
  54963. StopAnimationAction.prototype.serialize = function (parent) {
  54964. return _super.prototype._serialize.call(this, {
  54965. name: "StopAnimationAction",
  54966. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54967. }, parent);
  54968. };
  54969. return StopAnimationAction;
  54970. }(BABYLON.Action));
  54971. BABYLON.StopAnimationAction = StopAnimationAction;
  54972. /**
  54973. * This defines an action responsible that does nothing once triggered.
  54974. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54975. */
  54976. var DoNothingAction = /** @class */ (function (_super) {
  54977. __extends(DoNothingAction, _super);
  54978. /**
  54979. * Instantiate the action
  54980. * @param triggerOptions defines the trigger options
  54981. * @param condition defines the trigger related conditions
  54982. */
  54983. function DoNothingAction(triggerOptions, condition) {
  54984. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54985. return _super.call(this, triggerOptions, condition) || this;
  54986. }
  54987. /**
  54988. * Execute the action and do nothing.
  54989. */
  54990. DoNothingAction.prototype.execute = function () {
  54991. };
  54992. /**
  54993. * Serializes the actions and its related information.
  54994. * @param parent defines the object to serialize in
  54995. * @returns the serialized object
  54996. */
  54997. DoNothingAction.prototype.serialize = function (parent) {
  54998. return _super.prototype._serialize.call(this, {
  54999. name: "DoNothingAction",
  55000. properties: []
  55001. }, parent);
  55002. };
  55003. return DoNothingAction;
  55004. }(BABYLON.Action));
  55005. BABYLON.DoNothingAction = DoNothingAction;
  55006. /**
  55007. * This defines an action responsible to trigger several actions once triggered.
  55008. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55009. */
  55010. var CombineAction = /** @class */ (function (_super) {
  55011. __extends(CombineAction, _super);
  55012. /**
  55013. * Instantiate the action
  55014. * @param triggerOptions defines the trigger options
  55015. * @param children defines the list of aggregated animations to run
  55016. * @param condition defines the trigger related conditions
  55017. */
  55018. function CombineAction(triggerOptions, children, condition) {
  55019. var _this = _super.call(this, triggerOptions, condition) || this;
  55020. _this.children = children;
  55021. return _this;
  55022. }
  55023. /** @hidden */
  55024. CombineAction.prototype._prepare = function () {
  55025. for (var index = 0; index < this.children.length; index++) {
  55026. this.children[index]._actionManager = this._actionManager;
  55027. this.children[index]._prepare();
  55028. }
  55029. };
  55030. /**
  55031. * Execute the action and executes all the aggregated actions.
  55032. */
  55033. CombineAction.prototype.execute = function (evt) {
  55034. for (var index = 0; index < this.children.length; index++) {
  55035. this.children[index].execute(evt);
  55036. }
  55037. };
  55038. /**
  55039. * Serializes the actions and its related information.
  55040. * @param parent defines the object to serialize in
  55041. * @returns the serialized object
  55042. */
  55043. CombineAction.prototype.serialize = function (parent) {
  55044. var serializationObject = _super.prototype._serialize.call(this, {
  55045. name: "CombineAction",
  55046. properties: [],
  55047. combine: []
  55048. }, parent);
  55049. for (var i = 0; i < this.children.length; i++) {
  55050. serializationObject.combine.push(this.children[i].serialize(null));
  55051. }
  55052. return serializationObject;
  55053. };
  55054. return CombineAction;
  55055. }(BABYLON.Action));
  55056. BABYLON.CombineAction = CombineAction;
  55057. /**
  55058. * This defines an action responsible to run code (external event) once triggered.
  55059. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55060. */
  55061. var ExecuteCodeAction = /** @class */ (function (_super) {
  55062. __extends(ExecuteCodeAction, _super);
  55063. /**
  55064. * Instantiate the action
  55065. * @param triggerOptions defines the trigger options
  55066. * @param func defines the callback function to run
  55067. * @param condition defines the trigger related conditions
  55068. */
  55069. function ExecuteCodeAction(triggerOptions, func, condition) {
  55070. var _this = _super.call(this, triggerOptions, condition) || this;
  55071. _this.func = func;
  55072. return _this;
  55073. }
  55074. /**
  55075. * Execute the action and run the attached code.
  55076. */
  55077. ExecuteCodeAction.prototype.execute = function (evt) {
  55078. this.func(evt);
  55079. };
  55080. return ExecuteCodeAction;
  55081. }(BABYLON.Action));
  55082. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  55083. /**
  55084. * This defines an action responsible to set the parent property of the target once triggered.
  55085. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55086. */
  55087. var SetParentAction = /** @class */ (function (_super) {
  55088. __extends(SetParentAction, _super);
  55089. /**
  55090. * Instantiate the action
  55091. * @param triggerOptions defines the trigger options
  55092. * @param target defines the target containing the parent property
  55093. * @param parent defines from where the animation should start (animation frame)
  55094. * @param condition defines the trigger related conditions
  55095. */
  55096. function SetParentAction(triggerOptions, target, parent, condition) {
  55097. var _this = _super.call(this, triggerOptions, condition) || this;
  55098. _this._target = target;
  55099. _this._parent = parent;
  55100. return _this;
  55101. }
  55102. /** @hidden */
  55103. SetParentAction.prototype._prepare = function () {
  55104. };
  55105. /**
  55106. * Execute the action and set the parent property.
  55107. */
  55108. SetParentAction.prototype.execute = function () {
  55109. if (this._target.parent === this._parent) {
  55110. return;
  55111. }
  55112. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  55113. invertParentWorldMatrix.invert();
  55114. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  55115. this._target.parent = this._parent;
  55116. };
  55117. /**
  55118. * Serializes the actions and its related information.
  55119. * @param parent defines the object to serialize in
  55120. * @returns the serialized object
  55121. */
  55122. SetParentAction.prototype.serialize = function (parent) {
  55123. return _super.prototype._serialize.call(this, {
  55124. name: "SetParentAction",
  55125. properties: [
  55126. BABYLON.Action._GetTargetProperty(this._target),
  55127. BABYLON.Action._GetTargetProperty(this._parent),
  55128. ]
  55129. }, parent);
  55130. };
  55131. return SetParentAction;
  55132. }(BABYLON.Action));
  55133. BABYLON.SetParentAction = SetParentAction;
  55134. })(BABYLON || (BABYLON = {}));
  55135. //# sourceMappingURL=babylon.directActions.js.map
  55136. var BABYLON;
  55137. (function (BABYLON) {
  55138. var SpriteManager = /** @class */ (function () {
  55139. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  55140. if (epsilon === void 0) { epsilon = 0.01; }
  55141. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55142. this.name = name;
  55143. this.sprites = new Array();
  55144. this.renderingGroupId = 0;
  55145. this.layerMask = 0x0FFFFFFF;
  55146. this.fogEnabled = true;
  55147. this.isPickable = false;
  55148. /**
  55149. * An event triggered when the manager is disposed.
  55150. */
  55151. this.onDisposeObservable = new BABYLON.Observable();
  55152. this._vertexBuffers = {};
  55153. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  55154. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  55155. }
  55156. this._capacity = capacity;
  55157. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  55158. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55159. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55160. if (cellSize.width && cellSize.height) {
  55161. this.cellWidth = cellSize.width;
  55162. this.cellHeight = cellSize.height;
  55163. }
  55164. else if (cellSize !== undefined) {
  55165. this.cellWidth = cellSize;
  55166. this.cellHeight = cellSize;
  55167. }
  55168. else {
  55169. return;
  55170. }
  55171. this._epsilon = epsilon;
  55172. this._scene = scene;
  55173. this._scene.spriteManagers.push(this);
  55174. var indices = [];
  55175. var index = 0;
  55176. for (var count = 0; count < capacity; count++) {
  55177. indices.push(index);
  55178. indices.push(index + 1);
  55179. indices.push(index + 2);
  55180. indices.push(index);
  55181. indices.push(index + 2);
  55182. indices.push(index + 3);
  55183. index += 4;
  55184. }
  55185. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  55186. // VBO
  55187. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  55188. this._vertexData = new Float32Array(capacity * 16 * 4);
  55189. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  55190. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  55191. var options = this._buffer.createVertexBuffer("options", 4, 4);
  55192. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  55193. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  55194. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55195. this._vertexBuffers["options"] = options;
  55196. this._vertexBuffers["cellInfo"] = cellInfo;
  55197. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55198. // Effects
  55199. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  55200. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  55201. }
  55202. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  55203. set: function (callback) {
  55204. if (this._onDisposeObserver) {
  55205. this.onDisposeObservable.remove(this._onDisposeObserver);
  55206. }
  55207. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55208. },
  55209. enumerable: true,
  55210. configurable: true
  55211. });
  55212. Object.defineProperty(SpriteManager.prototype, "texture", {
  55213. get: function () {
  55214. return this._spriteTexture;
  55215. },
  55216. set: function (value) {
  55217. this._spriteTexture = value;
  55218. },
  55219. enumerable: true,
  55220. configurable: true
  55221. });
  55222. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  55223. var arrayOffset = index * 16;
  55224. if (offsetX === 0)
  55225. offsetX = this._epsilon;
  55226. else if (offsetX === 1)
  55227. offsetX = 1 - this._epsilon;
  55228. if (offsetY === 0)
  55229. offsetY = this._epsilon;
  55230. else if (offsetY === 1)
  55231. offsetY = 1 - this._epsilon;
  55232. this._vertexData[arrayOffset] = sprite.position.x;
  55233. this._vertexData[arrayOffset + 1] = sprite.position.y;
  55234. this._vertexData[arrayOffset + 2] = sprite.position.z;
  55235. this._vertexData[arrayOffset + 3] = sprite.angle;
  55236. this._vertexData[arrayOffset + 4] = sprite.width;
  55237. this._vertexData[arrayOffset + 5] = sprite.height;
  55238. this._vertexData[arrayOffset + 6] = offsetX;
  55239. this._vertexData[arrayOffset + 7] = offsetY;
  55240. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  55241. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  55242. var offset = (sprite.cellIndex / rowSize) >> 0;
  55243. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  55244. this._vertexData[arrayOffset + 11] = offset;
  55245. // Color
  55246. this._vertexData[arrayOffset + 12] = sprite.color.r;
  55247. this._vertexData[arrayOffset + 13] = sprite.color.g;
  55248. this._vertexData[arrayOffset + 14] = sprite.color.b;
  55249. this._vertexData[arrayOffset + 15] = sprite.color.a;
  55250. };
  55251. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  55252. var count = Math.min(this._capacity, this.sprites.length);
  55253. var min = BABYLON.Vector3.Zero();
  55254. var max = BABYLON.Vector3.Zero();
  55255. var distance = Number.MAX_VALUE;
  55256. var currentSprite = null;
  55257. var cameraSpacePosition = BABYLON.Vector3.Zero();
  55258. var cameraView = camera.getViewMatrix();
  55259. for (var index = 0; index < count; index++) {
  55260. var sprite = this.sprites[index];
  55261. if (!sprite) {
  55262. continue;
  55263. }
  55264. if (predicate) {
  55265. if (!predicate(sprite)) {
  55266. continue;
  55267. }
  55268. }
  55269. else if (!sprite.isPickable) {
  55270. continue;
  55271. }
  55272. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  55273. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  55274. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  55275. if (ray.intersectsBoxMinMax(min, max)) {
  55276. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  55277. if (distance > currentDistance) {
  55278. distance = currentDistance;
  55279. currentSprite = sprite;
  55280. if (fastCheck) {
  55281. break;
  55282. }
  55283. }
  55284. }
  55285. }
  55286. if (currentSprite) {
  55287. var result = new BABYLON.PickingInfo();
  55288. result.hit = true;
  55289. result.pickedSprite = currentSprite;
  55290. result.distance = distance;
  55291. return result;
  55292. }
  55293. return null;
  55294. };
  55295. SpriteManager.prototype.render = function () {
  55296. // Check
  55297. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  55298. return;
  55299. var engine = this._scene.getEngine();
  55300. var baseSize = this._spriteTexture.getBaseSize();
  55301. // Sprites
  55302. var deltaTime = engine.getDeltaTime();
  55303. var max = Math.min(this._capacity, this.sprites.length);
  55304. var rowSize = baseSize.width / this.cellWidth;
  55305. var offset = 0;
  55306. for (var index = 0; index < max; index++) {
  55307. var sprite = this.sprites[index];
  55308. if (!sprite || !sprite.isVisible) {
  55309. continue;
  55310. }
  55311. sprite._animate(deltaTime);
  55312. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  55313. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  55314. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  55315. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  55316. }
  55317. this._buffer.update(this._vertexData);
  55318. // Render
  55319. var effect = this._effectBase;
  55320. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55321. effect = this._effectFog;
  55322. }
  55323. engine.enableEffect(effect);
  55324. var viewMatrix = this._scene.getViewMatrix();
  55325. effect.setTexture("diffuseSampler", this._spriteTexture);
  55326. effect.setMatrix("view", viewMatrix);
  55327. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55328. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  55329. // Fog
  55330. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55331. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  55332. effect.setColor3("vFogColor", this._scene.fogColor);
  55333. }
  55334. // VBOs
  55335. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55336. // Draw order
  55337. engine.setDepthFunctionToLessOrEqual();
  55338. effect.setBool("alphaTest", true);
  55339. engine.setColorWrite(false);
  55340. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55341. engine.setColorWrite(true);
  55342. effect.setBool("alphaTest", false);
  55343. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55344. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55345. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55346. };
  55347. SpriteManager.prototype.dispose = function () {
  55348. if (this._buffer) {
  55349. this._buffer.dispose();
  55350. this._buffer = null;
  55351. }
  55352. if (this._indexBuffer) {
  55353. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55354. this._indexBuffer = null;
  55355. }
  55356. if (this._spriteTexture) {
  55357. this._spriteTexture.dispose();
  55358. this._spriteTexture = null;
  55359. }
  55360. // Remove from scene
  55361. var index = this._scene.spriteManagers.indexOf(this);
  55362. this._scene.spriteManagers.splice(index, 1);
  55363. // Callback
  55364. this.onDisposeObservable.notifyObservers(this);
  55365. this.onDisposeObservable.clear();
  55366. };
  55367. return SpriteManager;
  55368. }());
  55369. BABYLON.SpriteManager = SpriteManager;
  55370. })(BABYLON || (BABYLON = {}));
  55371. //# sourceMappingURL=babylon.spriteManager.js.map
  55372. var BABYLON;
  55373. (function (BABYLON) {
  55374. var Sprite = /** @class */ (function () {
  55375. function Sprite(name, manager) {
  55376. this.name = name;
  55377. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55378. this.width = 1.0;
  55379. this.height = 1.0;
  55380. this.angle = 0;
  55381. this.cellIndex = 0;
  55382. this.invertU = 0;
  55383. this.invertV = 0;
  55384. this.animations = new Array();
  55385. this.isPickable = false;
  55386. this._animationStarted = false;
  55387. this._loopAnimation = false;
  55388. this._fromIndex = 0;
  55389. this._toIndex = 0;
  55390. this._delay = 0;
  55391. this._direction = 1;
  55392. this._time = 0;
  55393. /**
  55394. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  55395. */
  55396. this.isVisible = true;
  55397. this._manager = manager;
  55398. this._manager.sprites.push(this);
  55399. this.position = BABYLON.Vector3.Zero();
  55400. }
  55401. Object.defineProperty(Sprite.prototype, "size", {
  55402. get: function () {
  55403. return this.width;
  55404. },
  55405. set: function (value) {
  55406. this.width = value;
  55407. this.height = value;
  55408. },
  55409. enumerable: true,
  55410. configurable: true
  55411. });
  55412. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55413. this._fromIndex = from;
  55414. this._toIndex = to;
  55415. this._loopAnimation = loop;
  55416. this._delay = delay;
  55417. this._animationStarted = true;
  55418. this._direction = from < to ? 1 : -1;
  55419. this.cellIndex = from;
  55420. this._time = 0;
  55421. this._onAnimationEnd = onAnimationEnd;
  55422. };
  55423. Sprite.prototype.stopAnimation = function () {
  55424. this._animationStarted = false;
  55425. };
  55426. /** @hidden */
  55427. Sprite.prototype._animate = function (deltaTime) {
  55428. if (!this._animationStarted)
  55429. return;
  55430. this._time += deltaTime;
  55431. if (this._time > this._delay) {
  55432. this._time = this._time % this._delay;
  55433. this.cellIndex += this._direction;
  55434. if (this.cellIndex > this._toIndex) {
  55435. if (this._loopAnimation) {
  55436. this.cellIndex = this._fromIndex;
  55437. }
  55438. else {
  55439. this.cellIndex = this._toIndex;
  55440. this._animationStarted = false;
  55441. if (this._onAnimationEnd) {
  55442. this._onAnimationEnd();
  55443. }
  55444. if (this.disposeWhenFinishedAnimating) {
  55445. this.dispose();
  55446. }
  55447. }
  55448. }
  55449. }
  55450. };
  55451. Sprite.prototype.dispose = function () {
  55452. for (var i = 0; i < this._manager.sprites.length; i++) {
  55453. if (this._manager.sprites[i] == this) {
  55454. this._manager.sprites.splice(i, 1);
  55455. }
  55456. }
  55457. };
  55458. return Sprite;
  55459. }());
  55460. BABYLON.Sprite = Sprite;
  55461. })(BABYLON || (BABYLON = {}));
  55462. //# sourceMappingURL=babylon.sprite.js.map
  55463. var BABYLON;
  55464. (function (BABYLON) {
  55465. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  55466. if (!BABYLON.PickingInfo) {
  55467. return null;
  55468. }
  55469. var pickingInfo = null;
  55470. if (!camera) {
  55471. if (!this.activeCamera) {
  55472. return null;
  55473. }
  55474. camera = this.activeCamera;
  55475. }
  55476. if (this.spriteManagers.length > 0) {
  55477. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55478. var spriteManager = this.spriteManagers[spriteIndex];
  55479. if (!spriteManager.isPickable) {
  55480. continue;
  55481. }
  55482. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55483. if (!result || !result.hit)
  55484. continue;
  55485. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55486. continue;
  55487. pickingInfo = result;
  55488. if (fastCheck) {
  55489. break;
  55490. }
  55491. }
  55492. }
  55493. return pickingInfo || new BABYLON.PickingInfo();
  55494. };
  55495. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55496. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55497. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55498. };
  55499. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55500. if (!this._tempSpritePickingRay) {
  55501. return null;
  55502. }
  55503. if (!camera) {
  55504. if (!this.activeCamera) {
  55505. return null;
  55506. }
  55507. camera = this.activeCamera;
  55508. }
  55509. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55510. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55511. };
  55512. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55513. if (this._pointerOverSprite === sprite) {
  55514. return;
  55515. }
  55516. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55517. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55518. }
  55519. this._pointerOverSprite = sprite;
  55520. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55521. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55522. }
  55523. };
  55524. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55525. return this._pointerOverSprite;
  55526. };
  55527. /**
  55528. * Defines the sprite scene component responsible to manage sprites
  55529. * in a given scene.
  55530. */
  55531. var SpriteSceneComponent = /** @class */ (function () {
  55532. /**
  55533. * Creates a new instance of the component for the given scene
  55534. * @param scene Defines the scene to register the component in
  55535. */
  55536. function SpriteSceneComponent(scene) {
  55537. /**
  55538. * The component name helpfull to identify the component in the list of scene components.
  55539. */
  55540. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  55541. this.scene = scene;
  55542. this.scene.spriteManagers = new Array();
  55543. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  55544. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  55545. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  55546. this._spritePredicate = function (sprite) {
  55547. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  55548. };
  55549. }
  55550. /**
  55551. * Registers the component in a given scene
  55552. */
  55553. SpriteSceneComponent.prototype.register = function () {
  55554. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  55555. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  55556. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  55557. };
  55558. /**
  55559. * Rebuilds the elements related to this component in case of
  55560. * context lost for instance.
  55561. */
  55562. SpriteSceneComponent.prototype.rebuild = function () {
  55563. /** Nothing to do for sprites */
  55564. };
  55565. /**
  55566. * Disposes the component and the associated ressources.
  55567. */
  55568. SpriteSceneComponent.prototype.dispose = function () {
  55569. this.scene.onBeforeSpritesRenderingObservable.clear();
  55570. this.scene.onAfterSpritesRenderingObservable.clear();
  55571. var spriteManagers = this.scene.spriteManagers;
  55572. while (spriteManagers.length) {
  55573. spriteManagers[0].dispose();
  55574. }
  55575. };
  55576. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  55577. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  55578. if (result) {
  55579. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  55580. }
  55581. return result;
  55582. };
  55583. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  55584. var scene = this.scene;
  55585. if (isMeshPicked) {
  55586. scene.setPointerOverSprite(null);
  55587. }
  55588. else {
  55589. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  55590. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55591. scene.setPointerOverSprite(pickResult.pickedSprite);
  55592. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  55593. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  55594. }
  55595. else {
  55596. canvas.style.cursor = scene.hoverCursor;
  55597. }
  55598. }
  55599. else {
  55600. scene.setPointerOverSprite(null);
  55601. }
  55602. }
  55603. return pickResult;
  55604. };
  55605. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55606. var scene = this.scene;
  55607. scene._pickedDownSprite = null;
  55608. if (scene.spriteManagers.length > 0) {
  55609. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55610. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55611. if (pickResult.pickedSprite.actionManager) {
  55612. scene._pickedDownSprite = pickResult.pickedSprite;
  55613. switch (evt.button) {
  55614. case 0:
  55615. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55616. break;
  55617. case 1:
  55618. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55619. break;
  55620. case 2:
  55621. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55622. break;
  55623. }
  55624. if (pickResult.pickedSprite.actionManager) {
  55625. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55626. }
  55627. }
  55628. }
  55629. }
  55630. return pickResult;
  55631. };
  55632. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55633. var scene = this.scene;
  55634. if (scene.spriteManagers.length > 0) {
  55635. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55636. if (spritePickResult) {
  55637. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  55638. if (spritePickResult.pickedSprite.actionManager) {
  55639. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55640. if (spritePickResult.pickedSprite.actionManager) {
  55641. if (!this.scene._isPointerSwiping()) {
  55642. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55643. }
  55644. }
  55645. }
  55646. }
  55647. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  55648. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  55649. }
  55650. }
  55651. }
  55652. return pickResult;
  55653. };
  55654. return SpriteSceneComponent;
  55655. }());
  55656. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  55657. })(BABYLON || (BABYLON = {}));
  55658. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  55659. var BABYLON;
  55660. (function (BABYLON) {
  55661. /**
  55662. * @hidden
  55663. */
  55664. var IntersectionInfo = /** @class */ (function () {
  55665. function IntersectionInfo(bu, bv, distance) {
  55666. this.bu = bu;
  55667. this.bv = bv;
  55668. this.distance = distance;
  55669. this.faceId = 0;
  55670. this.subMeshId = 0;
  55671. }
  55672. return IntersectionInfo;
  55673. }());
  55674. BABYLON.IntersectionInfo = IntersectionInfo;
  55675. /**
  55676. * Information about the result of picking within a scene
  55677. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  55678. */
  55679. var PickingInfo = /** @class */ (function () {
  55680. function PickingInfo() {
  55681. /**
  55682. * If the pick collided with an object
  55683. */
  55684. this.hit = false;
  55685. /**
  55686. * Distance away where the pick collided
  55687. */
  55688. this.distance = 0;
  55689. /**
  55690. * The location of pick collision
  55691. */
  55692. this.pickedPoint = null;
  55693. /**
  55694. * The mesh corresponding the the pick collision
  55695. */
  55696. this.pickedMesh = null;
  55697. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55698. this.bu = 0;
  55699. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55700. this.bv = 0;
  55701. /** The id of the face on the mesh that was picked */
  55702. this.faceId = -1;
  55703. /** Id of the the submesh that was picked */
  55704. this.subMeshId = 0;
  55705. /** If a sprite was picked, this will be the sprite the pick collided with */
  55706. this.pickedSprite = null;
  55707. /**
  55708. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55709. */
  55710. this.originMesh = null;
  55711. /**
  55712. * The ray that was used to perform the picking.
  55713. */
  55714. this.ray = null;
  55715. }
  55716. /**
  55717. * Gets the normal correspodning to the face the pick collided with
  55718. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55719. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55720. * @returns The normal correspodning to the face the pick collided with
  55721. */
  55722. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55723. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55724. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55725. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55726. return null;
  55727. }
  55728. var indices = this.pickedMesh.getIndices();
  55729. if (!indices) {
  55730. return null;
  55731. }
  55732. var result;
  55733. if (useVerticesNormals) {
  55734. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55735. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55736. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55737. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55738. normal0 = normal0.scale(this.bu);
  55739. normal1 = normal1.scale(this.bv);
  55740. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55741. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55742. }
  55743. else {
  55744. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55745. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55746. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55747. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55748. var p1p2 = vertex1.subtract(vertex2);
  55749. var p3p2 = vertex3.subtract(vertex2);
  55750. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55751. }
  55752. if (useWorldCoordinates) {
  55753. var wm = this.pickedMesh.getWorldMatrix();
  55754. if (this.pickedMesh.nonUniformScaling) {
  55755. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  55756. wm = BABYLON.Tmp.Matrix[0];
  55757. wm.setTranslationFromFloats(0, 0, 0);
  55758. wm.invert();
  55759. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  55760. wm = BABYLON.Tmp.Matrix[1];
  55761. }
  55762. result = BABYLON.Vector3.TransformNormal(result, wm);
  55763. }
  55764. result.normalize();
  55765. return result;
  55766. };
  55767. /**
  55768. * Gets the texture coordinates of where the pick occured
  55769. * @returns the vector containing the coordnates of the texture
  55770. */
  55771. PickingInfo.prototype.getTextureCoordinates = function () {
  55772. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55773. return null;
  55774. }
  55775. var indices = this.pickedMesh.getIndices();
  55776. if (!indices) {
  55777. return null;
  55778. }
  55779. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55780. if (!uvs) {
  55781. return null;
  55782. }
  55783. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55784. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55785. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55786. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55787. uv1 = uv1.scale(this.bu);
  55788. uv2 = uv2.scale(this.bv);
  55789. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55790. };
  55791. return PickingInfo;
  55792. }());
  55793. BABYLON.PickingInfo = PickingInfo;
  55794. })(BABYLON || (BABYLON = {}));
  55795. //# sourceMappingURL=babylon.pickingInfo.js.map
  55796. var BABYLON;
  55797. (function (BABYLON) {
  55798. var Ray = /** @class */ (function () {
  55799. function Ray(origin, direction, length) {
  55800. if (length === void 0) { length = Number.MAX_VALUE; }
  55801. this.origin = origin;
  55802. this.direction = direction;
  55803. this.length = length;
  55804. }
  55805. // Methods
  55806. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55807. var d = 0.0;
  55808. var maxValue = Number.MAX_VALUE;
  55809. var inv;
  55810. var min;
  55811. var max;
  55812. var temp;
  55813. if (Math.abs(this.direction.x) < 0.0000001) {
  55814. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55815. return false;
  55816. }
  55817. }
  55818. else {
  55819. inv = 1.0 / this.direction.x;
  55820. min = (minimum.x - this.origin.x) * inv;
  55821. max = (maximum.x - this.origin.x) * inv;
  55822. if (max === -Infinity) {
  55823. max = Infinity;
  55824. }
  55825. if (min > max) {
  55826. temp = min;
  55827. min = max;
  55828. max = temp;
  55829. }
  55830. d = Math.max(min, d);
  55831. maxValue = Math.min(max, maxValue);
  55832. if (d > maxValue) {
  55833. return false;
  55834. }
  55835. }
  55836. if (Math.abs(this.direction.y) < 0.0000001) {
  55837. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55838. return false;
  55839. }
  55840. }
  55841. else {
  55842. inv = 1.0 / this.direction.y;
  55843. min = (minimum.y - this.origin.y) * inv;
  55844. max = (maximum.y - this.origin.y) * inv;
  55845. if (max === -Infinity) {
  55846. max = Infinity;
  55847. }
  55848. if (min > max) {
  55849. temp = min;
  55850. min = max;
  55851. max = temp;
  55852. }
  55853. d = Math.max(min, d);
  55854. maxValue = Math.min(max, maxValue);
  55855. if (d > maxValue) {
  55856. return false;
  55857. }
  55858. }
  55859. if (Math.abs(this.direction.z) < 0.0000001) {
  55860. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55861. return false;
  55862. }
  55863. }
  55864. else {
  55865. inv = 1.0 / this.direction.z;
  55866. min = (minimum.z - this.origin.z) * inv;
  55867. max = (maximum.z - this.origin.z) * inv;
  55868. if (max === -Infinity) {
  55869. max = Infinity;
  55870. }
  55871. if (min > max) {
  55872. temp = min;
  55873. min = max;
  55874. max = temp;
  55875. }
  55876. d = Math.max(min, d);
  55877. maxValue = Math.min(max, maxValue);
  55878. if (d > maxValue) {
  55879. return false;
  55880. }
  55881. }
  55882. return true;
  55883. };
  55884. Ray.prototype.intersectsBox = function (box) {
  55885. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55886. };
  55887. Ray.prototype.intersectsSphere = function (sphere) {
  55888. var x = sphere.center.x - this.origin.x;
  55889. var y = sphere.center.y - this.origin.y;
  55890. var z = sphere.center.z - this.origin.z;
  55891. var pyth = (x * x) + (y * y) + (z * z);
  55892. var rr = sphere.radius * sphere.radius;
  55893. if (pyth <= rr) {
  55894. return true;
  55895. }
  55896. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55897. if (dot < 0.0) {
  55898. return false;
  55899. }
  55900. var temp = pyth - (dot * dot);
  55901. return temp <= rr;
  55902. };
  55903. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55904. if (!this._edge1) {
  55905. this._edge1 = BABYLON.Vector3.Zero();
  55906. this._edge2 = BABYLON.Vector3.Zero();
  55907. this._pvec = BABYLON.Vector3.Zero();
  55908. this._tvec = BABYLON.Vector3.Zero();
  55909. this._qvec = BABYLON.Vector3.Zero();
  55910. }
  55911. vertex1.subtractToRef(vertex0, this._edge1);
  55912. vertex2.subtractToRef(vertex0, this._edge2);
  55913. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55914. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55915. if (det === 0) {
  55916. return null;
  55917. }
  55918. var invdet = 1 / det;
  55919. this.origin.subtractToRef(vertex0, this._tvec);
  55920. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55921. if (bu < 0 || bu > 1.0) {
  55922. return null;
  55923. }
  55924. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55925. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55926. if (bv < 0 || bu + bv > 1.0) {
  55927. return null;
  55928. }
  55929. //check if the distance is longer than the predefined length.
  55930. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55931. if (distance > this.length) {
  55932. return null;
  55933. }
  55934. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55935. };
  55936. Ray.prototype.intersectsPlane = function (plane) {
  55937. var distance;
  55938. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55939. if (Math.abs(result1) < 9.99999997475243E-07) {
  55940. return null;
  55941. }
  55942. else {
  55943. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55944. distance = (-plane.d - result2) / result1;
  55945. if (distance < 0.0) {
  55946. if (distance < -9.99999997475243E-07) {
  55947. return null;
  55948. }
  55949. else {
  55950. return 0;
  55951. }
  55952. }
  55953. return distance;
  55954. }
  55955. };
  55956. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55957. var tm = BABYLON.Tmp.Matrix[0];
  55958. mesh.getWorldMatrix().invertToRef(tm);
  55959. if (this._tmpRay) {
  55960. Ray.TransformToRef(this, tm, this._tmpRay);
  55961. }
  55962. else {
  55963. this._tmpRay = Ray.Transform(this, tm);
  55964. }
  55965. return mesh.intersects(this._tmpRay, fastCheck);
  55966. };
  55967. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55968. if (results) {
  55969. results.length = 0;
  55970. }
  55971. else {
  55972. results = [];
  55973. }
  55974. for (var i = 0; i < meshes.length; i++) {
  55975. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55976. if (pickInfo.hit) {
  55977. results.push(pickInfo);
  55978. }
  55979. }
  55980. results.sort(this._comparePickingInfo);
  55981. return results;
  55982. };
  55983. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55984. if (pickingInfoA.distance < pickingInfoB.distance) {
  55985. return -1;
  55986. }
  55987. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55988. return 1;
  55989. }
  55990. else {
  55991. return 0;
  55992. }
  55993. };
  55994. /**
  55995. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55996. * @param sega the first point of the segment to test the intersection against
  55997. * @param segb the second point of the segment to test the intersection against
  55998. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55999. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  56000. */
  56001. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  56002. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  56003. var u = segb.subtract(sega);
  56004. var v = rsegb.subtract(this.origin);
  56005. var w = sega.subtract(this.origin);
  56006. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  56007. var b = BABYLON.Vector3.Dot(u, v);
  56008. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  56009. var d = BABYLON.Vector3.Dot(u, w);
  56010. var e = BABYLON.Vector3.Dot(v, w);
  56011. var D = a * c - b * b; // always >= 0
  56012. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  56013. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  56014. // compute the line parameters of the two closest points
  56015. if (D < Ray.smallnum) { // the lines are almost parallel
  56016. sN = 0.0; // force using point P0 on segment S1
  56017. sD = 1.0; // to prevent possible division by 0.0 later
  56018. tN = e;
  56019. tD = c;
  56020. }
  56021. else { // get the closest points on the infinite lines
  56022. sN = (b * e - c * d);
  56023. tN = (a * e - b * d);
  56024. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  56025. sN = 0.0;
  56026. tN = e;
  56027. tD = c;
  56028. }
  56029. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  56030. sN = sD;
  56031. tN = e + b;
  56032. tD = c;
  56033. }
  56034. }
  56035. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  56036. tN = 0.0;
  56037. // recompute sc for this edge
  56038. if (-d < 0.0) {
  56039. sN = 0.0;
  56040. }
  56041. else if (-d > a)
  56042. sN = sD;
  56043. else {
  56044. sN = -d;
  56045. sD = a;
  56046. }
  56047. }
  56048. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  56049. tN = tD;
  56050. // recompute sc for this edge
  56051. if ((-d + b) < 0.0) {
  56052. sN = 0;
  56053. }
  56054. else if ((-d + b) > a) {
  56055. sN = sD;
  56056. }
  56057. else {
  56058. sN = (-d + b);
  56059. sD = a;
  56060. }
  56061. }
  56062. // finally do the division to get sc and tc
  56063. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  56064. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  56065. // get the difference of the two closest points
  56066. var qtc = v.multiplyByFloats(tc, tc, tc);
  56067. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  56068. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  56069. if (isIntersected) {
  56070. return qtc.length();
  56071. }
  56072. return -1;
  56073. };
  56074. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56075. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  56076. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  56077. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  56078. this.direction.normalize();
  56079. return this;
  56080. };
  56081. // Statics
  56082. Ray.Zero = function () {
  56083. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  56084. };
  56085. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56086. var result = Ray.Zero();
  56087. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  56088. };
  56089. /**
  56090. * 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
  56091. * transformed to the given world matrix.
  56092. * @param origin The origin point
  56093. * @param end The end point
  56094. * @param world a matrix to transform the ray to. Default is the identity matrix.
  56095. */
  56096. Ray.CreateNewFromTo = function (origin, end, world) {
  56097. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  56098. var direction = end.subtract(origin);
  56099. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  56100. direction.normalize();
  56101. return Ray.Transform(new Ray(origin, direction, length), world);
  56102. };
  56103. Ray.Transform = function (ray, matrix) {
  56104. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  56105. Ray.TransformToRef(ray, matrix, result);
  56106. return result;
  56107. };
  56108. Ray.TransformToRef = function (ray, matrix, result) {
  56109. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  56110. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  56111. result.length = ray.length;
  56112. var dir = result.direction;
  56113. var len = dir.length();
  56114. if (!(len === 0 || len === 1)) {
  56115. var num = 1.0 / len;
  56116. dir.x *= num;
  56117. dir.y *= num;
  56118. dir.z *= num;
  56119. result.length *= len;
  56120. }
  56121. };
  56122. Ray.smallnum = 0.00000001;
  56123. Ray.rayl = 10e8;
  56124. return Ray;
  56125. }());
  56126. BABYLON.Ray = Ray;
  56127. })(BABYLON || (BABYLON = {}));
  56128. //# sourceMappingURL=babylon.ray.js.map
  56129. var BABYLON;
  56130. (function (BABYLON) {
  56131. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  56132. if (boxMin.x > sphereCenter.x + sphereRadius)
  56133. return false;
  56134. if (sphereCenter.x - sphereRadius > boxMax.x)
  56135. return false;
  56136. if (boxMin.y > sphereCenter.y + sphereRadius)
  56137. return false;
  56138. if (sphereCenter.y - sphereRadius > boxMax.y)
  56139. return false;
  56140. if (boxMin.z > sphereCenter.z + sphereRadius)
  56141. return false;
  56142. if (sphereCenter.z - sphereRadius > boxMax.z)
  56143. return false;
  56144. return true;
  56145. };
  56146. var getLowestRoot = (function () {
  56147. var result = { root: 0, found: false };
  56148. return function (a, b, c, maxR) {
  56149. result.root = 0;
  56150. result.found = false;
  56151. var determinant = b * b - 4.0 * a * c;
  56152. if (determinant < 0)
  56153. return result;
  56154. var sqrtD = Math.sqrt(determinant);
  56155. var r1 = (-b - sqrtD) / (2.0 * a);
  56156. var r2 = (-b + sqrtD) / (2.0 * a);
  56157. if (r1 > r2) {
  56158. var temp = r2;
  56159. r2 = r1;
  56160. r1 = temp;
  56161. }
  56162. if (r1 > 0 && r1 < maxR) {
  56163. result.root = r1;
  56164. result.found = true;
  56165. return result;
  56166. }
  56167. if (r2 > 0 && r2 < maxR) {
  56168. result.root = r2;
  56169. result.found = true;
  56170. return result;
  56171. }
  56172. return result;
  56173. };
  56174. })();
  56175. /** @hidden */
  56176. var Collider = /** @class */ (function () {
  56177. function Collider() {
  56178. this._collisionPoint = BABYLON.Vector3.Zero();
  56179. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  56180. this._tempVector = BABYLON.Vector3.Zero();
  56181. this._tempVector2 = BABYLON.Vector3.Zero();
  56182. this._tempVector3 = BABYLON.Vector3.Zero();
  56183. this._tempVector4 = BABYLON.Vector3.Zero();
  56184. this._edge = BABYLON.Vector3.Zero();
  56185. this._baseToVertex = BABYLON.Vector3.Zero();
  56186. this._destinationPoint = BABYLON.Vector3.Zero();
  56187. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  56188. this._displacementVector = BABYLON.Vector3.Zero();
  56189. /** @hidden */
  56190. this._radius = BABYLON.Vector3.One();
  56191. /** @hidden */
  56192. this._retry = 0;
  56193. /** @hidden */
  56194. this._basePointWorld = BABYLON.Vector3.Zero();
  56195. this._velocityWorld = BABYLON.Vector3.Zero();
  56196. this._normalizedVelocity = BABYLON.Vector3.Zero();
  56197. this._collisionMask = -1;
  56198. }
  56199. Object.defineProperty(Collider.prototype, "collisionMask", {
  56200. get: function () {
  56201. return this._collisionMask;
  56202. },
  56203. set: function (mask) {
  56204. this._collisionMask = !isNaN(mask) ? mask : -1;
  56205. },
  56206. enumerable: true,
  56207. configurable: true
  56208. });
  56209. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  56210. /**
  56211. * Gets the plane normal used to compute the sliding response (in local space)
  56212. */
  56213. get: function () {
  56214. return this._slidePlaneNormal;
  56215. },
  56216. enumerable: true,
  56217. configurable: true
  56218. });
  56219. // Methods
  56220. /** @hidden */
  56221. Collider.prototype._initialize = function (source, dir, e) {
  56222. this._velocity = dir;
  56223. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  56224. this._basePoint = source;
  56225. source.multiplyToRef(this._radius, this._basePointWorld);
  56226. dir.multiplyToRef(this._radius, this._velocityWorld);
  56227. this._velocityWorldLength = this._velocityWorld.length();
  56228. this._epsilon = e;
  56229. this.collisionFound = false;
  56230. };
  56231. /** @hidden */
  56232. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  56233. pa.subtractToRef(point, this._tempVector);
  56234. pb.subtractToRef(point, this._tempVector2);
  56235. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  56236. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56237. if (d < 0)
  56238. return false;
  56239. pc.subtractToRef(point, this._tempVector3);
  56240. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  56241. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56242. if (d < 0)
  56243. return false;
  56244. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  56245. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56246. return d >= 0;
  56247. };
  56248. /** @hidden */
  56249. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  56250. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  56251. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  56252. if (distance > this._velocityWorldLength + max + sphereRadius) {
  56253. return false;
  56254. }
  56255. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  56256. return false;
  56257. return true;
  56258. };
  56259. /** @hidden */
  56260. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  56261. var t0;
  56262. var embeddedInPlane = false;
  56263. //defensive programming, actually not needed.
  56264. if (!trianglePlaneArray) {
  56265. trianglePlaneArray = [];
  56266. }
  56267. if (!trianglePlaneArray[faceIndex]) {
  56268. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  56269. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  56270. }
  56271. var trianglePlane = trianglePlaneArray[faceIndex];
  56272. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  56273. return;
  56274. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  56275. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  56276. if (normalDotVelocity == 0) {
  56277. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  56278. return;
  56279. embeddedInPlane = true;
  56280. t0 = 0;
  56281. }
  56282. else {
  56283. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56284. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56285. if (t0 > t1) {
  56286. var temp = t1;
  56287. t1 = t0;
  56288. t0 = temp;
  56289. }
  56290. if (t0 > 1.0 || t1 < 0.0)
  56291. return;
  56292. if (t0 < 0)
  56293. t0 = 0;
  56294. if (t0 > 1.0)
  56295. t0 = 1.0;
  56296. }
  56297. this._collisionPoint.copyFromFloats(0, 0, 0);
  56298. var found = false;
  56299. var t = 1.0;
  56300. if (!embeddedInPlane) {
  56301. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  56302. this._velocity.scaleToRef(t0, this._tempVector);
  56303. this._planeIntersectionPoint.addInPlace(this._tempVector);
  56304. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  56305. found = true;
  56306. t = t0;
  56307. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  56308. }
  56309. }
  56310. if (!found) {
  56311. var velocitySquaredLength = this._velocity.lengthSquared();
  56312. var a = velocitySquaredLength;
  56313. this._basePoint.subtractToRef(p1, this._tempVector);
  56314. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56315. var c = this._tempVector.lengthSquared() - 1.0;
  56316. var lowestRoot = getLowestRoot(a, b, c, t);
  56317. if (lowestRoot.found) {
  56318. t = lowestRoot.root;
  56319. found = true;
  56320. this._collisionPoint.copyFrom(p1);
  56321. }
  56322. this._basePoint.subtractToRef(p2, this._tempVector);
  56323. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56324. c = this._tempVector.lengthSquared() - 1.0;
  56325. lowestRoot = getLowestRoot(a, b, c, t);
  56326. if (lowestRoot.found) {
  56327. t = lowestRoot.root;
  56328. found = true;
  56329. this._collisionPoint.copyFrom(p2);
  56330. }
  56331. this._basePoint.subtractToRef(p3, this._tempVector);
  56332. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56333. c = this._tempVector.lengthSquared() - 1.0;
  56334. lowestRoot = getLowestRoot(a, b, c, t);
  56335. if (lowestRoot.found) {
  56336. t = lowestRoot.root;
  56337. found = true;
  56338. this._collisionPoint.copyFrom(p3);
  56339. }
  56340. p2.subtractToRef(p1, this._edge);
  56341. p1.subtractToRef(this._basePoint, this._baseToVertex);
  56342. var edgeSquaredLength = this._edge.lengthSquared();
  56343. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56344. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56345. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56346. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56347. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56348. lowestRoot = getLowestRoot(a, b, c, t);
  56349. if (lowestRoot.found) {
  56350. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56351. if (f >= 0.0 && f <= 1.0) {
  56352. t = lowestRoot.root;
  56353. found = true;
  56354. this._edge.scaleInPlace(f);
  56355. p1.addToRef(this._edge, this._collisionPoint);
  56356. }
  56357. }
  56358. p3.subtractToRef(p2, this._edge);
  56359. p2.subtractToRef(this._basePoint, this._baseToVertex);
  56360. edgeSquaredLength = this._edge.lengthSquared();
  56361. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56362. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56363. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56364. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56365. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56366. lowestRoot = getLowestRoot(a, b, c, t);
  56367. if (lowestRoot.found) {
  56368. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56369. if (f >= 0.0 && f <= 1.0) {
  56370. t = lowestRoot.root;
  56371. found = true;
  56372. this._edge.scaleInPlace(f);
  56373. p2.addToRef(this._edge, this._collisionPoint);
  56374. }
  56375. }
  56376. p1.subtractToRef(p3, this._edge);
  56377. p3.subtractToRef(this._basePoint, this._baseToVertex);
  56378. edgeSquaredLength = this._edge.lengthSquared();
  56379. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56380. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56381. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56382. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56383. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56384. lowestRoot = getLowestRoot(a, b, c, t);
  56385. if (lowestRoot.found) {
  56386. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56387. if (f >= 0.0 && f <= 1.0) {
  56388. t = lowestRoot.root;
  56389. found = true;
  56390. this._edge.scaleInPlace(f);
  56391. p3.addToRef(this._edge, this._collisionPoint);
  56392. }
  56393. }
  56394. }
  56395. if (found) {
  56396. var distToCollision = t * this._velocity.length();
  56397. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  56398. if (!this.intersectionPoint) {
  56399. this.intersectionPoint = this._collisionPoint.clone();
  56400. }
  56401. else {
  56402. this.intersectionPoint.copyFrom(this._collisionPoint);
  56403. }
  56404. this._nearestDistance = distToCollision;
  56405. this.collisionFound = true;
  56406. }
  56407. }
  56408. };
  56409. /** @hidden */
  56410. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  56411. for (var i = indexStart; i < indexEnd; i += 3) {
  56412. var p1 = pts[indices[i] - decal];
  56413. var p2 = pts[indices[i + 1] - decal];
  56414. var p3 = pts[indices[i + 2] - decal];
  56415. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  56416. }
  56417. };
  56418. /** @hidden */
  56419. Collider.prototype._getResponse = function (pos, vel) {
  56420. pos.addToRef(vel, this._destinationPoint);
  56421. vel.scaleInPlace((this._nearestDistance / vel.length()));
  56422. this._basePoint.addToRef(vel, pos);
  56423. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  56424. this._slidePlaneNormal.normalize();
  56425. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  56426. pos.addInPlace(this._displacementVector);
  56427. this.intersectionPoint.addInPlace(this._displacementVector);
  56428. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  56429. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  56430. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  56431. };
  56432. return Collider;
  56433. }());
  56434. BABYLON.Collider = Collider;
  56435. })(BABYLON || (BABYLON = {}));
  56436. //# sourceMappingURL=babylon.collider.js.map
  56437. var BABYLON;
  56438. (function (BABYLON) {
  56439. //WebWorker code will be inserted to this variable.
  56440. /** @hidden */
  56441. BABYLON.CollisionWorker = "";
  56442. /** Defines supported task for worker process */
  56443. var WorkerTaskType;
  56444. (function (WorkerTaskType) {
  56445. /** Initialization */
  56446. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  56447. /** Update of geometry */
  56448. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  56449. /** Evaluate collision */
  56450. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  56451. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  56452. /** Defines kind of replies returned by worker */
  56453. var WorkerReplyType;
  56454. (function (WorkerReplyType) {
  56455. /** Success */
  56456. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  56457. /** Unkown error */
  56458. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  56459. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  56460. /** @hidden */
  56461. var CollisionCoordinatorWorker = /** @class */ (function () {
  56462. function CollisionCoordinatorWorker() {
  56463. var _this = this;
  56464. this._scaledPosition = BABYLON.Vector3.Zero();
  56465. this._scaledVelocity = BABYLON.Vector3.Zero();
  56466. this.onMeshUpdated = function (transformNode) {
  56467. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  56468. };
  56469. this.onGeometryUpdated = function (geometry) {
  56470. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  56471. };
  56472. this._afterRender = function () {
  56473. if (!_this._init)
  56474. return;
  56475. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  56476. return;
  56477. }
  56478. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56479. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56480. if (_this._runningUpdated > 4) {
  56481. return;
  56482. }
  56483. ++_this._runningUpdated;
  56484. var payload = {
  56485. updatedMeshes: _this._addUpdateMeshesList,
  56486. updatedGeometries: _this._addUpdateGeometriesList,
  56487. removedGeometries: _this._toRemoveGeometryArray,
  56488. removedMeshes: _this._toRemoveMeshesArray
  56489. };
  56490. var message = {
  56491. payload: payload,
  56492. taskType: WorkerTaskType.UPDATE
  56493. };
  56494. var serializable = [];
  56495. for (var id in payload.updatedGeometries) {
  56496. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56497. //prepare transferables
  56498. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56499. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56500. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56501. }
  56502. }
  56503. _this._worker.postMessage(message, serializable);
  56504. _this._addUpdateMeshesList = {};
  56505. _this._addUpdateGeometriesList = {};
  56506. _this._toRemoveGeometryArray = [];
  56507. _this._toRemoveMeshesArray = [];
  56508. };
  56509. this._onMessageFromWorker = function (e) {
  56510. var returnData = e.data;
  56511. if (returnData.error != WorkerReplyType.SUCCESS) {
  56512. //TODO what errors can be returned from the worker?
  56513. BABYLON.Tools.Warn("error returned from worker!");
  56514. return;
  56515. }
  56516. switch (returnData.taskType) {
  56517. case WorkerTaskType.INIT:
  56518. _this._init = true;
  56519. //Update the worked with ALL of the scene's current state
  56520. _this._scene.meshes.forEach(function (mesh) {
  56521. _this.onMeshAdded(mesh);
  56522. });
  56523. _this._scene.getGeometries().forEach(function (geometry) {
  56524. _this.onGeometryAdded(geometry);
  56525. });
  56526. break;
  56527. case WorkerTaskType.UPDATE:
  56528. _this._runningUpdated--;
  56529. break;
  56530. case WorkerTaskType.COLLIDE:
  56531. var returnPayload = returnData.payload;
  56532. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56533. return;
  56534. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56535. if (callback) {
  56536. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  56537. if (mesh) {
  56538. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56539. }
  56540. }
  56541. //cleanup
  56542. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56543. break;
  56544. }
  56545. };
  56546. this._collisionsCallbackArray = [];
  56547. this._init = false;
  56548. this._runningUpdated = 0;
  56549. this._addUpdateMeshesList = {};
  56550. this._addUpdateGeometriesList = {};
  56551. this._toRemoveGeometryArray = [];
  56552. this._toRemoveMeshesArray = [];
  56553. }
  56554. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56555. if (!this._init)
  56556. return;
  56557. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56558. return;
  56559. position.divideToRef(collider._radius, this._scaledPosition);
  56560. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56561. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56562. var payload = {
  56563. collider: {
  56564. position: this._scaledPosition.asArray(),
  56565. velocity: this._scaledVelocity.asArray(),
  56566. radius: collider._radius.asArray()
  56567. },
  56568. collisionId: collisionIndex,
  56569. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56570. maximumRetry: maximumRetry
  56571. };
  56572. var message = {
  56573. payload: payload,
  56574. taskType: WorkerTaskType.COLLIDE
  56575. };
  56576. this._worker.postMessage(message);
  56577. };
  56578. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56579. this._scene = scene;
  56580. this._scene.registerAfterRender(this._afterRender);
  56581. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56582. this._worker = new Worker(workerUrl);
  56583. this._worker.onmessage = this._onMessageFromWorker;
  56584. var message = {
  56585. payload: {},
  56586. taskType: WorkerTaskType.INIT
  56587. };
  56588. this._worker.postMessage(message);
  56589. };
  56590. CollisionCoordinatorWorker.prototype.destroy = function () {
  56591. this._scene.unregisterAfterRender(this._afterRender);
  56592. this._worker.terminate();
  56593. };
  56594. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56595. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56596. this.onMeshUpdated(mesh);
  56597. };
  56598. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56599. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56600. };
  56601. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56602. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56603. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56604. this.onGeometryUpdated(geometry);
  56605. };
  56606. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56607. this._toRemoveGeometryArray.push(geometry.id);
  56608. };
  56609. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56610. var submeshes = [];
  56611. if (mesh.subMeshes) {
  56612. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56613. var boundingInfo = sm.getBoundingInfo();
  56614. return {
  56615. position: idx,
  56616. verticesStart: sm.verticesStart,
  56617. verticesCount: sm.verticesCount,
  56618. indexStart: sm.indexStart,
  56619. indexCount: sm.indexCount,
  56620. hasMaterial: !!sm.getMaterial(),
  56621. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56622. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56623. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56624. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56625. };
  56626. });
  56627. }
  56628. var geometryId = null;
  56629. if (mesh instanceof BABYLON.Mesh) {
  56630. var geometry = mesh.geometry;
  56631. geometryId = geometry ? geometry.id : null;
  56632. }
  56633. else if (mesh instanceof BABYLON.InstancedMesh) {
  56634. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56635. geometryId = geometry ? geometry.id : null;
  56636. }
  56637. var boundingInfo = mesh.getBoundingInfo();
  56638. return {
  56639. uniqueId: mesh.uniqueId,
  56640. id: mesh.id,
  56641. name: mesh.name,
  56642. geometryId: geometryId,
  56643. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56644. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56645. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56646. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56647. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56648. subMeshes: submeshes,
  56649. checkCollisions: mesh.checkCollisions
  56650. };
  56651. };
  56652. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56653. return {
  56654. id: geometry.id,
  56655. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56656. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56657. indices: new Uint32Array(geometry.getIndices() || []),
  56658. };
  56659. };
  56660. return CollisionCoordinatorWorker;
  56661. }());
  56662. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56663. /** @hidden */
  56664. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56665. function CollisionCoordinatorLegacy() {
  56666. this._scaledPosition = BABYLON.Vector3.Zero();
  56667. this._scaledVelocity = BABYLON.Vector3.Zero();
  56668. this._finalPosition = BABYLON.Vector3.Zero();
  56669. }
  56670. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56671. position.divideToRef(collider._radius, this._scaledPosition);
  56672. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56673. collider.collidedMesh = null;
  56674. collider._retry = 0;
  56675. collider._initialVelocity = this._scaledVelocity;
  56676. collider._initialPosition = this._scaledPosition;
  56677. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56678. this._finalPosition.multiplyInPlace(collider._radius);
  56679. //run the callback
  56680. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56681. };
  56682. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56683. this._scene = scene;
  56684. };
  56685. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56686. //Legacy need no destruction method.
  56687. };
  56688. //No update in legacy mode
  56689. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56690. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56691. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56692. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56693. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56694. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56695. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56696. if (excludedMesh === void 0) { excludedMesh = null; }
  56697. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56698. if (collider._retry >= maximumRetry) {
  56699. finalPosition.copyFrom(position);
  56700. return;
  56701. }
  56702. // Check if this is a mesh else camera or -1
  56703. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56704. collider._initialize(position, velocity, closeDistance);
  56705. // Check all meshes
  56706. for (var index = 0; index < this._scene.meshes.length; index++) {
  56707. var mesh = this._scene.meshes[index];
  56708. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56709. mesh._checkCollision(collider);
  56710. }
  56711. }
  56712. if (!collider.collisionFound) {
  56713. position.addToRef(velocity, finalPosition);
  56714. return;
  56715. }
  56716. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56717. collider._getResponse(position, velocity);
  56718. }
  56719. if (velocity.length() <= closeDistance) {
  56720. finalPosition.copyFrom(position);
  56721. return;
  56722. }
  56723. collider._retry++;
  56724. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56725. };
  56726. return CollisionCoordinatorLegacy;
  56727. }());
  56728. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56729. })(BABYLON || (BABYLON = {}));
  56730. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56731. var BABYLON;
  56732. (function (BABYLON) {
  56733. /**
  56734. * A particle represents one of the element emitted by a particle system.
  56735. * This is mainly define by its coordinates, direction, velocity and age.
  56736. */
  56737. var Particle = /** @class */ (function () {
  56738. /**
  56739. * Creates a new instance Particle
  56740. * @param particleSystem the particle system the particle belongs to
  56741. */
  56742. function Particle(
  56743. /**
  56744. * The particle system the particle belongs to.
  56745. */
  56746. particleSystem) {
  56747. this.particleSystem = particleSystem;
  56748. /**
  56749. * The world position of the particle in the scene.
  56750. */
  56751. this.position = BABYLON.Vector3.Zero();
  56752. /**
  56753. * The world direction of the particle in the scene.
  56754. */
  56755. this.direction = BABYLON.Vector3.Zero();
  56756. /**
  56757. * The color of the particle.
  56758. */
  56759. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56760. /**
  56761. * The color change of the particle per step.
  56762. */
  56763. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56764. /**
  56765. * Defines how long will the life of the particle be.
  56766. */
  56767. this.lifeTime = 1.0;
  56768. /**
  56769. * The current age of the particle.
  56770. */
  56771. this.age = 0;
  56772. /**
  56773. * The current size of the particle.
  56774. */
  56775. this.size = 0;
  56776. /**
  56777. * The current scale of the particle.
  56778. */
  56779. this.scale = new BABYLON.Vector2(1, 1);
  56780. /**
  56781. * The current angle of the particle.
  56782. */
  56783. this.angle = 0;
  56784. /**
  56785. * Defines how fast is the angle changing.
  56786. */
  56787. this.angularSpeed = 0;
  56788. /**
  56789. * Defines the cell index used by the particle to be rendered from a sprite.
  56790. */
  56791. this.cellIndex = 0;
  56792. /** @hidden */
  56793. this._attachedSubEmitters = null;
  56794. /** @hidden */
  56795. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  56796. /** @hidden */
  56797. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  56798. /** @hidden */
  56799. this._currentSize1 = 0;
  56800. /** @hidden */
  56801. this._currentSize2 = 0;
  56802. /** @hidden */
  56803. this._currentAngularSpeed1 = 0;
  56804. /** @hidden */
  56805. this._currentAngularSpeed2 = 0;
  56806. /** @hidden */
  56807. this._currentVelocity1 = 0;
  56808. /** @hidden */
  56809. this._currentVelocity2 = 0;
  56810. /** @hidden */
  56811. this._currentLimitVelocity1 = 0;
  56812. /** @hidden */
  56813. this._currentLimitVelocity2 = 0;
  56814. /** @hidden */
  56815. this._currentDrag1 = 0;
  56816. /** @hidden */
  56817. this._currentDrag2 = 0;
  56818. this.id = Particle._Count++;
  56819. if (!this.particleSystem.isAnimationSheetEnabled) {
  56820. return;
  56821. }
  56822. this.updateCellInfoFromSystem();
  56823. }
  56824. Particle.prototype.updateCellInfoFromSystem = function () {
  56825. this.cellIndex = this.particleSystem.startSpriteCellID;
  56826. };
  56827. /**
  56828. * Defines how the sprite cell index is updated for the particle
  56829. */
  56830. Particle.prototype.updateCellIndex = function () {
  56831. var offsetAge = this.age;
  56832. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  56833. if (this.particleSystem.spriteRandomStartCell) {
  56834. if (this._randomCellOffset === undefined) {
  56835. this._randomCellOffset = Math.random() * this.lifeTime;
  56836. }
  56837. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  56838. changeSpeed = 1;
  56839. offsetAge = this._randomCellOffset;
  56840. }
  56841. else {
  56842. offsetAge += this._randomCellOffset;
  56843. }
  56844. }
  56845. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  56846. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  56847. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  56848. };
  56849. /** @hidden */
  56850. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  56851. if (subEmitter.particleSystem.emitter.position) {
  56852. var emitterMesh = subEmitter.particleSystem.emitter;
  56853. emitterMesh.position.copyFrom(this.position);
  56854. if (subEmitter.inheritDirection) {
  56855. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  56856. // Look at using Y as forward
  56857. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56858. }
  56859. }
  56860. else {
  56861. var emitterPosition = subEmitter.particleSystem.emitter;
  56862. emitterPosition.copyFrom(this.position);
  56863. }
  56864. // Set inheritedVelocityOffset to be used when new particles are created
  56865. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56866. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56867. };
  56868. /** @hidden */
  56869. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  56870. var _this = this;
  56871. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  56872. this._attachedSubEmitters.forEach(function (subEmitter) {
  56873. _this._inheritParticleInfoToSubEmitter(subEmitter);
  56874. });
  56875. }
  56876. };
  56877. /** @hidden */
  56878. Particle.prototype._reset = function () {
  56879. this.age = 0;
  56880. this._currentColorGradient = null;
  56881. this._currentSizeGradient = null;
  56882. this._currentAngularSpeedGradient = null;
  56883. this._currentVelocityGradient = null;
  56884. this._currentLimitVelocityGradient = null;
  56885. this._currentDragGradient = null;
  56886. this.cellIndex = this.particleSystem.startSpriteCellID;
  56887. this._randomCellOffset = undefined;
  56888. };
  56889. /**
  56890. * Copy the properties of particle to another one.
  56891. * @param other the particle to copy the information to.
  56892. */
  56893. Particle.prototype.copyTo = function (other) {
  56894. other.position.copyFrom(this.position);
  56895. if (this._initialDirection) {
  56896. if (other._initialDirection) {
  56897. other._initialDirection.copyFrom(this._initialDirection);
  56898. }
  56899. else {
  56900. other._initialDirection = this._initialDirection.clone();
  56901. }
  56902. }
  56903. else {
  56904. other._initialDirection = null;
  56905. }
  56906. other.direction.copyFrom(this.direction);
  56907. other.color.copyFrom(this.color);
  56908. other.colorStep.copyFrom(this.colorStep);
  56909. other.lifeTime = this.lifeTime;
  56910. other.age = this.age;
  56911. other._randomCellOffset = this._randomCellOffset;
  56912. other.size = this.size;
  56913. other.scale.copyFrom(this.scale);
  56914. other.angle = this.angle;
  56915. other.angularSpeed = this.angularSpeed;
  56916. other.particleSystem = this.particleSystem;
  56917. other.cellIndex = this.cellIndex;
  56918. other.id = this.id;
  56919. other._attachedSubEmitters = this._attachedSubEmitters;
  56920. if (this._currentColorGradient) {
  56921. other._currentColorGradient = this._currentColorGradient;
  56922. other._currentColor1.copyFrom(this._currentColor1);
  56923. other._currentColor2.copyFrom(this._currentColor2);
  56924. }
  56925. if (this._currentSizeGradient) {
  56926. other._currentSizeGradient = this._currentSizeGradient;
  56927. other._currentSize1 = this._currentSize1;
  56928. other._currentSize2 = this._currentSize2;
  56929. }
  56930. if (this._currentAngularSpeedGradient) {
  56931. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  56932. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  56933. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  56934. }
  56935. if (this._currentVelocityGradient) {
  56936. other._currentVelocityGradient = this._currentVelocityGradient;
  56937. other._currentVelocity1 = this._currentVelocity1;
  56938. other._currentVelocity2 = this._currentVelocity2;
  56939. }
  56940. if (this._currentLimitVelocityGradient) {
  56941. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  56942. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  56943. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  56944. }
  56945. if (this._currentDragGradient) {
  56946. other._currentDragGradient = this._currentDragGradient;
  56947. other._currentDrag1 = this._currentDrag1;
  56948. other._currentDrag2 = this._currentDrag2;
  56949. }
  56950. if (this.particleSystem.isAnimationSheetEnabled) {
  56951. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  56952. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  56953. }
  56954. if (this.particleSystem.useRampGradients) {
  56955. other.remapData.copyFrom(this.remapData);
  56956. }
  56957. if (this._randomNoiseCoordinates1) {
  56958. if (other._randomNoiseCoordinates1) {
  56959. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  56960. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  56961. }
  56962. else {
  56963. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  56964. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  56965. }
  56966. }
  56967. };
  56968. Particle._Count = 0;
  56969. return Particle;
  56970. }());
  56971. BABYLON.Particle = Particle;
  56972. })(BABYLON || (BABYLON = {}));
  56973. //# sourceMappingURL=babylon.particle.js.map
  56974. var BABYLON;
  56975. (function (BABYLON) {
  56976. /**
  56977. * This represents the base class for particle system in Babylon.
  56978. * 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.
  56979. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56980. * @example https://doc.babylonjs.com/babylon101/particles
  56981. */
  56982. var BaseParticleSystem = /** @class */ (function () {
  56983. /**
  56984. * Instantiates a particle system.
  56985. * 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.
  56986. * @param name The name of the particle system
  56987. */
  56988. function BaseParticleSystem(name) {
  56989. /**
  56990. * List of animations used by the particle system.
  56991. */
  56992. this.animations = [];
  56993. /**
  56994. * The rendering group used by the Particle system to chose when to render.
  56995. */
  56996. this.renderingGroupId = 0;
  56997. /**
  56998. * The emitter represents the Mesh or position we are attaching the particle system to.
  56999. */
  57000. this.emitter = null;
  57001. /**
  57002. * The maximum number of particles to emit per frame
  57003. */
  57004. this.emitRate = 10;
  57005. /**
  57006. * If you want to launch only a few particles at once, that can be done, as well.
  57007. */
  57008. this.manualEmitCount = -1;
  57009. /**
  57010. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57011. */
  57012. this.updateSpeed = 0.01;
  57013. /**
  57014. * The amount of time the particle system is running (depends of the overall update speed).
  57015. */
  57016. this.targetStopDuration = 0;
  57017. /**
  57018. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  57019. */
  57020. this.disposeOnStop = false;
  57021. /**
  57022. * Minimum power of emitting particles.
  57023. */
  57024. this.minEmitPower = 1;
  57025. /**
  57026. * Maximum power of emitting particles.
  57027. */
  57028. this.maxEmitPower = 1;
  57029. /**
  57030. * Minimum life time of emitting particles.
  57031. */
  57032. this.minLifeTime = 1;
  57033. /**
  57034. * Maximum life time of emitting particles.
  57035. */
  57036. this.maxLifeTime = 1;
  57037. /**
  57038. * Minimum Size of emitting particles.
  57039. */
  57040. this.minSize = 1;
  57041. /**
  57042. * Maximum Size of emitting particles.
  57043. */
  57044. this.maxSize = 1;
  57045. /**
  57046. * Minimum scale of emitting particles on X axis.
  57047. */
  57048. this.minScaleX = 1;
  57049. /**
  57050. * Maximum scale of emitting particles on X axis.
  57051. */
  57052. this.maxScaleX = 1;
  57053. /**
  57054. * Minimum scale of emitting particles on Y axis.
  57055. */
  57056. this.minScaleY = 1;
  57057. /**
  57058. * Maximum scale of emitting particles on Y axis.
  57059. */
  57060. this.maxScaleY = 1;
  57061. /**
  57062. * Gets or sets the minimal initial rotation in radians.
  57063. */
  57064. this.minInitialRotation = 0;
  57065. /**
  57066. * Gets or sets the maximal initial rotation in radians.
  57067. */
  57068. this.maxInitialRotation = 0;
  57069. /**
  57070. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57071. */
  57072. this.minAngularSpeed = 0;
  57073. /**
  57074. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57075. */
  57076. this.maxAngularSpeed = 0;
  57077. /**
  57078. * The layer mask we are rendering the particles through.
  57079. */
  57080. this.layerMask = 0x0FFFFFFF;
  57081. /**
  57082. * This can help using your own shader to render the particle system.
  57083. * The according effect will be created
  57084. */
  57085. this.customShader = null;
  57086. /**
  57087. * By default particle system starts as soon as they are created. This prevents the
  57088. * automatic start to happen and let you decide when to start emitting particles.
  57089. */
  57090. this.preventAutoStart = false;
  57091. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  57092. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  57093. /**
  57094. * Callback triggered when the particle animation is ending.
  57095. */
  57096. this.onAnimationEnd = null;
  57097. /**
  57098. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57099. */
  57100. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57101. /**
  57102. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57103. * to override the particles.
  57104. */
  57105. this.forceDepthWrite = false;
  57106. /** 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 */
  57107. this.preWarmCycles = 0;
  57108. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57109. this.preWarmStepOffset = 1;
  57110. /**
  57111. * 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)
  57112. */
  57113. this.spriteCellChangeSpeed = 1;
  57114. /**
  57115. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57116. */
  57117. this.startSpriteCellID = 0;
  57118. /**
  57119. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57120. */
  57121. this.endSpriteCellID = 0;
  57122. /**
  57123. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57124. */
  57125. this.spriteCellWidth = 0;
  57126. /**
  57127. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57128. */
  57129. this.spriteCellHeight = 0;
  57130. /**
  57131. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  57132. */
  57133. this.spriteRandomStartCell = false;
  57134. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57135. this.translationPivot = new BABYLON.Vector2(0, 0);
  57136. /**
  57137. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  57138. */
  57139. this.beginAnimationOnStart = false;
  57140. /**
  57141. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  57142. */
  57143. this.beginAnimationFrom = 0;
  57144. /**
  57145. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  57146. */
  57147. this.beginAnimationTo = 60;
  57148. /**
  57149. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  57150. */
  57151. this.beginAnimationLoop = false;
  57152. /**
  57153. * You can use gravity if you want to give an orientation to your particles.
  57154. */
  57155. this.gravity = BABYLON.Vector3.Zero();
  57156. this._colorGradients = null;
  57157. this._sizeGradients = null;
  57158. this._lifeTimeGradients = null;
  57159. this._angularSpeedGradients = null;
  57160. this._velocityGradients = null;
  57161. this._limitVelocityGradients = null;
  57162. this._dragGradients = null;
  57163. this._emitRateGradients = null;
  57164. this._startSizeGradients = null;
  57165. this._rampGradients = null;
  57166. this._colorRemapGradients = null;
  57167. this._alphaRemapGradients = null;
  57168. /**
  57169. * Defines the delay in milliseconds before starting the system (0 by default)
  57170. */
  57171. this.startDelay = 0;
  57172. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  57173. this.limitVelocityDamping = 0.4;
  57174. /**
  57175. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57176. */
  57177. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57178. /**
  57179. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57180. */
  57181. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57182. /**
  57183. * Color the particle will have at the end of its lifetime
  57184. */
  57185. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  57186. /**
  57187. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  57188. */
  57189. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57190. /** @hidden */
  57191. this._isSubEmitter = false;
  57192. /**
  57193. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57194. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  57195. */
  57196. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  57197. this._isBillboardBased = true;
  57198. /**
  57199. * Local cache of defines for image processing.
  57200. */
  57201. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  57202. this.id = name;
  57203. this.name = name;
  57204. }
  57205. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  57206. /**
  57207. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  57208. */
  57209. get: function () {
  57210. return this._isAnimationSheetEnabled;
  57211. },
  57212. set: function (value) {
  57213. if (this._isAnimationSheetEnabled == value) {
  57214. return;
  57215. }
  57216. this._isAnimationSheetEnabled = value;
  57217. this._reset();
  57218. },
  57219. enumerable: true,
  57220. configurable: true
  57221. });
  57222. /**
  57223. * Get hosting scene
  57224. * @returns the scene
  57225. */
  57226. BaseParticleSystem.prototype.getScene = function () {
  57227. return this._scene;
  57228. };
  57229. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  57230. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  57231. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  57232. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  57233. };
  57234. /**
  57235. * Gets the current list of drag gradients.
  57236. * You must use addDragGradient and removeDragGradient to udpate this list
  57237. * @returns the list of drag gradients
  57238. */
  57239. BaseParticleSystem.prototype.getDragGradients = function () {
  57240. return this._dragGradients;
  57241. };
  57242. /**
  57243. * Gets the current list of limit velocity gradients.
  57244. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  57245. * @returns the list of limit velocity gradients
  57246. */
  57247. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  57248. return this._limitVelocityGradients;
  57249. };
  57250. /**
  57251. * Gets the current list of color gradients.
  57252. * You must use addColorGradient and removeColorGradient to udpate this list
  57253. * @returns the list of color gradients
  57254. */
  57255. BaseParticleSystem.prototype.getColorGradients = function () {
  57256. return this._colorGradients;
  57257. };
  57258. /**
  57259. * Gets the current list of size gradients.
  57260. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57261. * @returns the list of size gradients
  57262. */
  57263. BaseParticleSystem.prototype.getSizeGradients = function () {
  57264. return this._sizeGradients;
  57265. };
  57266. /**
  57267. * Gets the current list of color remap gradients.
  57268. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  57269. * @returns the list of color remap gradients
  57270. */
  57271. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  57272. return this._colorRemapGradients;
  57273. };
  57274. /**
  57275. * Gets the current list of alpha remap gradients.
  57276. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  57277. * @returns the list of alpha remap gradients
  57278. */
  57279. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  57280. return this._alphaRemapGradients;
  57281. };
  57282. /**
  57283. * Gets the current list of life time gradients.
  57284. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  57285. * @returns the list of life time gradients
  57286. */
  57287. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  57288. return this._lifeTimeGradients;
  57289. };
  57290. /**
  57291. * Gets the current list of angular speed gradients.
  57292. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57293. * @returns the list of angular speed gradients
  57294. */
  57295. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  57296. return this._angularSpeedGradients;
  57297. };
  57298. /**
  57299. * Gets the current list of velocity gradients.
  57300. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57301. * @returns the list of velocity gradients
  57302. */
  57303. BaseParticleSystem.prototype.getVelocityGradients = function () {
  57304. return this._velocityGradients;
  57305. };
  57306. /**
  57307. * Gets the current list of start size gradients.
  57308. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  57309. * @returns the list of start size gradients
  57310. */
  57311. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  57312. return this._startSizeGradients;
  57313. };
  57314. /**
  57315. * Gets the current list of emit rate gradients.
  57316. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  57317. * @returns the list of emit rate gradients
  57318. */
  57319. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  57320. return this._emitRateGradients;
  57321. };
  57322. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  57323. /**
  57324. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57325. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57326. */
  57327. get: function () {
  57328. if (this.particleEmitterType.direction1) {
  57329. return this.particleEmitterType.direction1;
  57330. }
  57331. return BABYLON.Vector3.Zero();
  57332. },
  57333. set: function (value) {
  57334. if (this.particleEmitterType.direction1) {
  57335. this.particleEmitterType.direction1 = value;
  57336. }
  57337. },
  57338. enumerable: true,
  57339. configurable: true
  57340. });
  57341. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  57342. /**
  57343. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57344. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57345. */
  57346. get: function () {
  57347. if (this.particleEmitterType.direction2) {
  57348. return this.particleEmitterType.direction2;
  57349. }
  57350. return BABYLON.Vector3.Zero();
  57351. },
  57352. set: function (value) {
  57353. if (this.particleEmitterType.direction2) {
  57354. this.particleEmitterType.direction2 = value;
  57355. }
  57356. },
  57357. enumerable: true,
  57358. configurable: true
  57359. });
  57360. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  57361. /**
  57362. * 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.
  57363. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57364. */
  57365. get: function () {
  57366. if (this.particleEmitterType.minEmitBox) {
  57367. return this.particleEmitterType.minEmitBox;
  57368. }
  57369. return BABYLON.Vector3.Zero();
  57370. },
  57371. set: function (value) {
  57372. if (this.particleEmitterType.minEmitBox) {
  57373. this.particleEmitterType.minEmitBox = value;
  57374. }
  57375. },
  57376. enumerable: true,
  57377. configurable: true
  57378. });
  57379. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  57380. /**
  57381. * 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.
  57382. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57383. */
  57384. get: function () {
  57385. if (this.particleEmitterType.maxEmitBox) {
  57386. return this.particleEmitterType.maxEmitBox;
  57387. }
  57388. return BABYLON.Vector3.Zero();
  57389. },
  57390. set: function (value) {
  57391. if (this.particleEmitterType.maxEmitBox) {
  57392. this.particleEmitterType.maxEmitBox = value;
  57393. }
  57394. },
  57395. enumerable: true,
  57396. configurable: true
  57397. });
  57398. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  57399. /**
  57400. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57401. */
  57402. get: function () {
  57403. return this._isBillboardBased;
  57404. },
  57405. set: function (value) {
  57406. if (this._isBillboardBased === value) {
  57407. return;
  57408. }
  57409. this._isBillboardBased = value;
  57410. this._reset();
  57411. },
  57412. enumerable: true,
  57413. configurable: true
  57414. });
  57415. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  57416. /**
  57417. * Gets the image processing configuration used either in this material.
  57418. */
  57419. get: function () {
  57420. return this._imageProcessingConfiguration;
  57421. },
  57422. /**
  57423. * Sets the Default image processing configuration used either in the this material.
  57424. *
  57425. * If sets to null, the scene one is in use.
  57426. */
  57427. set: function (value) {
  57428. this._attachImageProcessingConfiguration(value);
  57429. },
  57430. enumerable: true,
  57431. configurable: true
  57432. });
  57433. /**
  57434. * Attaches a new image processing configuration to the Standard Material.
  57435. * @param configuration
  57436. */
  57437. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  57438. if (configuration === this._imageProcessingConfiguration) {
  57439. return;
  57440. }
  57441. // Pick the scene configuration if needed.
  57442. if (!configuration) {
  57443. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  57444. }
  57445. else {
  57446. this._imageProcessingConfiguration = configuration;
  57447. }
  57448. };
  57449. /** @hidden */
  57450. BaseParticleSystem.prototype._reset = function () {
  57451. };
  57452. /** @hidden */
  57453. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  57454. if (!gradients) {
  57455. return this;
  57456. }
  57457. var index = 0;
  57458. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57459. var valueGradient = gradients_1[_i];
  57460. if (valueGradient.gradient === gradient) {
  57461. gradients.splice(index, 1);
  57462. break;
  57463. }
  57464. index++;
  57465. }
  57466. if (texture) {
  57467. texture.dispose();
  57468. }
  57469. return this;
  57470. };
  57471. /**
  57472. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  57473. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57474. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57475. * @returns the emitter
  57476. */
  57477. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  57478. var particleEmitter = new BABYLON.PointParticleEmitter();
  57479. particleEmitter.direction1 = direction1;
  57480. particleEmitter.direction2 = direction2;
  57481. this.particleEmitterType = particleEmitter;
  57482. return particleEmitter;
  57483. };
  57484. /**
  57485. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  57486. * @param radius The radius of the hemisphere to emit from
  57487. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57488. * @returns the emitter
  57489. */
  57490. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  57491. if (radius === void 0) { radius = 1; }
  57492. if (radiusRange === void 0) { radiusRange = 1; }
  57493. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  57494. this.particleEmitterType = particleEmitter;
  57495. return particleEmitter;
  57496. };
  57497. /**
  57498. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57499. * @param radius The radius of the sphere to emit from
  57500. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57501. * @returns the emitter
  57502. */
  57503. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57504. if (radius === void 0) { radius = 1; }
  57505. if (radiusRange === void 0) { radiusRange = 1; }
  57506. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57507. this.particleEmitterType = particleEmitter;
  57508. return particleEmitter;
  57509. };
  57510. /**
  57511. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  57512. * @param radius The radius of the sphere to emit from
  57513. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57514. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57515. * @returns the emitter
  57516. */
  57517. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57518. if (radius === void 0) { radius = 1; }
  57519. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57520. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57521. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57522. this.particleEmitterType = particleEmitter;
  57523. return particleEmitter;
  57524. };
  57525. /**
  57526. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57527. * @param radius The radius of the emission cylinder
  57528. * @param height The height of the emission cylinder
  57529. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57530. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57531. * @returns the emitter
  57532. */
  57533. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57534. if (radius === void 0) { radius = 1; }
  57535. if (height === void 0) { height = 1; }
  57536. if (radiusRange === void 0) { radiusRange = 1; }
  57537. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57538. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  57539. this.particleEmitterType = particleEmitter;
  57540. return particleEmitter;
  57541. };
  57542. /**
  57543. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  57544. * @param radius The radius of the cylinder to emit from
  57545. * @param height The height of the emission cylinder
  57546. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57547. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  57548. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  57549. * @returns the emitter
  57550. */
  57551. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  57552. if (radius === void 0) { radius = 1; }
  57553. if (height === void 0) { height = 1; }
  57554. if (radiusRange === void 0) { radiusRange = 1; }
  57555. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57556. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57557. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  57558. this.particleEmitterType = particleEmitter;
  57559. return particleEmitter;
  57560. };
  57561. /**
  57562. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  57563. * @param radius The radius of the cone to emit from
  57564. * @param angle The base angle of the cone
  57565. * @returns the emitter
  57566. */
  57567. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57568. if (radius === void 0) { radius = 1; }
  57569. if (angle === void 0) { angle = Math.PI / 4; }
  57570. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57571. this.particleEmitterType = particleEmitter;
  57572. return particleEmitter;
  57573. };
  57574. /**
  57575. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57576. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57577. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57578. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57579. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57580. * @returns the emitter
  57581. */
  57582. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57583. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57584. this.particleEmitterType = particleEmitter;
  57585. this.direction1 = direction1;
  57586. this.direction2 = direction2;
  57587. this.minEmitBox = minEmitBox;
  57588. this.maxEmitBox = maxEmitBox;
  57589. return particleEmitter;
  57590. };
  57591. /**
  57592. * Source color is added to the destination color without alpha affecting the result
  57593. */
  57594. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  57595. /**
  57596. * Blend current color and particle color using particle’s alpha
  57597. */
  57598. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  57599. /**
  57600. * Add current color and particle color multiplied by particle’s alpha
  57601. */
  57602. BaseParticleSystem.BLENDMODE_ADD = 2;
  57603. /**
  57604. * Multiply current color with particle color
  57605. */
  57606. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  57607. /**
  57608. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  57609. */
  57610. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  57611. return BaseParticleSystem;
  57612. }());
  57613. BABYLON.BaseParticleSystem = BaseParticleSystem;
  57614. })(BABYLON || (BABYLON = {}));
  57615. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  57616. var BABYLON;
  57617. (function (BABYLON) {
  57618. /**
  57619. * This represents a particle system in Babylon.
  57620. * 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.
  57621. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57622. * @example https://doc.babylonjs.com/babylon101/particles
  57623. */
  57624. var ParticleSystem = /** @class */ (function (_super) {
  57625. __extends(ParticleSystem, _super);
  57626. /**
  57627. * Instantiates a particle system.
  57628. * 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.
  57629. * @param name The name of the particle system
  57630. * @param capacity The max number of particles alive at the same time
  57631. * @param scene The scene the particle system belongs to
  57632. * @param customEffect a custom effect used to change the way particles are rendered by default
  57633. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57634. * @param epsilon Offset used to render the particles
  57635. */
  57636. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  57637. if (customEffect === void 0) { customEffect = null; }
  57638. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57639. if (epsilon === void 0) { epsilon = 0.01; }
  57640. var _this = _super.call(this, name) || this;
  57641. /**
  57642. * @hidden
  57643. */
  57644. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  57645. /**
  57646. * An event triggered when the system is disposed
  57647. */
  57648. _this.onDisposeObservable = new BABYLON.Observable();
  57649. _this._particles = new Array();
  57650. _this._stockParticles = new Array();
  57651. _this._newPartsExcess = 0;
  57652. _this._vertexBuffers = {};
  57653. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  57654. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57655. _this._scaledDirection = BABYLON.Vector3.Zero();
  57656. _this._scaledGravity = BABYLON.Vector3.Zero();
  57657. _this._currentRenderId = -1;
  57658. _this._useInstancing = false;
  57659. _this._started = false;
  57660. _this._stopped = false;
  57661. _this._actualFrame = 0;
  57662. /** @hidden */
  57663. _this._currentEmitRate1 = 0;
  57664. /** @hidden */
  57665. _this._currentEmitRate2 = 0;
  57666. /** @hidden */
  57667. _this._currentStartSize1 = 0;
  57668. /** @hidden */
  57669. _this._currentStartSize2 = 0;
  57670. _this._rawTextureWidth = 256;
  57671. _this._useRampGradients = false;
  57672. /**
  57673. * @hidden
  57674. * If the particle systems emitter should be disposed when the particle system is disposed
  57675. */
  57676. _this._disposeEmitterOnDispose = false;
  57677. // start of sub system methods
  57678. /**
  57679. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  57680. * Its lifetime will start back at 0.
  57681. */
  57682. _this.recycleParticle = function (particle) {
  57683. // move particle from activeParticle list to stock particles
  57684. var lastParticle = _this._particles.pop();
  57685. if (lastParticle !== particle) {
  57686. lastParticle.copyTo(particle);
  57687. }
  57688. _this._stockParticles.push(lastParticle);
  57689. };
  57690. _this._createParticle = function () {
  57691. var particle;
  57692. if (_this._stockParticles.length !== 0) {
  57693. particle = _this._stockParticles.pop();
  57694. particle._reset();
  57695. }
  57696. else {
  57697. particle = new BABYLON.Particle(_this);
  57698. }
  57699. // Attach emitters
  57700. if (_this._subEmitters && _this._subEmitters.length > 0) {
  57701. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  57702. particle._attachedSubEmitters = [];
  57703. subEmitters.forEach(function (subEmitter) {
  57704. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  57705. var newEmitter = subEmitter.clone();
  57706. particle._attachedSubEmitters.push(newEmitter);
  57707. newEmitter.particleSystem.start();
  57708. }
  57709. });
  57710. }
  57711. return particle;
  57712. };
  57713. _this._emitFromParticle = function (particle) {
  57714. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  57715. return;
  57716. }
  57717. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  57718. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  57719. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  57720. var subSystem = subEmitter.clone();
  57721. particle._inheritParticleInfoToSubEmitter(subSystem);
  57722. subSystem.particleSystem._rootParticleSystem = _this;
  57723. _this.activeSubSystems.push(subSystem.particleSystem);
  57724. subSystem.particleSystem.start();
  57725. }
  57726. });
  57727. };
  57728. _this._capacity = capacity;
  57729. _this._epsilon = epsilon;
  57730. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57731. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57732. // Setup the default processing configuration to the scene.
  57733. _this._attachImageProcessingConfiguration(null);
  57734. _this._customEffect = customEffect;
  57735. _this._scene.particleSystems.push(_this);
  57736. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  57737. _this._createIndexBuffer();
  57738. _this._createVertexBuffers();
  57739. // Default emitter type
  57740. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57741. // Update
  57742. _this.updateFunction = function (particles) {
  57743. var noiseTextureSize = null;
  57744. var noiseTextureData = null;
  57745. if (_this.noiseTexture) { // We need to get texture data back to CPU
  57746. noiseTextureSize = _this.noiseTexture.getSize();
  57747. noiseTextureData = (_this.noiseTexture.getContent());
  57748. }
  57749. var _loop_1 = function () {
  57750. particle = particles[index];
  57751. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  57752. var previousAge = particle.age;
  57753. particle.age += scaledUpdateSpeed;
  57754. // Evaluate step to death
  57755. if (particle.age > particle.lifeTime) {
  57756. var diff = particle.age - previousAge;
  57757. var oldDiff = particle.lifeTime - previousAge;
  57758. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  57759. particle.age = particle.lifeTime;
  57760. }
  57761. var ratio = particle.age / particle.lifeTime;
  57762. // Color
  57763. if (_this._colorGradients && _this._colorGradients.length > 0) {
  57764. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  57765. if (currentGradient !== particle._currentColorGradient) {
  57766. particle._currentColor1.copyFrom(particle._currentColor2);
  57767. nextGradient.getColorToRef(particle._currentColor2);
  57768. particle._currentColorGradient = currentGradient;
  57769. }
  57770. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  57771. });
  57772. }
  57773. else {
  57774. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  57775. particle.color.addInPlace(_this._scaledColorStep);
  57776. if (particle.color.a < 0) {
  57777. particle.color.a = 0;
  57778. }
  57779. }
  57780. // Angular speed
  57781. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  57782. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  57783. if (currentGradient !== particle._currentAngularSpeedGradient) {
  57784. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  57785. particle._currentAngularSpeed2 = nextGradient.getFactor();
  57786. particle._currentAngularSpeedGradient = currentGradient;
  57787. }
  57788. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  57789. });
  57790. }
  57791. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  57792. // Direction
  57793. var directionScale = scaledUpdateSpeed;
  57794. /// Velocity
  57795. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  57796. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  57797. if (currentGradient !== particle._currentVelocityGradient) {
  57798. particle._currentVelocity1 = particle._currentVelocity2;
  57799. particle._currentVelocity2 = nextGradient.getFactor();
  57800. particle._currentVelocityGradient = currentGradient;
  57801. }
  57802. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  57803. });
  57804. }
  57805. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  57806. /// Limit velocity
  57807. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  57808. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  57809. if (currentGradient !== particle._currentLimitVelocityGradient) {
  57810. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  57811. particle._currentLimitVelocity2 = nextGradient.getFactor();
  57812. particle._currentLimitVelocityGradient = currentGradient;
  57813. }
  57814. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  57815. var currentVelocity = particle.direction.length();
  57816. if (currentVelocity > limitVelocity) {
  57817. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  57818. }
  57819. });
  57820. }
  57821. /// Drag
  57822. if (_this._dragGradients && _this._dragGradients.length > 0) {
  57823. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  57824. if (currentGradient !== particle._currentDragGradient) {
  57825. particle._currentDrag1 = particle._currentDrag2;
  57826. particle._currentDrag2 = nextGradient.getFactor();
  57827. particle._currentDragGradient = currentGradient;
  57828. }
  57829. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  57830. _this._scaledDirection.scaleInPlace(1.0 - drag);
  57831. });
  57832. }
  57833. particle.position.addInPlace(_this._scaledDirection);
  57834. // Noise
  57835. if (noiseTextureData && noiseTextureSize) {
  57836. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57837. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57838. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57839. var force = BABYLON.Tmp.Vector3[0];
  57840. var scaledForce = BABYLON.Tmp.Vector3[1];
  57841. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  57842. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  57843. particle.direction.addInPlace(scaledForce);
  57844. }
  57845. // Gravity
  57846. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  57847. particle.direction.addInPlace(_this._scaledGravity);
  57848. // Size
  57849. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  57850. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57851. if (currentGradient !== particle._currentSizeGradient) {
  57852. particle._currentSize1 = particle._currentSize2;
  57853. particle._currentSize2 = nextGradient.getFactor();
  57854. particle._currentSizeGradient = currentGradient;
  57855. }
  57856. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  57857. });
  57858. }
  57859. // Remap data
  57860. if (_this._useRampGradients) {
  57861. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  57862. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  57863. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57864. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57865. particle.remapData.x = min;
  57866. particle.remapData.y = max - min;
  57867. });
  57868. }
  57869. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  57870. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  57871. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57872. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57873. particle.remapData.z = min;
  57874. particle.remapData.w = max - min;
  57875. });
  57876. }
  57877. }
  57878. if (_this._isAnimationSheetEnabled) {
  57879. particle.updateCellIndex();
  57880. }
  57881. // Update the position of the attached sub-emitters to match their attached particle
  57882. particle._inheritParticleInfoToSubEmitters();
  57883. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  57884. _this._emitFromParticle(particle);
  57885. if (particle._attachedSubEmitters) {
  57886. particle._attachedSubEmitters.forEach(function (subEmitter) {
  57887. subEmitter.particleSystem.disposeOnStop = true;
  57888. subEmitter.particleSystem.stop();
  57889. });
  57890. particle._attachedSubEmitters = null;
  57891. }
  57892. _this.recycleParticle(particle);
  57893. index--;
  57894. return "continue";
  57895. }
  57896. };
  57897. var particle;
  57898. for (var index = 0; index < particles.length; index++) {
  57899. _loop_1();
  57900. }
  57901. };
  57902. return _this;
  57903. }
  57904. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  57905. /**
  57906. * Sets a callback that will be triggered when the system is disposed
  57907. */
  57908. set: function (callback) {
  57909. if (this._onDisposeObserver) {
  57910. this.onDisposeObservable.remove(this._onDisposeObserver);
  57911. }
  57912. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57913. },
  57914. enumerable: true,
  57915. configurable: true
  57916. });
  57917. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  57918. /** Gets or sets a boolean indicating that ramp gradients must be used
  57919. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  57920. */
  57921. get: function () {
  57922. return this._useRampGradients;
  57923. },
  57924. set: function (value) {
  57925. if (this._useRampGradients === value) {
  57926. return;
  57927. }
  57928. this._useRampGradients = value;
  57929. this._resetEffect();
  57930. },
  57931. enumerable: true,
  57932. configurable: true
  57933. });
  57934. Object.defineProperty(ParticleSystem.prototype, "particles", {
  57935. //end of Sub-emitter
  57936. /**
  57937. * Gets the current list of active particles
  57938. */
  57939. get: function () {
  57940. return this._particles;
  57941. },
  57942. enumerable: true,
  57943. configurable: true
  57944. });
  57945. /**
  57946. * Returns the string "ParticleSystem"
  57947. * @returns a string containing the class name
  57948. */
  57949. ParticleSystem.prototype.getClassName = function () {
  57950. return "ParticleSystem";
  57951. };
  57952. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  57953. var newGradient = new BABYLON.FactorGradient();
  57954. newGradient.gradient = gradient;
  57955. newGradient.factor1 = factor;
  57956. newGradient.factor2 = factor2;
  57957. factorGradients.push(newGradient);
  57958. factorGradients.sort(function (a, b) {
  57959. if (a.gradient < b.gradient) {
  57960. return -1;
  57961. }
  57962. else if (a.gradient > b.gradient) {
  57963. return 1;
  57964. }
  57965. return 0;
  57966. });
  57967. };
  57968. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  57969. if (!factorGradients) {
  57970. return;
  57971. }
  57972. var index = 0;
  57973. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  57974. var factorGradient = factorGradients_1[_i];
  57975. if (factorGradient.gradient === gradient) {
  57976. factorGradients.splice(index, 1);
  57977. break;
  57978. }
  57979. index++;
  57980. }
  57981. };
  57982. /**
  57983. * Adds a new life time gradient
  57984. * @param gradient defines the gradient to use (between 0 and 1)
  57985. * @param factor defines the life time factor to affect to the specified gradient
  57986. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57987. * @returns the current particle system
  57988. */
  57989. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  57990. if (!this._lifeTimeGradients) {
  57991. this._lifeTimeGradients = [];
  57992. }
  57993. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  57994. return this;
  57995. };
  57996. /**
  57997. * Remove a specific life time gradient
  57998. * @param gradient defines the gradient to remove
  57999. * @returns the current particle system
  58000. */
  58001. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  58002. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  58003. return this;
  58004. };
  58005. /**
  58006. * Adds a new size gradient
  58007. * @param gradient defines the gradient to use (between 0 and 1)
  58008. * @param factor defines the size factor to affect to the specified gradient
  58009. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58010. * @returns the current particle system
  58011. */
  58012. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  58013. if (!this._sizeGradients) {
  58014. this._sizeGradients = [];
  58015. }
  58016. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  58017. return this;
  58018. };
  58019. /**
  58020. * Remove a specific size gradient
  58021. * @param gradient defines the gradient to remove
  58022. * @returns the current particle system
  58023. */
  58024. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  58025. this._removeFactorGradient(this._sizeGradients, gradient);
  58026. return this;
  58027. };
  58028. /**
  58029. * Adds a new color remap gradient
  58030. * @param gradient defines the gradient to use (between 0 and 1)
  58031. * @param min defines the color remap minimal range
  58032. * @param max defines the color remap maximal range
  58033. * @returns the current particle system
  58034. */
  58035. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  58036. if (!this._colorRemapGradients) {
  58037. this._colorRemapGradients = [];
  58038. }
  58039. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  58040. return this;
  58041. };
  58042. /**
  58043. * Remove a specific color remap gradient
  58044. * @param gradient defines the gradient to remove
  58045. * @returns the current particle system
  58046. */
  58047. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  58048. this._removeFactorGradient(this._colorRemapGradients, gradient);
  58049. return this;
  58050. };
  58051. /**
  58052. * Adds a new alpha remap gradient
  58053. * @param gradient defines the gradient to use (between 0 and 1)
  58054. * @param min defines the alpha remap minimal range
  58055. * @param max defines the alpha remap maximal range
  58056. * @returns the current particle system
  58057. */
  58058. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  58059. if (!this._alphaRemapGradients) {
  58060. this._alphaRemapGradients = [];
  58061. }
  58062. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  58063. return this;
  58064. };
  58065. /**
  58066. * Remove a specific alpha remap gradient
  58067. * @param gradient defines the gradient to remove
  58068. * @returns the current particle system
  58069. */
  58070. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  58071. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  58072. return this;
  58073. };
  58074. /**
  58075. * Adds a new angular speed gradient
  58076. * @param gradient defines the gradient to use (between 0 and 1)
  58077. * @param factor defines the angular speed to affect to the specified gradient
  58078. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58079. * @returns the current particle system
  58080. */
  58081. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  58082. if (!this._angularSpeedGradients) {
  58083. this._angularSpeedGradients = [];
  58084. }
  58085. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  58086. return this;
  58087. };
  58088. /**
  58089. * Remove a specific angular speed gradient
  58090. * @param gradient defines the gradient to remove
  58091. * @returns the current particle system
  58092. */
  58093. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  58094. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  58095. return this;
  58096. };
  58097. /**
  58098. * Adds a new velocity gradient
  58099. * @param gradient defines the gradient to use (between 0 and 1)
  58100. * @param factor defines the velocity to affect to the specified gradient
  58101. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58102. * @returns the current particle system
  58103. */
  58104. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  58105. if (!this._velocityGradients) {
  58106. this._velocityGradients = [];
  58107. }
  58108. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  58109. return this;
  58110. };
  58111. /**
  58112. * Remove a specific velocity gradient
  58113. * @param gradient defines the gradient to remove
  58114. * @returns the current particle system
  58115. */
  58116. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  58117. this._removeFactorGradient(this._velocityGradients, gradient);
  58118. return this;
  58119. };
  58120. /**
  58121. * Adds a new limit velocity gradient
  58122. * @param gradient defines the gradient to use (between 0 and 1)
  58123. * @param factor defines the limit velocity value to affect to the specified gradient
  58124. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58125. * @returns the current particle system
  58126. */
  58127. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  58128. if (!this._limitVelocityGradients) {
  58129. this._limitVelocityGradients = [];
  58130. }
  58131. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  58132. return this;
  58133. };
  58134. /**
  58135. * Remove a specific limit velocity gradient
  58136. * @param gradient defines the gradient to remove
  58137. * @returns the current particle system
  58138. */
  58139. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  58140. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  58141. return this;
  58142. };
  58143. /**
  58144. * Adds a new drag gradient
  58145. * @param gradient defines the gradient to use (between 0 and 1)
  58146. * @param factor defines the drag value to affect to the specified gradient
  58147. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58148. * @returns the current particle system
  58149. */
  58150. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  58151. if (!this._dragGradients) {
  58152. this._dragGradients = [];
  58153. }
  58154. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  58155. return this;
  58156. };
  58157. /**
  58158. * Remove a specific drag gradient
  58159. * @param gradient defines the gradient to remove
  58160. * @returns the current particle system
  58161. */
  58162. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  58163. this._removeFactorGradient(this._dragGradients, gradient);
  58164. return this;
  58165. };
  58166. /**
  58167. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  58168. * @param gradient defines the gradient to use (between 0 and 1)
  58169. * @param factor defines the emit rate value to affect to the specified gradient
  58170. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58171. * @returns the current particle system
  58172. */
  58173. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  58174. if (!this._emitRateGradients) {
  58175. this._emitRateGradients = [];
  58176. }
  58177. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  58178. if (!this._currentEmitRateGradient) {
  58179. this._currentEmitRateGradient = this._emitRateGradients[0];
  58180. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  58181. this._currentEmitRate2 = this._currentEmitRate1;
  58182. }
  58183. if (this._emitRateGradients.length === 2) {
  58184. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  58185. }
  58186. return this;
  58187. };
  58188. /**
  58189. * Remove a specific emit rate gradient
  58190. * @param gradient defines the gradient to remove
  58191. * @returns the current particle system
  58192. */
  58193. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  58194. this._removeFactorGradient(this._emitRateGradients, gradient);
  58195. return this;
  58196. };
  58197. /**
  58198. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  58199. * @param gradient defines the gradient to use (between 0 and 1)
  58200. * @param factor defines the start size value to affect to the specified gradient
  58201. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58202. * @returns the current particle system
  58203. */
  58204. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  58205. if (!this._startSizeGradients) {
  58206. this._startSizeGradients = [];
  58207. }
  58208. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  58209. if (!this._currentStartSizeGradient) {
  58210. this._currentStartSizeGradient = this._startSizeGradients[0];
  58211. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  58212. this._currentStartSize2 = this._currentStartSize1;
  58213. }
  58214. if (this._startSizeGradients.length === 2) {
  58215. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  58216. }
  58217. return this;
  58218. };
  58219. /**
  58220. * Remove a specific start size gradient
  58221. * @param gradient defines the gradient to remove
  58222. * @returns the current particle system
  58223. */
  58224. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  58225. this._removeFactorGradient(this._emitRateGradients, gradient);
  58226. return this;
  58227. };
  58228. ParticleSystem.prototype._createRampGradientTexture = function () {
  58229. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  58230. return;
  58231. }
  58232. var data = new Uint8Array(this._rawTextureWidth * 4);
  58233. var tmpColor = BABYLON.Tmp.Color3[0];
  58234. for (var x = 0; x < this._rawTextureWidth; x++) {
  58235. var ratio = x / this._rawTextureWidth;
  58236. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  58237. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  58238. data[x * 4] = tmpColor.r * 255;
  58239. data[x * 4 + 1] = tmpColor.g * 255;
  58240. data[x * 4 + 2] = tmpColor.b * 255;
  58241. data[x * 4 + 3] = 255;
  58242. });
  58243. }
  58244. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58245. };
  58246. /**
  58247. * Gets the current list of ramp gradients.
  58248. * You must use addRampGradient and removeRampGradient to udpate this list
  58249. * @returns the list of ramp gradients
  58250. */
  58251. ParticleSystem.prototype.getRampGradients = function () {
  58252. return this._rampGradients;
  58253. };
  58254. /**
  58255. * Adds a new ramp gradient used to remap particle colors
  58256. * @param gradient defines the gradient to use (between 0 and 1)
  58257. * @param color defines the color to affect to the specified gradient
  58258. * @returns the current particle system
  58259. */
  58260. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  58261. if (!this._rampGradients) {
  58262. this._rampGradients = [];
  58263. }
  58264. var rampGradient = new BABYLON.Color3Gradient();
  58265. rampGradient.gradient = gradient;
  58266. rampGradient.color = color;
  58267. this._rampGradients.push(rampGradient);
  58268. this._rampGradients.sort(function (a, b) {
  58269. if (a.gradient < b.gradient) {
  58270. return -1;
  58271. }
  58272. else if (a.gradient > b.gradient) {
  58273. return 1;
  58274. }
  58275. return 0;
  58276. });
  58277. if (this._rampGradientsTexture) {
  58278. this._rampGradientsTexture.dispose();
  58279. this._rampGradientsTexture = null;
  58280. }
  58281. this._createRampGradientTexture();
  58282. return this;
  58283. };
  58284. /**
  58285. * Remove a specific ramp gradient
  58286. * @param gradient defines the gradient to remove
  58287. * @returns the current particle system
  58288. */
  58289. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  58290. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  58291. this._rampGradientsTexture = null;
  58292. if (this._rampGradients && this._rampGradients.length > 0) {
  58293. this._createRampGradientTexture();
  58294. }
  58295. return this;
  58296. };
  58297. /**
  58298. * Adds a new color gradient
  58299. * @param gradient defines the gradient to use (between 0 and 1)
  58300. * @param color1 defines the color to affect to the specified gradient
  58301. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  58302. */
  58303. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  58304. if (!this._colorGradients) {
  58305. this._colorGradients = [];
  58306. }
  58307. var colorGradient = new BABYLON.ColorGradient();
  58308. colorGradient.gradient = gradient;
  58309. colorGradient.color1 = color1;
  58310. colorGradient.color2 = color2;
  58311. this._colorGradients.push(colorGradient);
  58312. this._colorGradients.sort(function (a, b) {
  58313. if (a.gradient < b.gradient) {
  58314. return -1;
  58315. }
  58316. else if (a.gradient > b.gradient) {
  58317. return 1;
  58318. }
  58319. return 0;
  58320. });
  58321. return this;
  58322. };
  58323. /**
  58324. * Remove a specific color gradient
  58325. * @param gradient defines the gradient to remove
  58326. */
  58327. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  58328. if (!this._colorGradients) {
  58329. return this;
  58330. }
  58331. var index = 0;
  58332. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  58333. var colorGradient = _a[_i];
  58334. if (colorGradient.gradient === gradient) {
  58335. this._colorGradients.splice(index, 1);
  58336. break;
  58337. }
  58338. index++;
  58339. }
  58340. return this;
  58341. };
  58342. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  58343. u = Math.abs(u) * 0.5 + 0.5;
  58344. v = Math.abs(v) * 0.5 + 0.5;
  58345. var wrappedU = ((u * width) % width) | 0;
  58346. var wrappedV = ((v * height) % height) | 0;
  58347. var position = (wrappedU + wrappedV * width) * 4;
  58348. return pixels[position] / 255;
  58349. };
  58350. ParticleSystem.prototype._reset = function () {
  58351. this._resetEffect();
  58352. };
  58353. ParticleSystem.prototype._resetEffect = function () {
  58354. if (this._vertexBuffer) {
  58355. this._vertexBuffer.dispose();
  58356. this._vertexBuffer = null;
  58357. }
  58358. if (this._spriteBuffer) {
  58359. this._spriteBuffer.dispose();
  58360. this._spriteBuffer = null;
  58361. }
  58362. this._createVertexBuffers();
  58363. };
  58364. ParticleSystem.prototype._createVertexBuffers = function () {
  58365. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  58366. if (this._isAnimationSheetEnabled) {
  58367. this._vertexBufferSize += 1;
  58368. }
  58369. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58370. this._vertexBufferSize += 3;
  58371. }
  58372. if (this._useRampGradients) {
  58373. this._vertexBufferSize += 4;
  58374. }
  58375. var engine = this._scene.getEngine();
  58376. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  58377. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  58378. var dataOffset = 0;
  58379. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58380. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  58381. dataOffset += 3;
  58382. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58383. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  58384. dataOffset += 4;
  58385. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58386. this._vertexBuffers["angle"] = options;
  58387. dataOffset += 1;
  58388. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58389. this._vertexBuffers["size"] = size;
  58390. dataOffset += 2;
  58391. if (this._isAnimationSheetEnabled) {
  58392. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58393. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  58394. dataOffset += 1;
  58395. }
  58396. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58397. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58398. this._vertexBuffers["direction"] = directionBuffer;
  58399. dataOffset += 3;
  58400. }
  58401. if (this._useRampGradients) {
  58402. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58403. this._vertexBuffers["remapData"] = rampDataBuffer;
  58404. dataOffset += 4;
  58405. }
  58406. var offsets;
  58407. if (this._useInstancing) {
  58408. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  58409. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  58410. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  58411. }
  58412. else {
  58413. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58414. dataOffset += 2;
  58415. }
  58416. this._vertexBuffers["offset"] = offsets;
  58417. };
  58418. ParticleSystem.prototype._createIndexBuffer = function () {
  58419. if (this._useInstancing) {
  58420. return;
  58421. }
  58422. var indices = [];
  58423. var index = 0;
  58424. for (var count = 0; count < this._capacity; count++) {
  58425. indices.push(index);
  58426. indices.push(index + 1);
  58427. indices.push(index + 2);
  58428. indices.push(index);
  58429. indices.push(index + 2);
  58430. indices.push(index + 3);
  58431. index += 4;
  58432. }
  58433. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  58434. };
  58435. /**
  58436. * Gets the maximum number of particles active at the same time.
  58437. * @returns The max number of active particles.
  58438. */
  58439. ParticleSystem.prototype.getCapacity = function () {
  58440. return this._capacity;
  58441. };
  58442. /**
  58443. * Gets whether there are still active particles in the system.
  58444. * @returns True if it is alive, otherwise false.
  58445. */
  58446. ParticleSystem.prototype.isAlive = function () {
  58447. return this._alive;
  58448. };
  58449. /**
  58450. * Gets if the system has been started. (Note: this will still be true after stop is called)
  58451. * @returns True if it has been started, otherwise false.
  58452. */
  58453. ParticleSystem.prototype.isStarted = function () {
  58454. return this._started;
  58455. };
  58456. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  58457. var _this = this;
  58458. this._subEmitters = new Array();
  58459. if (this.subEmitters) {
  58460. this.subEmitters.forEach(function (subEmitter) {
  58461. if (subEmitter instanceof ParticleSystem) {
  58462. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  58463. }
  58464. else if (subEmitter instanceof BABYLON.SubEmitter) {
  58465. _this._subEmitters.push([subEmitter]);
  58466. }
  58467. else if (subEmitter instanceof Array) {
  58468. _this._subEmitters.push(subEmitter);
  58469. }
  58470. });
  58471. }
  58472. };
  58473. /**
  58474. * Starts the particle system and begins to emit
  58475. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  58476. */
  58477. ParticleSystem.prototype.start = function (delay) {
  58478. var _this = this;
  58479. if (delay === void 0) { delay = this.startDelay; }
  58480. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  58481. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  58482. }
  58483. if (delay) {
  58484. setTimeout(function () {
  58485. _this.start(0);
  58486. }, delay);
  58487. return;
  58488. }
  58489. // Convert the subEmitters field to the constant type field _subEmitters
  58490. this._prepareSubEmitterInternalArray();
  58491. this._started = true;
  58492. this._stopped = false;
  58493. this._actualFrame = 0;
  58494. if (this._subEmitters && this._subEmitters.length != 0) {
  58495. this.activeSubSystems = new Array();
  58496. }
  58497. if (this.preWarmCycles) {
  58498. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58499. this.emitter.computeWorldMatrix(true);
  58500. }
  58501. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58502. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58503. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58504. setTimeout(function () {
  58505. for (var index = 0; index < _this.preWarmCycles; index++) {
  58506. _this.animate(true);
  58507. noiseTextureAsProcedural_1.render();
  58508. }
  58509. });
  58510. });
  58511. }
  58512. else {
  58513. for (var index = 0; index < this.preWarmCycles; index++) {
  58514. this.animate(true);
  58515. }
  58516. }
  58517. }
  58518. // Animations
  58519. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  58520. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  58521. }
  58522. };
  58523. /**
  58524. * Stops the particle system.
  58525. * @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.
  58526. */
  58527. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58528. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58529. this._stopped = true;
  58530. if (stopSubEmitters) {
  58531. this._stopSubEmitters();
  58532. }
  58533. };
  58534. // animation sheet
  58535. /**
  58536. * Remove all active particles
  58537. */
  58538. ParticleSystem.prototype.reset = function () {
  58539. this._stockParticles = [];
  58540. this._particles = [];
  58541. };
  58542. /**
  58543. * @hidden (for internal use only)
  58544. */
  58545. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  58546. var offset = index * this._vertexBufferSize;
  58547. this._vertexData[offset++] = particle.position.x;
  58548. this._vertexData[offset++] = particle.position.y;
  58549. this._vertexData[offset++] = particle.position.z;
  58550. this._vertexData[offset++] = particle.color.r;
  58551. this._vertexData[offset++] = particle.color.g;
  58552. this._vertexData[offset++] = particle.color.b;
  58553. this._vertexData[offset++] = particle.color.a;
  58554. this._vertexData[offset++] = particle.angle;
  58555. this._vertexData[offset++] = particle.scale.x * particle.size;
  58556. this._vertexData[offset++] = particle.scale.y * particle.size;
  58557. if (this._isAnimationSheetEnabled) {
  58558. this._vertexData[offset++] = particle.cellIndex;
  58559. }
  58560. if (!this._isBillboardBased) {
  58561. if (particle._initialDirection) {
  58562. this._vertexData[offset++] = particle._initialDirection.x;
  58563. this._vertexData[offset++] = particle._initialDirection.y;
  58564. this._vertexData[offset++] = particle._initialDirection.z;
  58565. }
  58566. else {
  58567. this._vertexData[offset++] = particle.direction.x;
  58568. this._vertexData[offset++] = particle.direction.y;
  58569. this._vertexData[offset++] = particle.direction.z;
  58570. }
  58571. }
  58572. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58573. this._vertexData[offset++] = particle.direction.x;
  58574. this._vertexData[offset++] = particle.direction.y;
  58575. this._vertexData[offset++] = particle.direction.z;
  58576. }
  58577. if (this._useRampGradients) {
  58578. this._vertexData[offset++] = particle.remapData.x;
  58579. this._vertexData[offset++] = particle.remapData.y;
  58580. this._vertexData[offset++] = particle.remapData.z;
  58581. this._vertexData[offset++] = particle.remapData.w;
  58582. }
  58583. if (!this._useInstancing) {
  58584. if (this._isAnimationSheetEnabled) {
  58585. if (offsetX === 0)
  58586. offsetX = this._epsilon;
  58587. else if (offsetX === 1)
  58588. offsetX = 1 - this._epsilon;
  58589. if (offsetY === 0)
  58590. offsetY = this._epsilon;
  58591. else if (offsetY === 1)
  58592. offsetY = 1 - this._epsilon;
  58593. }
  58594. this._vertexData[offset++] = offsetX;
  58595. this._vertexData[offset++] = offsetY;
  58596. }
  58597. };
  58598. ParticleSystem.prototype._stopSubEmitters = function () {
  58599. if (!this.activeSubSystems) {
  58600. return;
  58601. }
  58602. this.activeSubSystems.forEach(function (subSystem) {
  58603. subSystem.stop(true);
  58604. });
  58605. this.activeSubSystems = new Array();
  58606. };
  58607. ParticleSystem.prototype._removeFromRoot = function () {
  58608. if (!this._rootParticleSystem) {
  58609. return;
  58610. }
  58611. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  58612. if (index !== -1) {
  58613. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  58614. }
  58615. this._rootParticleSystem = null;
  58616. };
  58617. // End of sub system methods
  58618. ParticleSystem.prototype._update = function (newParticles) {
  58619. var _this = this;
  58620. // Update current
  58621. this._alive = this._particles.length > 0;
  58622. if (this.emitter.position) {
  58623. var emitterMesh = this.emitter;
  58624. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  58625. }
  58626. else {
  58627. var emitterPosition = this.emitter;
  58628. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58629. }
  58630. this.updateFunction(this._particles);
  58631. // Add new ones
  58632. var particle;
  58633. var _loop_2 = function () {
  58634. if (this_1._particles.length === this_1._capacity) {
  58635. return "break";
  58636. }
  58637. particle = this_1._createParticle();
  58638. this_1._particles.push(particle);
  58639. // Emitter
  58640. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  58641. if (this_1.startPositionFunction) {
  58642. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58643. }
  58644. else {
  58645. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58646. }
  58647. if (this_1.startDirectionFunction) {
  58648. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58649. }
  58650. else {
  58651. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58652. }
  58653. if (emitPower === 0) {
  58654. if (!particle._initialDirection) {
  58655. particle._initialDirection = particle.direction.clone();
  58656. }
  58657. else {
  58658. particle._initialDirection.copyFrom(particle.direction);
  58659. }
  58660. }
  58661. else {
  58662. particle._initialDirection = null;
  58663. }
  58664. particle.direction.scaleInPlace(emitPower);
  58665. // Life time
  58666. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  58667. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  58668. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  58669. var factorGradient1 = currentGradient;
  58670. var factorGradient2 = nextGradient;
  58671. var lifeTime1 = factorGradient1.getFactor();
  58672. var lifeTime2 = factorGradient2.getFactor();
  58673. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  58674. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  58675. });
  58676. }
  58677. else {
  58678. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  58679. }
  58680. // Size
  58681. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  58682. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  58683. }
  58684. else {
  58685. particle._currentSizeGradient = this_1._sizeGradients[0];
  58686. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  58687. particle.size = particle._currentSize1;
  58688. if (this_1._sizeGradients.length > 1) {
  58689. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  58690. }
  58691. else {
  58692. particle._currentSize2 = particle._currentSize1;
  58693. }
  58694. }
  58695. // Size and scale
  58696. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  58697. // Adjust scale by start size
  58698. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  58699. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  58700. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  58701. if (currentGradient !== _this._currentStartSizeGradient) {
  58702. _this._currentStartSize1 = _this._currentStartSize2;
  58703. _this._currentStartSize2 = nextGradient.getFactor();
  58704. _this._currentStartSizeGradient = currentGradient;
  58705. }
  58706. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  58707. particle.scale.scaleInPlace(value);
  58708. });
  58709. }
  58710. // Angle
  58711. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  58712. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  58713. }
  58714. else {
  58715. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  58716. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  58717. particle._currentAngularSpeed1 = particle.angularSpeed;
  58718. if (this_1._angularSpeedGradients.length > 1) {
  58719. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  58720. }
  58721. else {
  58722. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  58723. }
  58724. }
  58725. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  58726. // Velocity
  58727. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  58728. particle._currentVelocityGradient = this_1._velocityGradients[0];
  58729. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  58730. if (this_1._velocityGradients.length > 1) {
  58731. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  58732. }
  58733. else {
  58734. particle._currentVelocity2 = particle._currentVelocity1;
  58735. }
  58736. }
  58737. // Limit velocity
  58738. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  58739. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  58740. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  58741. if (this_1._limitVelocityGradients.length > 1) {
  58742. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  58743. }
  58744. else {
  58745. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  58746. }
  58747. }
  58748. // Drag
  58749. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  58750. particle._currentDragGradient = this_1._dragGradients[0];
  58751. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  58752. if (this_1._dragGradients.length > 1) {
  58753. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  58754. }
  58755. else {
  58756. particle._currentDrag2 = particle._currentDrag1;
  58757. }
  58758. }
  58759. // Color
  58760. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  58761. step = BABYLON.Scalar.RandomRange(0, 1.0);
  58762. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  58763. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  58764. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  58765. }
  58766. else {
  58767. particle._currentColorGradient = this_1._colorGradients[0];
  58768. particle._currentColorGradient.getColorToRef(particle.color);
  58769. particle._currentColor1.copyFrom(particle.color);
  58770. if (this_1._colorGradients.length > 1) {
  58771. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  58772. }
  58773. else {
  58774. particle._currentColor2.copyFrom(particle.color);
  58775. }
  58776. }
  58777. // Sheet
  58778. if (this_1._isAnimationSheetEnabled) {
  58779. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  58780. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  58781. }
  58782. // Inherited Velocity
  58783. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  58784. // Ramp
  58785. if (this_1._useRampGradients) {
  58786. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  58787. }
  58788. // Noise texture coordinates
  58789. if (this_1.noiseTexture) {
  58790. if (particle._randomNoiseCoordinates1) {
  58791. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  58792. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  58793. }
  58794. else {
  58795. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58796. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58797. }
  58798. }
  58799. // Update the position of the attached sub-emitters to match their attached particle
  58800. particle._inheritParticleInfoToSubEmitters();
  58801. };
  58802. var this_1 = this, step;
  58803. for (var index = 0; index < newParticles; index++) {
  58804. var state_1 = _loop_2();
  58805. if (state_1 === "break")
  58806. break;
  58807. }
  58808. };
  58809. /** @hidden */
  58810. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  58811. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58812. if (isBillboardBased === void 0) { isBillboardBased = false; }
  58813. if (useRampGradients === void 0) { useRampGradients = false; }
  58814. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  58815. if (isAnimationSheetEnabled) {
  58816. attributeNamesOrOptions.push("cellIndex");
  58817. }
  58818. if (!isBillboardBased) {
  58819. attributeNamesOrOptions.push("direction");
  58820. }
  58821. if (useRampGradients) {
  58822. attributeNamesOrOptions.push("remapData");
  58823. }
  58824. return attributeNamesOrOptions;
  58825. };
  58826. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  58827. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58828. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  58829. if (isAnimationSheetEnabled) {
  58830. effectCreationOption.push("particlesInfos");
  58831. }
  58832. return effectCreationOption;
  58833. };
  58834. ParticleSystem.prototype._getEffect = function (blendMode) {
  58835. if (this._customEffect) {
  58836. return this._customEffect;
  58837. }
  58838. ;
  58839. var defines = [];
  58840. if (this._scene.clipPlane) {
  58841. defines.push("#define CLIPPLANE");
  58842. }
  58843. if (this._scene.clipPlane2) {
  58844. defines.push("#define CLIPPLANE2");
  58845. }
  58846. if (this._scene.clipPlane3) {
  58847. defines.push("#define CLIPPLANE3");
  58848. }
  58849. if (this._scene.clipPlane4) {
  58850. defines.push("#define CLIPPLANE4");
  58851. }
  58852. if (this._isAnimationSheetEnabled) {
  58853. defines.push("#define ANIMATESHEET");
  58854. }
  58855. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  58856. defines.push("#define BLENDMULTIPLYMODE");
  58857. }
  58858. if (this._useRampGradients) {
  58859. defines.push("#define RAMPGRADIENT");
  58860. }
  58861. if (this._isBillboardBased) {
  58862. defines.push("#define BILLBOARD");
  58863. switch (this.billboardMode) {
  58864. case ParticleSystem.BILLBOARDMODE_Y:
  58865. defines.push("#define BILLBOARDY");
  58866. break;
  58867. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  58868. defines.push("#define BILLBOARDSTRETCHED");
  58869. break;
  58870. case ParticleSystem.BILLBOARDMODE_ALL:
  58871. default:
  58872. break;
  58873. }
  58874. }
  58875. if (this._imageProcessingConfiguration) {
  58876. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  58877. defines.push(this._imageProcessingConfigurationDefines.toString());
  58878. }
  58879. // Effect
  58880. var join = defines.join("\n");
  58881. if (this._cachedDefines !== join) {
  58882. this._cachedDefines = join;
  58883. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  58884. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  58885. var samplers = ["diffuseSampler", "rampSampler"];
  58886. if (BABYLON.ImageProcessingConfiguration) {
  58887. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  58888. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  58889. }
  58890. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  58891. }
  58892. return this._effect;
  58893. };
  58894. /**
  58895. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58896. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  58897. */
  58898. ParticleSystem.prototype.animate = function (preWarmOnly) {
  58899. var _this = this;
  58900. if (preWarmOnly === void 0) { preWarmOnly = false; }
  58901. if (!this._started)
  58902. return;
  58903. if (!preWarmOnly) {
  58904. // Check
  58905. if (!this.isReady())
  58906. return;
  58907. if (this._currentRenderId === this._scene.getRenderId()) {
  58908. return;
  58909. }
  58910. this._currentRenderId = this._scene.getRenderId();
  58911. }
  58912. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  58913. // Determine the number of particles we need to create
  58914. var newParticles;
  58915. if (this.manualEmitCount > -1) {
  58916. newParticles = this.manualEmitCount;
  58917. this._newPartsExcess = 0;
  58918. this.manualEmitCount = 0;
  58919. }
  58920. else {
  58921. var rate_1 = this.emitRate;
  58922. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  58923. var ratio = this._actualFrame / this.targetStopDuration;
  58924. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  58925. if (currentGradient !== _this._currentEmitRateGradient) {
  58926. _this._currentEmitRate1 = _this._currentEmitRate2;
  58927. _this._currentEmitRate2 = nextGradient.getFactor();
  58928. _this._currentEmitRateGradient = currentGradient;
  58929. }
  58930. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  58931. });
  58932. }
  58933. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  58934. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  58935. }
  58936. if (this._newPartsExcess > 1.0) {
  58937. newParticles += this._newPartsExcess >> 0;
  58938. this._newPartsExcess -= this._newPartsExcess >> 0;
  58939. }
  58940. this._alive = false;
  58941. if (!this._stopped) {
  58942. this._actualFrame += this._scaledUpdateSpeed;
  58943. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  58944. this.stop();
  58945. }
  58946. else {
  58947. newParticles = 0;
  58948. }
  58949. this._update(newParticles);
  58950. // Stopped?
  58951. if (this._stopped) {
  58952. if (!this._alive) {
  58953. this._started = false;
  58954. if (this.onAnimationEnd) {
  58955. this.onAnimationEnd();
  58956. }
  58957. if (this.disposeOnStop) {
  58958. this._scene._toBeDisposed.push(this);
  58959. }
  58960. }
  58961. }
  58962. if (!preWarmOnly) {
  58963. // Update VBO
  58964. var offset = 0;
  58965. for (var index = 0; index < this._particles.length; index++) {
  58966. var particle = this._particles[index];
  58967. this._appendParticleVertices(offset, particle);
  58968. offset += this._useInstancing ? 1 : 4;
  58969. }
  58970. if (this._vertexBuffer) {
  58971. this._vertexBuffer.update(this._vertexData);
  58972. }
  58973. }
  58974. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  58975. this.stop();
  58976. }
  58977. };
  58978. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  58979. this._appendParticleVertex(offset++, particle, 0, 0);
  58980. if (!this._useInstancing) {
  58981. this._appendParticleVertex(offset++, particle, 1, 0);
  58982. this._appendParticleVertex(offset++, particle, 1, 1);
  58983. this._appendParticleVertex(offset++, particle, 0, 1);
  58984. }
  58985. };
  58986. /**
  58987. * Rebuilds the particle system.
  58988. */
  58989. ParticleSystem.prototype.rebuild = function () {
  58990. this._createIndexBuffer();
  58991. if (this._vertexBuffer) {
  58992. this._vertexBuffer._rebuild();
  58993. }
  58994. };
  58995. /**
  58996. * Is this system ready to be used/rendered
  58997. * @return true if the system is ready
  58998. */
  58999. ParticleSystem.prototype.isReady = function () {
  59000. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59001. return false;
  59002. }
  59003. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59004. if (!this._getEffect(this.blendMode).isReady()) {
  59005. return false;
  59006. }
  59007. }
  59008. else {
  59009. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  59010. return false;
  59011. }
  59012. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  59013. return false;
  59014. }
  59015. }
  59016. return true;
  59017. };
  59018. ParticleSystem.prototype._render = function (blendMode) {
  59019. var effect = this._getEffect(blendMode);
  59020. var engine = this._scene.getEngine();
  59021. // Render
  59022. engine.enableEffect(effect);
  59023. var viewMatrix = this._scene.getViewMatrix();
  59024. effect.setTexture("diffuseSampler", this.particleTexture);
  59025. effect.setMatrix("view", viewMatrix);
  59026. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  59027. if (this._isAnimationSheetEnabled && this.particleTexture) {
  59028. var baseSize = this.particleTexture.getBaseSize();
  59029. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  59030. }
  59031. effect.setVector2("translationPivot", this.translationPivot);
  59032. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  59033. if (this._isBillboardBased) {
  59034. var camera = this._scene.activeCamera;
  59035. effect.setVector3("eyePosition", camera.globalPosition);
  59036. }
  59037. if (this._rampGradientsTexture) {
  59038. effect.setTexture("rampSampler", this._rampGradientsTexture);
  59039. }
  59040. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  59041. var invView = viewMatrix.clone();
  59042. invView.invert();
  59043. effect.setMatrix("invView", invView);
  59044. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  59045. }
  59046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  59047. // image processing
  59048. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  59049. this._imageProcessingConfiguration.bind(effect);
  59050. }
  59051. // Draw order
  59052. switch (blendMode) {
  59053. case ParticleSystem.BLENDMODE_ADD:
  59054. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  59055. break;
  59056. case ParticleSystem.BLENDMODE_ONEONE:
  59057. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  59058. break;
  59059. case ParticleSystem.BLENDMODE_STANDARD:
  59060. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59061. break;
  59062. case ParticleSystem.BLENDMODE_MULTIPLY:
  59063. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  59064. break;
  59065. }
  59066. if (this._useInstancing) {
  59067. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  59068. }
  59069. else {
  59070. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  59071. }
  59072. return this._particles.length;
  59073. };
  59074. /**
  59075. * Renders the particle system in its current state.
  59076. * @returns the current number of particles
  59077. */
  59078. ParticleSystem.prototype.render = function () {
  59079. // Check
  59080. if (!this.isReady() || !this._particles.length) {
  59081. return 0;
  59082. }
  59083. var engine = this._scene.getEngine();
  59084. engine.setState(false);
  59085. if (this.forceDepthWrite) {
  59086. engine.setDepthWrite(true);
  59087. }
  59088. var outparticles = 0;
  59089. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59090. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  59091. }
  59092. outparticles = this._render(this.blendMode);
  59093. engine.unbindInstanceAttributes();
  59094. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59095. return outparticles;
  59096. };
  59097. /**
  59098. * Disposes the particle system and free the associated resources
  59099. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  59100. */
  59101. ParticleSystem.prototype.dispose = function (disposeTexture) {
  59102. if (disposeTexture === void 0) { disposeTexture = true; }
  59103. if (this._vertexBuffer) {
  59104. this._vertexBuffer.dispose();
  59105. this._vertexBuffer = null;
  59106. }
  59107. if (this._spriteBuffer) {
  59108. this._spriteBuffer.dispose();
  59109. this._spriteBuffer = null;
  59110. }
  59111. if (this._indexBuffer) {
  59112. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59113. this._indexBuffer = null;
  59114. }
  59115. if (disposeTexture && this.particleTexture) {
  59116. this.particleTexture.dispose();
  59117. this.particleTexture = null;
  59118. }
  59119. if (disposeTexture && this.noiseTexture) {
  59120. this.noiseTexture.dispose();
  59121. this.noiseTexture = null;
  59122. }
  59123. if (this._rampGradientsTexture) {
  59124. this._rampGradientsTexture.dispose();
  59125. this._rampGradientsTexture = null;
  59126. }
  59127. this._removeFromRoot();
  59128. if (this._subEmitters && this._subEmitters.length) {
  59129. for (var index = 0; index < this._subEmitters.length; index++) {
  59130. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  59131. var subEmitter = _a[_i];
  59132. subEmitter.dispose();
  59133. }
  59134. }
  59135. this._subEmitters = [];
  59136. this.subEmitters = [];
  59137. }
  59138. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  59139. this.emitter.dispose(true);
  59140. }
  59141. // Remove from scene
  59142. var index = this._scene.particleSystems.indexOf(this);
  59143. if (index > -1) {
  59144. this._scene.particleSystems.splice(index, 1);
  59145. }
  59146. this._scene._activeParticleSystems.dispose();
  59147. // Callback
  59148. this.onDisposeObservable.notifyObservers(this);
  59149. this.onDisposeObservable.clear();
  59150. this.reset();
  59151. };
  59152. // Clone
  59153. /**
  59154. * Clones the particle system.
  59155. * @param name The name of the cloned object
  59156. * @param newEmitter The new emitter to use
  59157. * @returns the cloned particle system
  59158. */
  59159. ParticleSystem.prototype.clone = function (name, newEmitter) {
  59160. var custom = null;
  59161. var program = null;
  59162. if (this.customShader != null) {
  59163. program = this.customShader;
  59164. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59165. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59166. }
  59167. else if (this._customEffect) {
  59168. custom = this._customEffect;
  59169. }
  59170. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  59171. result.customShader = program;
  59172. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  59173. if (newEmitter === undefined) {
  59174. newEmitter = this.emitter;
  59175. }
  59176. result.noiseTexture = this.noiseTexture;
  59177. result.emitter = newEmitter;
  59178. if (this.particleTexture) {
  59179. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  59180. }
  59181. // Clone gradients
  59182. if (this._colorGradients) {
  59183. this._colorGradients.forEach(function (v) {
  59184. result.addColorGradient(v.gradient, v.color1, v.color2);
  59185. });
  59186. }
  59187. if (this._dragGradients) {
  59188. this._dragGradients.forEach(function (v) {
  59189. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  59190. });
  59191. }
  59192. if (this._angularSpeedGradients) {
  59193. this._angularSpeedGradients.forEach(function (v) {
  59194. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  59195. });
  59196. }
  59197. if (this._emitRateGradients) {
  59198. this._emitRateGradients.forEach(function (v) {
  59199. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  59200. });
  59201. }
  59202. if (this._lifeTimeGradients) {
  59203. this._lifeTimeGradients.forEach(function (v) {
  59204. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  59205. });
  59206. }
  59207. if (this._limitVelocityGradients) {
  59208. this._limitVelocityGradients.forEach(function (v) {
  59209. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  59210. });
  59211. }
  59212. if (this._sizeGradients) {
  59213. this._sizeGradients.forEach(function (v) {
  59214. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  59215. });
  59216. }
  59217. if (this._startSizeGradients) {
  59218. this._startSizeGradients.forEach(function (v) {
  59219. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  59220. });
  59221. }
  59222. if (this._velocityGradients) {
  59223. this._velocityGradients.forEach(function (v) {
  59224. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  59225. });
  59226. }
  59227. if (this._rampGradients) {
  59228. this._rampGradients.forEach(function (v) {
  59229. result.addRampGradient(v.gradient, v.color);
  59230. });
  59231. }
  59232. if (this._colorRemapGradients) {
  59233. this._colorRemapGradients.forEach(function (v) {
  59234. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  59235. });
  59236. }
  59237. if (this._alphaRemapGradients) {
  59238. this._alphaRemapGradients.forEach(function (v) {
  59239. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  59240. });
  59241. }
  59242. if (!this.preventAutoStart) {
  59243. result.start();
  59244. }
  59245. return result;
  59246. };
  59247. /**
  59248. * Serializes the particle system to a JSON object.
  59249. * @returns the JSON object
  59250. */
  59251. ParticleSystem.prototype.serialize = function () {
  59252. var serializationObject = {};
  59253. ParticleSystem._Serialize(serializationObject, this);
  59254. serializationObject.textureMask = this.textureMask.asArray();
  59255. serializationObject.customShader = this.customShader;
  59256. serializationObject.preventAutoStart = this.preventAutoStart;
  59257. // SubEmitters
  59258. if (this.subEmitters) {
  59259. serializationObject.subEmitters = [];
  59260. if (!this._subEmitters) {
  59261. this._prepareSubEmitterInternalArray();
  59262. }
  59263. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  59264. var subs = _a[_i];
  59265. var cell = [];
  59266. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  59267. var sub = subs_1[_b];
  59268. cell.push(sub.serialize());
  59269. }
  59270. serializationObject.subEmitters.push(cell);
  59271. }
  59272. }
  59273. return serializationObject;
  59274. };
  59275. /** @hidden */
  59276. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  59277. serializationObject.name = particleSystem.name;
  59278. serializationObject.id = particleSystem.id;
  59279. serializationObject.capacity = particleSystem.getCapacity();
  59280. // Emitter
  59281. if (particleSystem.emitter.position) {
  59282. var emitterMesh = particleSystem.emitter;
  59283. serializationObject.emitterId = emitterMesh.id;
  59284. }
  59285. else {
  59286. var emitterPosition = particleSystem.emitter;
  59287. serializationObject.emitter = emitterPosition.asArray();
  59288. }
  59289. // Emitter
  59290. if (particleSystem.particleEmitterType) {
  59291. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  59292. }
  59293. if (particleSystem.particleTexture) {
  59294. serializationObject.textureName = particleSystem.particleTexture.name;
  59295. serializationObject.invertY = particleSystem.particleTexture._invertY;
  59296. }
  59297. // Animations
  59298. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  59299. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  59300. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  59301. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  59302. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  59303. // Particle system
  59304. serializationObject.startDelay = particleSystem.startDelay;
  59305. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  59306. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  59307. serializationObject.billboardMode = particleSystem.billboardMode;
  59308. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  59309. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  59310. serializationObject.minSize = particleSystem.minSize;
  59311. serializationObject.maxSize = particleSystem.maxSize;
  59312. serializationObject.minScaleX = particleSystem.minScaleX;
  59313. serializationObject.maxScaleX = particleSystem.maxScaleX;
  59314. serializationObject.minScaleY = particleSystem.minScaleY;
  59315. serializationObject.maxScaleY = particleSystem.maxScaleY;
  59316. serializationObject.minEmitPower = particleSystem.minEmitPower;
  59317. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  59318. serializationObject.minLifeTime = particleSystem.minLifeTime;
  59319. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  59320. serializationObject.emitRate = particleSystem.emitRate;
  59321. serializationObject.gravity = particleSystem.gravity.asArray();
  59322. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  59323. serializationObject.color1 = particleSystem.color1.asArray();
  59324. serializationObject.color2 = particleSystem.color2.asArray();
  59325. serializationObject.colorDead = particleSystem.colorDead.asArray();
  59326. serializationObject.updateSpeed = particleSystem.updateSpeed;
  59327. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  59328. serializationObject.blendMode = particleSystem.blendMode;
  59329. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  59330. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  59331. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  59332. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  59333. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  59334. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  59335. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  59336. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  59337. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  59338. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  59339. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  59340. var colorGradients = particleSystem.getColorGradients();
  59341. if (colorGradients) {
  59342. serializationObject.colorGradients = [];
  59343. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  59344. var colorGradient = colorGradients_1[_i];
  59345. var serializedGradient = {
  59346. gradient: colorGradient.gradient,
  59347. color1: colorGradient.color1.asArray()
  59348. };
  59349. if (colorGradient.color2) {
  59350. serializedGradient.color2 = colorGradient.color2.asArray();
  59351. }
  59352. serializationObject.colorGradients.push(serializedGradient);
  59353. }
  59354. }
  59355. var rampGradients = particleSystem.getRampGradients();
  59356. if (rampGradients) {
  59357. serializationObject.rampGradients = [];
  59358. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  59359. var rampGradient = rampGradients_1[_a];
  59360. var serializedGradient = {
  59361. gradient: rampGradient.gradient,
  59362. color: rampGradient.color.asArray()
  59363. };
  59364. serializationObject.rampGradients.push(serializedGradient);
  59365. }
  59366. serializationObject.useRampGradients = particleSystem.useRampGradients;
  59367. }
  59368. var colorRemapGradients = particleSystem.getColorRemapGradients();
  59369. if (colorRemapGradients) {
  59370. serializationObject.colorRemapGradients = [];
  59371. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  59372. var colorRemapGradient = colorRemapGradients_1[_b];
  59373. var serializedGradient = {
  59374. gradient: colorRemapGradient.gradient,
  59375. factor1: colorRemapGradient.factor1
  59376. };
  59377. if (colorRemapGradient.factor2 !== undefined) {
  59378. serializedGradient.factor2 = colorRemapGradient.factor2;
  59379. }
  59380. serializationObject.colorRemapGradients.push(serializedGradient);
  59381. }
  59382. }
  59383. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  59384. if (alphaRemapGradients) {
  59385. serializationObject.alphaRemapGradients = [];
  59386. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  59387. var alphaRemapGradient = alphaRemapGradients_1[_c];
  59388. var serializedGradient = {
  59389. gradient: alphaRemapGradient.gradient,
  59390. factor1: alphaRemapGradient.factor1
  59391. };
  59392. if (alphaRemapGradient.factor2 !== undefined) {
  59393. serializedGradient.factor2 = alphaRemapGradient.factor2;
  59394. }
  59395. serializationObject.alphaRemapGradients.push(serializedGradient);
  59396. }
  59397. }
  59398. var sizeGradients = particleSystem.getSizeGradients();
  59399. if (sizeGradients) {
  59400. serializationObject.sizeGradients = [];
  59401. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  59402. var sizeGradient = sizeGradients_1[_d];
  59403. var serializedGradient = {
  59404. gradient: sizeGradient.gradient,
  59405. factor1: sizeGradient.factor1
  59406. };
  59407. if (sizeGradient.factor2 !== undefined) {
  59408. serializedGradient.factor2 = sizeGradient.factor2;
  59409. }
  59410. serializationObject.sizeGradients.push(serializedGradient);
  59411. }
  59412. }
  59413. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  59414. if (angularSpeedGradients) {
  59415. serializationObject.angularSpeedGradients = [];
  59416. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  59417. var angularSpeedGradient = angularSpeedGradients_1[_e];
  59418. var serializedGradient = {
  59419. gradient: angularSpeedGradient.gradient,
  59420. factor1: angularSpeedGradient.factor1
  59421. };
  59422. if (angularSpeedGradient.factor2 !== undefined) {
  59423. serializedGradient.factor2 = angularSpeedGradient.factor2;
  59424. }
  59425. serializationObject.angularSpeedGradients.push(serializedGradient);
  59426. }
  59427. }
  59428. var velocityGradients = particleSystem.getVelocityGradients();
  59429. if (velocityGradients) {
  59430. serializationObject.velocityGradients = [];
  59431. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  59432. var velocityGradient = velocityGradients_1[_f];
  59433. var serializedGradient = {
  59434. gradient: velocityGradient.gradient,
  59435. factor1: velocityGradient.factor1
  59436. };
  59437. if (velocityGradient.factor2 !== undefined) {
  59438. serializedGradient.factor2 = velocityGradient.factor2;
  59439. }
  59440. serializationObject.velocityGradients.push(serializedGradient);
  59441. }
  59442. }
  59443. var dragGradients = particleSystem.getDragGradients();
  59444. if (dragGradients) {
  59445. serializationObject.dragyGradients = [];
  59446. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  59447. var dragGradient = dragGradients_1[_g];
  59448. var serializedGradient = {
  59449. gradient: dragGradient.gradient,
  59450. factor1: dragGradient.factor1
  59451. };
  59452. if (dragGradient.factor2 !== undefined) {
  59453. serializedGradient.factor2 = dragGradient.factor2;
  59454. }
  59455. serializationObject.dragGradients.push(serializedGradient);
  59456. }
  59457. }
  59458. var emitRateGradients = particleSystem.getEmitRateGradients();
  59459. if (emitRateGradients) {
  59460. serializationObject.emitRateGradients = [];
  59461. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  59462. var emitRateGradient = emitRateGradients_1[_h];
  59463. var serializedGradient = {
  59464. gradient: emitRateGradient.gradient,
  59465. factor1: emitRateGradient.factor1
  59466. };
  59467. if (emitRateGradient.factor2 !== undefined) {
  59468. serializedGradient.factor2 = emitRateGradient.factor2;
  59469. }
  59470. serializationObject.emitRateGradients.push(serializedGradient);
  59471. }
  59472. }
  59473. var startSizeGradients = particleSystem.getStartSizeGradients();
  59474. if (startSizeGradients) {
  59475. serializationObject.startSizeGradients = [];
  59476. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  59477. var startSizeGradient = startSizeGradients_1[_j];
  59478. var serializedGradient = {
  59479. gradient: startSizeGradient.gradient,
  59480. factor1: startSizeGradient.factor1
  59481. };
  59482. if (startSizeGradient.factor2 !== undefined) {
  59483. serializedGradient.factor2 = startSizeGradient.factor2;
  59484. }
  59485. serializationObject.startSizeGradients.push(serializedGradient);
  59486. }
  59487. }
  59488. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  59489. if (lifeTimeGradients) {
  59490. serializationObject.lifeTimeGradients = [];
  59491. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  59492. var lifeTimeGradient = lifeTimeGradients_1[_k];
  59493. var serializedGradient = {
  59494. gradient: lifeTimeGradient.gradient,
  59495. factor1: lifeTimeGradient.factor1
  59496. };
  59497. if (lifeTimeGradient.factor2 !== undefined) {
  59498. serializedGradient.factor2 = lifeTimeGradient.factor2;
  59499. }
  59500. serializationObject.lifeTimeGradients.push(serializedGradient);
  59501. }
  59502. }
  59503. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  59504. if (limitVelocityGradients) {
  59505. serializationObject.limitVelocityGradients = [];
  59506. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  59507. var limitVelocityGradient = limitVelocityGradients_1[_l];
  59508. var serializedGradient = {
  59509. gradient: limitVelocityGradient.gradient,
  59510. factor1: limitVelocityGradient.factor1
  59511. };
  59512. if (limitVelocityGradient.factor2 !== undefined) {
  59513. serializedGradient.factor2 = limitVelocityGradient.factor2;
  59514. }
  59515. serializationObject.limitVelocityGradients.push(serializedGradient);
  59516. }
  59517. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  59518. }
  59519. if (particleSystem.noiseTexture) {
  59520. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  59521. }
  59522. };
  59523. /** @hidden */
  59524. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  59525. // Texture
  59526. if (parsedParticleSystem.textureName) {
  59527. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  59528. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  59529. }
  59530. // Emitter
  59531. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  59532. particleSystem.emitter = BABYLON.Vector3.Zero();
  59533. }
  59534. else if (parsedParticleSystem.emitterId) {
  59535. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  59536. }
  59537. else {
  59538. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  59539. }
  59540. // Misc.
  59541. if (parsedParticleSystem.renderingGroupId !== undefined) {
  59542. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  59543. }
  59544. if (parsedParticleSystem.isBillboardBased !== undefined) {
  59545. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  59546. }
  59547. if (parsedParticleSystem.billboardMode !== undefined) {
  59548. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  59549. }
  59550. // Animations
  59551. if (parsedParticleSystem.animations) {
  59552. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  59553. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  59554. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59555. }
  59556. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  59557. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  59558. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  59559. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  59560. }
  59561. if (parsedParticleSystem.autoAnimate) {
  59562. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  59563. }
  59564. // Particle system
  59565. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  59566. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  59567. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  59568. particleSystem.minSize = parsedParticleSystem.minSize;
  59569. particleSystem.maxSize = parsedParticleSystem.maxSize;
  59570. if (parsedParticleSystem.minScaleX) {
  59571. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  59572. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  59573. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  59574. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  59575. }
  59576. if (parsedParticleSystem.preWarmCycles !== undefined) {
  59577. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  59578. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  59579. }
  59580. if (parsedParticleSystem.minInitialRotation !== undefined) {
  59581. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  59582. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  59583. }
  59584. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  59585. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  59586. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  59587. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  59588. particleSystem.emitRate = parsedParticleSystem.emitRate;
  59589. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  59590. if (parsedParticleSystem.noiseStrength) {
  59591. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  59592. }
  59593. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  59594. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  59595. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  59596. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  59597. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  59598. particleSystem.blendMode = parsedParticleSystem.blendMode;
  59599. if (parsedParticleSystem.colorGradients) {
  59600. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  59601. var colorGradient = _a[_i];
  59602. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  59603. }
  59604. }
  59605. if (parsedParticleSystem.rampGradients) {
  59606. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  59607. var rampGradient = _c[_b];
  59608. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  59609. }
  59610. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  59611. }
  59612. if (parsedParticleSystem.colorRemapGradients) {
  59613. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  59614. var colorRemapGradient = _e[_d];
  59615. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  59616. }
  59617. }
  59618. if (parsedParticleSystem.alphaRemapGradients) {
  59619. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  59620. var alphaRemapGradient = _g[_f];
  59621. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  59622. }
  59623. }
  59624. if (parsedParticleSystem.sizeGradients) {
  59625. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  59626. var sizeGradient = _j[_h];
  59627. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59628. }
  59629. }
  59630. if (parsedParticleSystem.sizeGradients) {
  59631. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  59632. var sizeGradient = _l[_k];
  59633. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59634. }
  59635. }
  59636. if (parsedParticleSystem.angularSpeedGradients) {
  59637. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  59638. var angularSpeedGradient = _o[_m];
  59639. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  59640. }
  59641. }
  59642. if (parsedParticleSystem.velocityGradients) {
  59643. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  59644. var velocityGradient = _q[_p];
  59645. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  59646. }
  59647. }
  59648. if (parsedParticleSystem.dragGradients) {
  59649. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  59650. var dragGradient = _s[_r];
  59651. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  59652. }
  59653. }
  59654. if (parsedParticleSystem.emitRateGradients) {
  59655. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  59656. var emitRateGradient = _u[_t];
  59657. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  59658. }
  59659. }
  59660. if (parsedParticleSystem.startSizeGradients) {
  59661. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  59662. var startSizeGradient = _w[_v];
  59663. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  59664. }
  59665. }
  59666. if (parsedParticleSystem.lifeTimeGradients) {
  59667. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  59668. var lifeTimeGradient = _y[_x];
  59669. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  59670. }
  59671. }
  59672. if (parsedParticleSystem.limitVelocityGradients) {
  59673. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  59674. var limitVelocityGradient = _0[_z];
  59675. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  59676. }
  59677. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  59678. }
  59679. if (parsedParticleSystem.noiseTexture) {
  59680. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  59681. }
  59682. // Emitter
  59683. var emitterType;
  59684. if (parsedParticleSystem.particleEmitterType) {
  59685. switch (parsedParticleSystem.particleEmitterType.type) {
  59686. case "SphereParticleEmitter":
  59687. emitterType = new BABYLON.SphereParticleEmitter();
  59688. break;
  59689. case "SphereDirectedParticleEmitter":
  59690. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  59691. break;
  59692. case "ConeEmitter":
  59693. case "ConeParticleEmitter":
  59694. emitterType = new BABYLON.ConeParticleEmitter();
  59695. break;
  59696. case "CylinderParticleEmitter":
  59697. emitterType = new BABYLON.CylinderParticleEmitter();
  59698. break;
  59699. case "HemisphericParticleEmitter":
  59700. emitterType = new BABYLON.HemisphericParticleEmitter();
  59701. break;
  59702. case "BoxEmitter":
  59703. case "BoxParticleEmitter":
  59704. default:
  59705. emitterType = new BABYLON.BoxParticleEmitter();
  59706. break;
  59707. }
  59708. emitterType.parse(parsedParticleSystem.particleEmitterType);
  59709. }
  59710. else {
  59711. emitterType = new BABYLON.BoxParticleEmitter();
  59712. emitterType.parse(parsedParticleSystem);
  59713. }
  59714. particleSystem.particleEmitterType = emitterType;
  59715. // Animation sheet
  59716. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  59717. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  59718. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  59719. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  59720. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  59721. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  59722. };
  59723. /**
  59724. * Parses a JSON object to create a particle system.
  59725. * @param parsedParticleSystem The JSON object to parse
  59726. * @param scene The scene to create the particle system in
  59727. * @param rootUrl The root url to use to load external dependencies like texture
  59728. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  59729. * @returns the Parsed particle system
  59730. */
  59731. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  59732. if (doNotStart === void 0) { doNotStart = false; }
  59733. var name = parsedParticleSystem.name;
  59734. var custom = null;
  59735. var program = null;
  59736. if (parsedParticleSystem.customShader) {
  59737. program = parsedParticleSystem.customShader;
  59738. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59739. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59740. }
  59741. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  59742. particleSystem.customShader = program;
  59743. if (parsedParticleSystem.id) {
  59744. particleSystem.id = parsedParticleSystem.id;
  59745. }
  59746. // SubEmitters
  59747. if (parsedParticleSystem.subEmitters) {
  59748. particleSystem.subEmitters = [];
  59749. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  59750. var cell = _a[_i];
  59751. var cellArray = [];
  59752. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  59753. var sub = cell_1[_b];
  59754. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  59755. }
  59756. particleSystem.subEmitters.push(cellArray);
  59757. }
  59758. }
  59759. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  59760. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  59761. // Auto start
  59762. if (parsedParticleSystem.preventAutoStart) {
  59763. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  59764. }
  59765. if (!doNotStart && !particleSystem.preventAutoStart) {
  59766. particleSystem.start();
  59767. }
  59768. return particleSystem;
  59769. };
  59770. /**
  59771. * Billboard mode will only apply to Y axis
  59772. */
  59773. ParticleSystem.BILLBOARDMODE_Y = 2;
  59774. /**
  59775. * Billboard mode will apply to all axes
  59776. */
  59777. ParticleSystem.BILLBOARDMODE_ALL = 7;
  59778. /**
  59779. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  59780. */
  59781. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  59782. return ParticleSystem;
  59783. }(BABYLON.BaseParticleSystem));
  59784. BABYLON.ParticleSystem = ParticleSystem;
  59785. })(BABYLON || (BABYLON = {}));
  59786. //# sourceMappingURL=babylon.particleSystem.js.map
  59787. var BABYLON;
  59788. (function (BABYLON) {
  59789. /**
  59790. * Particle emitter emitting particles from the inside of a box.
  59791. * It emits the particles randomly between 2 given directions.
  59792. */
  59793. var BoxParticleEmitter = /** @class */ (function () {
  59794. /**
  59795. * Creates a new instance BoxParticleEmitter
  59796. */
  59797. function BoxParticleEmitter() {
  59798. /**
  59799. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59800. */
  59801. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59802. /**
  59803. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59804. */
  59805. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59806. /**
  59807. * 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.
  59808. */
  59809. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  59810. /**
  59811. * 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.
  59812. */
  59813. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  59814. }
  59815. /**
  59816. * Called by the particle System when the direction is computed for the created particle.
  59817. * @param worldMatrix is the world matrix of the particle system
  59818. * @param directionToUpdate is the direction vector to update with the result
  59819. * @param particle is the particle we are computed the direction for
  59820. */
  59821. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59822. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59823. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59824. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59825. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59826. };
  59827. /**
  59828. * Called by the particle System when the position is computed for the created particle.
  59829. * @param worldMatrix is the world matrix of the particle system
  59830. * @param positionToUpdate is the position vector to update with the result
  59831. * @param particle is the particle we are computed the position for
  59832. */
  59833. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59834. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  59835. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  59836. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  59837. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59838. };
  59839. /**
  59840. * Clones the current emitter and returns a copy of it
  59841. * @returns the new emitter
  59842. */
  59843. BoxParticleEmitter.prototype.clone = function () {
  59844. var newOne = new BoxParticleEmitter();
  59845. BABYLON.Tools.DeepCopy(this, newOne);
  59846. return newOne;
  59847. };
  59848. /**
  59849. * Called by the GPUParticleSystem to setup the update shader
  59850. * @param effect defines the update shader
  59851. */
  59852. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  59853. effect.setVector3("direction1", this.direction1);
  59854. effect.setVector3("direction2", this.direction2);
  59855. effect.setVector3("minEmitBox", this.minEmitBox);
  59856. effect.setVector3("maxEmitBox", this.maxEmitBox);
  59857. };
  59858. /**
  59859. * Returns a string to use to update the GPU particles update shader
  59860. * @returns a string containng the defines string
  59861. */
  59862. BoxParticleEmitter.prototype.getEffectDefines = function () {
  59863. return "#define BOXEMITTER";
  59864. };
  59865. /**
  59866. * Returns the string "BoxParticleEmitter"
  59867. * @returns a string containing the class name
  59868. */
  59869. BoxParticleEmitter.prototype.getClassName = function () {
  59870. return "BoxParticleEmitter";
  59871. };
  59872. /**
  59873. * Serializes the particle system to a JSON object.
  59874. * @returns the JSON object
  59875. */
  59876. BoxParticleEmitter.prototype.serialize = function () {
  59877. var serializationObject = {};
  59878. serializationObject.type = this.getClassName();
  59879. serializationObject.direction1 = this.direction1.asArray();
  59880. serializationObject.direction2 = this.direction2.asArray();
  59881. serializationObject.minEmitBox = this.minEmitBox.asArray();
  59882. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  59883. return serializationObject;
  59884. };
  59885. /**
  59886. * Parse properties from a JSON object
  59887. * @param serializationObject defines the JSON object
  59888. */
  59889. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  59890. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59891. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59892. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  59893. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  59894. };
  59895. return BoxParticleEmitter;
  59896. }());
  59897. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  59898. })(BABYLON || (BABYLON = {}));
  59899. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  59900. var BABYLON;
  59901. (function (BABYLON) {
  59902. /**
  59903. * Particle emitter emitting particles from the inside of a cylinder.
  59904. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  59905. */
  59906. var CylinderParticleEmitter = /** @class */ (function () {
  59907. /**
  59908. * Creates a new instance CylinderParticleEmitter
  59909. * @param radius the radius of the emission cylinder (1 by default)
  59910. * @param height the height of the emission cylinder (1 by default)
  59911. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59912. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59913. */
  59914. function CylinderParticleEmitter(
  59915. /**
  59916. * The radius of the emission cylinder.
  59917. */
  59918. radius,
  59919. /**
  59920. * The height of the emission cylinder.
  59921. */
  59922. height,
  59923. /**
  59924. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59925. */
  59926. radiusRange,
  59927. /**
  59928. * How much to randomize the particle direction [0-1].
  59929. */
  59930. directionRandomizer) {
  59931. if (radius === void 0) { radius = 1; }
  59932. if (height === void 0) { height = 1; }
  59933. if (radiusRange === void 0) { radiusRange = 1; }
  59934. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59935. this.radius = radius;
  59936. this.height = height;
  59937. this.radiusRange = radiusRange;
  59938. this.directionRandomizer = directionRandomizer;
  59939. }
  59940. /**
  59941. * Called by the particle System when the direction is computed for the created particle.
  59942. * @param worldMatrix is the world matrix of the particle system
  59943. * @param directionToUpdate is the direction vector to update with the result
  59944. * @param particle is the particle we are computed the direction for
  59945. */
  59946. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59947. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59948. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  59949. var angle = Math.atan2(direction.x, direction.z);
  59950. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  59951. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  59952. direction.x = Math.sin(angle);
  59953. direction.z = Math.cos(angle);
  59954. direction.normalize();
  59955. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59956. };
  59957. /**
  59958. * Called by the particle System when the position is computed for the created particle.
  59959. * @param worldMatrix is the world matrix of the particle system
  59960. * @param positionToUpdate is the position vector to update with the result
  59961. * @param particle is the particle we are computed the position for
  59962. */
  59963. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59964. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  59965. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59966. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  59967. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  59968. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  59969. var xPos = positionRadius * Math.cos(angle);
  59970. var zPos = positionRadius * Math.sin(angle);
  59971. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  59972. };
  59973. /**
  59974. * Clones the current emitter and returns a copy of it
  59975. * @returns the new emitter
  59976. */
  59977. CylinderParticleEmitter.prototype.clone = function () {
  59978. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  59979. BABYLON.Tools.DeepCopy(this, newOne);
  59980. return newOne;
  59981. };
  59982. /**
  59983. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59984. * @param effect defines the update shader
  59985. */
  59986. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  59987. effect.setFloat("radius", this.radius);
  59988. effect.setFloat("height", this.height);
  59989. effect.setFloat("radiusRange", this.radiusRange);
  59990. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59991. };
  59992. /**
  59993. * Returns a string to use to update the GPU particles update shader
  59994. * @returns a string containng the defines string
  59995. */
  59996. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  59997. return "#define CYLINDEREMITTER";
  59998. };
  59999. /**
  60000. * Returns the string "CylinderParticleEmitter"
  60001. * @returns a string containing the class name
  60002. */
  60003. CylinderParticleEmitter.prototype.getClassName = function () {
  60004. return "CylinderParticleEmitter";
  60005. };
  60006. /**
  60007. * Serializes the particle system to a JSON object.
  60008. * @returns the JSON object
  60009. */
  60010. CylinderParticleEmitter.prototype.serialize = function () {
  60011. var serializationObject = {};
  60012. serializationObject.type = this.getClassName();
  60013. serializationObject.radius = this.radius;
  60014. serializationObject.height = this.height;
  60015. serializationObject.radiusRange = this.radiusRange;
  60016. serializationObject.directionRandomizer = this.directionRandomizer;
  60017. return serializationObject;
  60018. };
  60019. /**
  60020. * Parse properties from a JSON object
  60021. * @param serializationObject defines the JSON object
  60022. */
  60023. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  60024. this.radius = serializationObject.radius;
  60025. this.height = serializationObject.height;
  60026. this.radiusRange = serializationObject.radiusRange;
  60027. this.directionRandomizer = serializationObject.directionRandomizer;
  60028. };
  60029. return CylinderParticleEmitter;
  60030. }());
  60031. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  60032. /**
  60033. * Particle emitter emitting particles from the inside of a cylinder.
  60034. * It emits the particles randomly between two vectors.
  60035. */
  60036. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  60037. __extends(CylinderDirectedParticleEmitter, _super);
  60038. /**
  60039. * Creates a new instance CylinderDirectedParticleEmitter
  60040. * @param radius the radius of the emission cylinder (1 by default)
  60041. * @param height the height of the emission cylinder (1 by default)
  60042. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60043. * @param direction1 the min limit of the emission direction (up vector by default)
  60044. * @param direction2 the max limit of the emission direction (up vector by default)
  60045. */
  60046. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  60047. /**
  60048. * The min limit of the emission direction.
  60049. */
  60050. direction1,
  60051. /**
  60052. * The max limit of the emission direction.
  60053. */
  60054. direction2) {
  60055. if (radius === void 0) { radius = 1; }
  60056. if (height === void 0) { height = 1; }
  60057. if (radiusRange === void 0) { radiusRange = 1; }
  60058. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60059. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60060. var _this = _super.call(this, radius, height, radiusRange) || this;
  60061. _this.direction1 = direction1;
  60062. _this.direction2 = direction2;
  60063. return _this;
  60064. }
  60065. /**
  60066. * Called by the particle System when the direction is computed for the created particle.
  60067. * @param worldMatrix is the world matrix of the particle system
  60068. * @param directionToUpdate is the direction vector to update with the result
  60069. * @param particle is the particle we are computed the direction for
  60070. */
  60071. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60072. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60073. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60074. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60075. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60076. };
  60077. /**
  60078. * Clones the current emitter and returns a copy of it
  60079. * @returns the new emitter
  60080. */
  60081. CylinderDirectedParticleEmitter.prototype.clone = function () {
  60082. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  60083. BABYLON.Tools.DeepCopy(this, newOne);
  60084. return newOne;
  60085. };
  60086. /**
  60087. * Called by the GPUParticleSystem to setup the update shader
  60088. * @param effect defines the update shader
  60089. */
  60090. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60091. effect.setFloat("radius", this.radius);
  60092. effect.setFloat("height", this.height);
  60093. effect.setFloat("radiusRange", this.radiusRange);
  60094. effect.setVector3("direction1", this.direction1);
  60095. effect.setVector3("direction2", this.direction2);
  60096. };
  60097. /**
  60098. * Returns a string to use to update the GPU particles update shader
  60099. * @returns a string containng the defines string
  60100. */
  60101. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60102. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  60103. };
  60104. /**
  60105. * Returns the string "CylinderDirectedParticleEmitter"
  60106. * @returns a string containing the class name
  60107. */
  60108. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  60109. return "CylinderDirectedParticleEmitter";
  60110. };
  60111. /**
  60112. * Serializes the particle system to a JSON object.
  60113. * @returns the JSON object
  60114. */
  60115. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  60116. var serializationObject = _super.prototype.serialize.call(this);
  60117. serializationObject.direction1 = this.direction1.asArray();
  60118. serializationObject.direction2 = this.direction2.asArray();
  60119. return serializationObject;
  60120. };
  60121. /**
  60122. * Parse properties from a JSON object
  60123. * @param serializationObject defines the JSON object
  60124. */
  60125. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60126. _super.prototype.parse.call(this, serializationObject);
  60127. this.direction1.copyFrom(serializationObject.direction1);
  60128. this.direction2.copyFrom(serializationObject.direction2);
  60129. };
  60130. return CylinderDirectedParticleEmitter;
  60131. }(CylinderParticleEmitter));
  60132. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  60133. })(BABYLON || (BABYLON = {}));
  60134. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  60135. var BABYLON;
  60136. (function (BABYLON) {
  60137. /**
  60138. * Particle emitter emitting particles from the inside of a cone.
  60139. * It emits the particles alongside the cone volume from the base to the particle.
  60140. * The emission direction might be randomized.
  60141. */
  60142. var ConeParticleEmitter = /** @class */ (function () {
  60143. /**
  60144. * Creates a new instance ConeParticleEmitter
  60145. * @param radius the radius of the emission cone (1 by default)
  60146. * @param angles the cone base angle (PI by default)
  60147. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  60148. */
  60149. function ConeParticleEmitter(radius, angle,
  60150. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  60151. directionRandomizer) {
  60152. if (radius === void 0) { radius = 1; }
  60153. if (angle === void 0) { angle = Math.PI; }
  60154. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60155. this.directionRandomizer = directionRandomizer;
  60156. /**
  60157. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  60158. */
  60159. this.radiusRange = 1;
  60160. /**
  60161. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  60162. */
  60163. this.heightRange = 1;
  60164. /**
  60165. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  60166. */
  60167. this.emitFromSpawnPointOnly = false;
  60168. this.angle = angle;
  60169. this.radius = radius;
  60170. }
  60171. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  60172. /**
  60173. * Gets or sets the radius of the emission cone
  60174. */
  60175. get: function () {
  60176. return this._radius;
  60177. },
  60178. set: function (value) {
  60179. this._radius = value;
  60180. this._buildHeight();
  60181. },
  60182. enumerable: true,
  60183. configurable: true
  60184. });
  60185. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  60186. /**
  60187. * Gets or sets the angle of the emission cone
  60188. */
  60189. get: function () {
  60190. return this._angle;
  60191. },
  60192. set: function (value) {
  60193. this._angle = value;
  60194. this._buildHeight();
  60195. },
  60196. enumerable: true,
  60197. configurable: true
  60198. });
  60199. ConeParticleEmitter.prototype._buildHeight = function () {
  60200. if (this._angle !== 0) {
  60201. this._height = this._radius / Math.tan(this._angle / 2);
  60202. }
  60203. else {
  60204. this._height = 1;
  60205. }
  60206. };
  60207. /**
  60208. * Called by the particle System when the direction is computed for the created particle.
  60209. * @param worldMatrix is the world matrix of the particle system
  60210. * @param directionToUpdate is the direction vector to update with the result
  60211. * @param particle is the particle we are computed the direction for
  60212. */
  60213. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60214. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  60215. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  60216. }
  60217. else {
  60218. // measure the direction Vector from the emitter to the particle.
  60219. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60220. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60221. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60222. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60223. direction.x += randX;
  60224. direction.y += randY;
  60225. direction.z += randZ;
  60226. direction.normalize();
  60227. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60228. }
  60229. };
  60230. /**
  60231. * Called by the particle System when the position is computed for the created particle.
  60232. * @param worldMatrix is the world matrix of the particle system
  60233. * @param positionToUpdate is the position vector to update with the result
  60234. * @param particle is the particle we are computed the position for
  60235. */
  60236. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60237. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  60238. var h;
  60239. if (!this.emitFromSpawnPointOnly) {
  60240. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  60241. // Better distribution in a cone at normal angles.
  60242. h = 1 - h * h;
  60243. }
  60244. else {
  60245. h = 0.0001;
  60246. }
  60247. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  60248. radius = radius * h;
  60249. var randX = radius * Math.sin(s);
  60250. var randZ = radius * Math.cos(s);
  60251. var randY = h * this._height;
  60252. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60253. };
  60254. /**
  60255. * Clones the current emitter and returns a copy of it
  60256. * @returns the new emitter
  60257. */
  60258. ConeParticleEmitter.prototype.clone = function () {
  60259. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  60260. BABYLON.Tools.DeepCopy(this, newOne);
  60261. return newOne;
  60262. };
  60263. /**
  60264. * Called by the GPUParticleSystem to setup the update shader
  60265. * @param effect defines the update shader
  60266. */
  60267. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  60268. effect.setFloat2("radius", this._radius, this.radiusRange);
  60269. effect.setFloat("coneAngle", this._angle);
  60270. effect.setFloat2("height", this._height, this.heightRange);
  60271. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60272. };
  60273. /**
  60274. * Returns a string to use to update the GPU particles update shader
  60275. * @returns a string containng the defines string
  60276. */
  60277. ConeParticleEmitter.prototype.getEffectDefines = function () {
  60278. var defines = "#define CONEEMITTER";
  60279. if (this.emitFromSpawnPointOnly) {
  60280. defines += "\n#define CONEEMITTERSPAWNPOINT";
  60281. }
  60282. return defines;
  60283. };
  60284. /**
  60285. * Returns the string "ConeParticleEmitter"
  60286. * @returns a string containing the class name
  60287. */
  60288. ConeParticleEmitter.prototype.getClassName = function () {
  60289. return "ConeParticleEmitter";
  60290. };
  60291. /**
  60292. * Serializes the particle system to a JSON object.
  60293. * @returns the JSON object
  60294. */
  60295. ConeParticleEmitter.prototype.serialize = function () {
  60296. var serializationObject = {};
  60297. serializationObject.type = this.getClassName();
  60298. serializationObject.radius = this._radius;
  60299. serializationObject.angle = this._angle;
  60300. serializationObject.directionRandomizer = this.directionRandomizer;
  60301. return serializationObject;
  60302. };
  60303. /**
  60304. * Parse properties from a JSON object
  60305. * @param serializationObject defines the JSON object
  60306. */
  60307. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  60308. this.radius = serializationObject.radius;
  60309. this.angle = serializationObject.angle;
  60310. this.directionRandomizer = serializationObject.directionRandomizer;
  60311. };
  60312. return ConeParticleEmitter;
  60313. }());
  60314. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  60315. })(BABYLON || (BABYLON = {}));
  60316. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  60317. var BABYLON;
  60318. (function (BABYLON) {
  60319. /**
  60320. * Particle emitter emitting particles from the inside of a sphere.
  60321. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  60322. */
  60323. var SphereParticleEmitter = /** @class */ (function () {
  60324. /**
  60325. * Creates a new instance SphereParticleEmitter
  60326. * @param radius the radius of the emission sphere (1 by default)
  60327. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60328. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60329. */
  60330. function SphereParticleEmitter(
  60331. /**
  60332. * The radius of the emission sphere.
  60333. */
  60334. radius,
  60335. /**
  60336. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60337. */
  60338. radiusRange,
  60339. /**
  60340. * How much to randomize the particle direction [0-1].
  60341. */
  60342. directionRandomizer) {
  60343. if (radius === void 0) { radius = 1; }
  60344. if (radiusRange === void 0) { radiusRange = 1; }
  60345. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60346. this.radius = radius;
  60347. this.radiusRange = radiusRange;
  60348. this.directionRandomizer = directionRandomizer;
  60349. }
  60350. /**
  60351. * Called by the particle System when the direction is computed for the created particle.
  60352. * @param worldMatrix is the world matrix of the particle system
  60353. * @param directionToUpdate is the direction vector to update with the result
  60354. * @param particle is the particle we are computed the direction for
  60355. */
  60356. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60357. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60358. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60359. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60360. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60361. direction.x += randX;
  60362. direction.y += randY;
  60363. direction.z += randZ;
  60364. direction.normalize();
  60365. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60366. };
  60367. /**
  60368. * Called by the particle System when the position is computed for the created particle.
  60369. * @param worldMatrix is the world matrix of the particle system
  60370. * @param positionToUpdate is the position vector to update with the result
  60371. * @param particle is the particle we are computed the position for
  60372. */
  60373. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60374. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60375. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60376. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60377. var theta = Math.acos(2 * v - 1);
  60378. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60379. var randY = randRadius * Math.cos(theta);
  60380. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60381. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60382. };
  60383. /**
  60384. * Clones the current emitter and returns a copy of it
  60385. * @returns the new emitter
  60386. */
  60387. SphereParticleEmitter.prototype.clone = function () {
  60388. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  60389. BABYLON.Tools.DeepCopy(this, newOne);
  60390. return newOne;
  60391. };
  60392. /**
  60393. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60394. * @param effect defines the update shader
  60395. */
  60396. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  60397. effect.setFloat("radius", this.radius);
  60398. effect.setFloat("radiusRange", this.radiusRange);
  60399. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60400. };
  60401. /**
  60402. * Returns a string to use to update the GPU particles update shader
  60403. * @returns a string containng the defines string
  60404. */
  60405. SphereParticleEmitter.prototype.getEffectDefines = function () {
  60406. return "#define SPHEREEMITTER";
  60407. };
  60408. /**
  60409. * Returns the string "SphereParticleEmitter"
  60410. * @returns a string containing the class name
  60411. */
  60412. SphereParticleEmitter.prototype.getClassName = function () {
  60413. return "SphereParticleEmitter";
  60414. };
  60415. /**
  60416. * Serializes the particle system to a JSON object.
  60417. * @returns the JSON object
  60418. */
  60419. SphereParticleEmitter.prototype.serialize = function () {
  60420. var serializationObject = {};
  60421. serializationObject.type = this.getClassName();
  60422. serializationObject.radius = this.radius;
  60423. serializationObject.radiusRange = this.radiusRange;
  60424. serializationObject.directionRandomizer = this.directionRandomizer;
  60425. return serializationObject;
  60426. };
  60427. /**
  60428. * Parse properties from a JSON object
  60429. * @param serializationObject defines the JSON object
  60430. */
  60431. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  60432. this.radius = serializationObject.radius;
  60433. this.radiusRange = serializationObject.radiusRange;
  60434. this.directionRandomizer = serializationObject.directionRandomizer;
  60435. };
  60436. return SphereParticleEmitter;
  60437. }());
  60438. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  60439. /**
  60440. * Particle emitter emitting particles from the inside of a sphere.
  60441. * It emits the particles randomly between two vectors.
  60442. */
  60443. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  60444. __extends(SphereDirectedParticleEmitter, _super);
  60445. /**
  60446. * Creates a new instance SphereDirectedParticleEmitter
  60447. * @param radius the radius of the emission sphere (1 by default)
  60448. * @param direction1 the min limit of the emission direction (up vector by default)
  60449. * @param direction2 the max limit of the emission direction (up vector by default)
  60450. */
  60451. function SphereDirectedParticleEmitter(radius,
  60452. /**
  60453. * The min limit of the emission direction.
  60454. */
  60455. direction1,
  60456. /**
  60457. * The max limit of the emission direction.
  60458. */
  60459. direction2) {
  60460. if (radius === void 0) { radius = 1; }
  60461. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60462. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60463. var _this = _super.call(this, radius) || this;
  60464. _this.direction1 = direction1;
  60465. _this.direction2 = direction2;
  60466. return _this;
  60467. }
  60468. /**
  60469. * Called by the particle System when the direction is computed for the created particle.
  60470. * @param worldMatrix is the world matrix of the particle system
  60471. * @param directionToUpdate is the direction vector to update with the result
  60472. * @param particle is the particle we are computed the direction for
  60473. */
  60474. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60475. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60476. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60477. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60478. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60479. };
  60480. /**
  60481. * Clones the current emitter and returns a copy of it
  60482. * @returns the new emitter
  60483. */
  60484. SphereDirectedParticleEmitter.prototype.clone = function () {
  60485. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  60486. BABYLON.Tools.DeepCopy(this, newOne);
  60487. return newOne;
  60488. };
  60489. /**
  60490. * Called by the GPUParticleSystem to setup the update shader
  60491. * @param effect defines the update shader
  60492. */
  60493. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60494. effect.setFloat("radius", this.radius);
  60495. effect.setFloat("radiusRange", this.radiusRange);
  60496. effect.setVector3("direction1", this.direction1);
  60497. effect.setVector3("direction2", this.direction2);
  60498. };
  60499. /**
  60500. * Returns a string to use to update the GPU particles update shader
  60501. * @returns a string containng the defines string
  60502. */
  60503. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60504. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  60505. };
  60506. /**
  60507. * Returns the string "SphereDirectedParticleEmitter"
  60508. * @returns a string containing the class name
  60509. */
  60510. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  60511. return "SphereDirectedParticleEmitter";
  60512. };
  60513. /**
  60514. * Serializes the particle system to a JSON object.
  60515. * @returns the JSON object
  60516. */
  60517. SphereDirectedParticleEmitter.prototype.serialize = function () {
  60518. var serializationObject = _super.prototype.serialize.call(this);
  60519. serializationObject.direction1 = this.direction1.asArray();
  60520. serializationObject.direction2 = this.direction2.asArray();
  60521. return serializationObject;
  60522. };
  60523. /**
  60524. * Parse properties from a JSON object
  60525. * @param serializationObject defines the JSON object
  60526. */
  60527. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60528. _super.prototype.parse.call(this, serializationObject);
  60529. this.direction1.copyFrom(serializationObject.direction1);
  60530. this.direction2.copyFrom(serializationObject.direction2);
  60531. };
  60532. return SphereDirectedParticleEmitter;
  60533. }(SphereParticleEmitter));
  60534. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  60535. })(BABYLON || (BABYLON = {}));
  60536. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  60537. var BABYLON;
  60538. (function (BABYLON) {
  60539. /**
  60540. * Particle emitter emitting particles from the inside of a hemisphere.
  60541. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  60542. */
  60543. var HemisphericParticleEmitter = /** @class */ (function () {
  60544. /**
  60545. * Creates a new instance HemisphericParticleEmitter
  60546. * @param radius the radius of the emission hemisphere (1 by default)
  60547. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60548. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60549. */
  60550. function HemisphericParticleEmitter(
  60551. /**
  60552. * The radius of the emission hemisphere.
  60553. */
  60554. radius,
  60555. /**
  60556. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60557. */
  60558. radiusRange,
  60559. /**
  60560. * How much to randomize the particle direction [0-1].
  60561. */
  60562. directionRandomizer) {
  60563. if (radius === void 0) { radius = 1; }
  60564. if (radiusRange === void 0) { radiusRange = 1; }
  60565. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60566. this.radius = radius;
  60567. this.radiusRange = radiusRange;
  60568. this.directionRandomizer = directionRandomizer;
  60569. }
  60570. /**
  60571. * Called by the particle System when the direction is computed for the created particle.
  60572. * @param worldMatrix is the world matrix of the particle system
  60573. * @param directionToUpdate is the direction vector to update with the result
  60574. * @param particle is the particle we are computed the direction for
  60575. */
  60576. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60577. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60578. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60579. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60580. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60581. direction.x += randX;
  60582. direction.y += randY;
  60583. direction.z += randZ;
  60584. direction.normalize();
  60585. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60586. };
  60587. /**
  60588. * Called by the particle System when the position is computed for the created particle.
  60589. * @param worldMatrix is the world matrix of the particle system
  60590. * @param positionToUpdate is the position vector to update with the result
  60591. * @param particle is the particle we are computed the position for
  60592. */
  60593. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60594. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60595. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60596. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60597. var theta = Math.acos(2 * v - 1);
  60598. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60599. var randY = randRadius * Math.cos(theta);
  60600. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60601. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  60602. };
  60603. /**
  60604. * Clones the current emitter and returns a copy of it
  60605. * @returns the new emitter
  60606. */
  60607. HemisphericParticleEmitter.prototype.clone = function () {
  60608. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  60609. BABYLON.Tools.DeepCopy(this, newOne);
  60610. return newOne;
  60611. };
  60612. /**
  60613. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60614. * @param effect defines the update shader
  60615. */
  60616. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  60617. effect.setFloat("radius", this.radius);
  60618. effect.setFloat("radiusRange", this.radiusRange);
  60619. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60620. };
  60621. /**
  60622. * Returns a string to use to update the GPU particles update shader
  60623. * @returns a string containng the defines string
  60624. */
  60625. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  60626. return "#define HEMISPHERICEMITTER";
  60627. };
  60628. /**
  60629. * Returns the string "HemisphericParticleEmitter"
  60630. * @returns a string containing the class name
  60631. */
  60632. HemisphericParticleEmitter.prototype.getClassName = function () {
  60633. return "HemisphericParticleEmitter";
  60634. };
  60635. /**
  60636. * Serializes the particle system to a JSON object.
  60637. * @returns the JSON object
  60638. */
  60639. HemisphericParticleEmitter.prototype.serialize = function () {
  60640. var serializationObject = {};
  60641. serializationObject.type = this.getClassName();
  60642. serializationObject.radius = this.radius;
  60643. serializationObject.radiusRange = this.radiusRange;
  60644. serializationObject.directionRandomizer = this.directionRandomizer;
  60645. return serializationObject;
  60646. };
  60647. /**
  60648. * Parse properties from a JSON object
  60649. * @param serializationObject defines the JSON object
  60650. */
  60651. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  60652. this.radius = serializationObject.radius;
  60653. this.radiusRange = serializationObject.radiusRange;
  60654. this.directionRandomizer = serializationObject.directionRandomizer;
  60655. };
  60656. return HemisphericParticleEmitter;
  60657. }());
  60658. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  60659. })(BABYLON || (BABYLON = {}));
  60660. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  60661. var BABYLON;
  60662. (function (BABYLON) {
  60663. /**
  60664. * Particle emitter emitting particles from a point.
  60665. * It emits the particles randomly between 2 given directions.
  60666. */
  60667. var PointParticleEmitter = /** @class */ (function () {
  60668. /**
  60669. * Creates a new instance PointParticleEmitter
  60670. */
  60671. function PointParticleEmitter() {
  60672. /**
  60673. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60674. */
  60675. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60676. /**
  60677. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60678. */
  60679. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60680. }
  60681. /**
  60682. * Called by the particle System when the direction is computed for the created particle.
  60683. * @param worldMatrix is the world matrix of the particle system
  60684. * @param directionToUpdate is the direction vector to update with the result
  60685. * @param particle is the particle we are computed the direction for
  60686. */
  60687. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60688. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60689. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60690. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60691. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60692. };
  60693. /**
  60694. * Called by the particle System when the position is computed for the created particle.
  60695. * @param worldMatrix is the world matrix of the particle system
  60696. * @param positionToUpdate is the position vector to update with the result
  60697. * @param particle is the particle we are computed the position for
  60698. */
  60699. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60700. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  60701. };
  60702. /**
  60703. * Clones the current emitter and returns a copy of it
  60704. * @returns the new emitter
  60705. */
  60706. PointParticleEmitter.prototype.clone = function () {
  60707. var newOne = new PointParticleEmitter();
  60708. BABYLON.Tools.DeepCopy(this, newOne);
  60709. return newOne;
  60710. };
  60711. /**
  60712. * Called by the GPUParticleSystem to setup the update shader
  60713. * @param effect defines the update shader
  60714. */
  60715. PointParticleEmitter.prototype.applyToShader = function (effect) {
  60716. effect.setVector3("direction1", this.direction1);
  60717. effect.setVector3("direction2", this.direction2);
  60718. };
  60719. /**
  60720. * Returns a string to use to update the GPU particles update shader
  60721. * @returns a string containng the defines string
  60722. */
  60723. PointParticleEmitter.prototype.getEffectDefines = function () {
  60724. return "#define POINTEMITTER";
  60725. };
  60726. /**
  60727. * Returns the string "PointParticleEmitter"
  60728. * @returns a string containing the class name
  60729. */
  60730. PointParticleEmitter.prototype.getClassName = function () {
  60731. return "PointParticleEmitter";
  60732. };
  60733. /**
  60734. * Serializes the particle system to a JSON object.
  60735. * @returns the JSON object
  60736. */
  60737. PointParticleEmitter.prototype.serialize = function () {
  60738. var serializationObject = {};
  60739. serializationObject.type = this.getClassName();
  60740. serializationObject.direction1 = this.direction1.asArray();
  60741. serializationObject.direction2 = this.direction2.asArray();
  60742. return serializationObject;
  60743. };
  60744. /**
  60745. * Parse properties from a JSON object
  60746. * @param serializationObject defines the JSON object
  60747. */
  60748. PointParticleEmitter.prototype.parse = function (serializationObject) {
  60749. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60750. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60751. };
  60752. return PointParticleEmitter;
  60753. }());
  60754. BABYLON.PointParticleEmitter = PointParticleEmitter;
  60755. })(BABYLON || (BABYLON = {}));
  60756. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  60757. var BABYLON;
  60758. (function (BABYLON) {
  60759. // Adds the parsers to the scene parsers.
  60760. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  60761. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  60762. if (!individualParser) {
  60763. return;
  60764. }
  60765. // Particles Systems
  60766. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60767. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60768. var parsedParticleSystem = parsedData.particleSystems[index];
  60769. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  60770. }
  60771. }
  60772. });
  60773. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  60774. if (parsedParticleSystem.activeParticleCount) {
  60775. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60776. return ps;
  60777. }
  60778. else {
  60779. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60780. return ps;
  60781. }
  60782. });
  60783. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  60784. if (uniformsNames === void 0) { uniformsNames = []; }
  60785. if (samplers === void 0) { samplers = []; }
  60786. if (defines === void 0) { defines = ""; }
  60787. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  60788. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  60789. if (defines.indexOf(" BILLBOARD") === -1) {
  60790. defines += "\n#define BILLBOARD\n";
  60791. }
  60792. if (samplers.indexOf("diffuseSampler") === -1) {
  60793. samplers.push("diffuseSampler");
  60794. }
  60795. return this.createEffect({
  60796. vertex: "particles",
  60797. fragmentElement: fragmentName
  60798. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  60799. };
  60800. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  60801. var results = new Array();
  60802. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60803. var particleSystem = this.getScene().particleSystems[index];
  60804. if (particleSystem.emitter === this) {
  60805. results.push(particleSystem);
  60806. }
  60807. }
  60808. return results;
  60809. };
  60810. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  60811. var results = new Array();
  60812. var descendants = this.getDescendants();
  60813. descendants.push(this);
  60814. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60815. var particleSystem = this.getScene().particleSystems[index];
  60816. var emitter = particleSystem.emitter;
  60817. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  60818. results.push(particleSystem);
  60819. }
  60820. }
  60821. return results;
  60822. };
  60823. })(BABYLON || (BABYLON = {}));
  60824. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  60825. var BABYLON;
  60826. (function (BABYLON) {
  60827. /**
  60828. * Type of sub emitter
  60829. */
  60830. var SubEmitterType;
  60831. (function (SubEmitterType) {
  60832. /**
  60833. * Attached to the particle over it's lifetime
  60834. */
  60835. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  60836. /**
  60837. * Created when the particle dies
  60838. */
  60839. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  60840. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  60841. /**
  60842. * Sub emitter class used to emit particles from an existing particle
  60843. */
  60844. var SubEmitter = /** @class */ (function () {
  60845. /**
  60846. * Creates a sub emitter
  60847. * @param particleSystem the particle system to be used by the sub emitter
  60848. */
  60849. function SubEmitter(
  60850. /**
  60851. * the particle system to be used by the sub emitter
  60852. */
  60853. particleSystem) {
  60854. this.particleSystem = particleSystem;
  60855. /**
  60856. * Type of the submitter (Default: END)
  60857. */
  60858. this.type = SubEmitterType.END;
  60859. /**
  60860. * 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)
  60861. * Note: This only is supported when using an emitter of type Mesh
  60862. */
  60863. this.inheritDirection = false;
  60864. /**
  60865. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  60866. */
  60867. this.inheritedVelocityAmount = 0;
  60868. }
  60869. /**
  60870. * Clones the sub emitter
  60871. * @returns the cloned sub emitter
  60872. */
  60873. SubEmitter.prototype.clone = function () {
  60874. // Clone particle system
  60875. var emitter = this.particleSystem.emitter;
  60876. if (!emitter) {
  60877. emitter = new BABYLON.Vector3();
  60878. }
  60879. else if (emitter instanceof BABYLON.Vector3) {
  60880. emitter = emitter.clone();
  60881. }
  60882. else if (emitter instanceof BABYLON.AbstractMesh) {
  60883. emitter = new BABYLON.Mesh("", emitter.getScene());
  60884. emitter.isVisible = false;
  60885. }
  60886. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  60887. // Clone properties
  60888. clone.type = this.type;
  60889. clone.inheritDirection = this.inheritDirection;
  60890. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60891. clone.particleSystem._disposeEmitterOnDispose = true;
  60892. clone.particleSystem.disposeOnStop = true;
  60893. return clone;
  60894. };
  60895. /**
  60896. * Serialize current object to a JSON object
  60897. * @returns the serialized object
  60898. */
  60899. SubEmitter.prototype.serialize = function () {
  60900. var serializationObject = {};
  60901. serializationObject.type = this.type;
  60902. serializationObject.inheritDirection = this.inheritDirection;
  60903. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60904. serializationObject.particleSystem = this.particleSystem.serialize();
  60905. return serializationObject;
  60906. };
  60907. /**
  60908. * Creates a new SubEmitter from a serialized JSON version
  60909. * @param serializationObject defines the JSON object to read from
  60910. * @param scene defines the hosting scene
  60911. * @param rootUrl defines the rootUrl for data loading
  60912. * @returns a new SubEmitter
  60913. */
  60914. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  60915. var system = serializationObject.particleSystem;
  60916. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  60917. subEmitter.type = serializationObject.type;
  60918. subEmitter.inheritDirection = serializationObject.inheritDirection;
  60919. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  60920. subEmitter.particleSystem._isSubEmitter = true;
  60921. return subEmitter;
  60922. };
  60923. /** Release associated resources */
  60924. SubEmitter.prototype.dispose = function () {
  60925. this.particleSystem.dispose();
  60926. };
  60927. return SubEmitter;
  60928. }());
  60929. BABYLON.SubEmitter = SubEmitter;
  60930. })(BABYLON || (BABYLON = {}));
  60931. //# sourceMappingURL=babylon.subEmitter.js.map
  60932. var BABYLON;
  60933. (function (BABYLON) {
  60934. var ShaderMaterial = /** @class */ (function (_super) {
  60935. __extends(ShaderMaterial, _super);
  60936. function ShaderMaterial(name, scene, shaderPath, options) {
  60937. var _this = _super.call(this, name, scene) || this;
  60938. _this._textures = {};
  60939. _this._textureArrays = {};
  60940. _this._floats = {};
  60941. _this._ints = {};
  60942. _this._floatsArrays = {};
  60943. _this._colors3 = {};
  60944. _this._colors3Arrays = {};
  60945. _this._colors4 = {};
  60946. _this._vectors2 = {};
  60947. _this._vectors3 = {};
  60948. _this._vectors4 = {};
  60949. _this._matrices = {};
  60950. _this._matrices3x3 = {};
  60951. _this._matrices2x2 = {};
  60952. _this._vectors2Arrays = {};
  60953. _this._vectors3Arrays = {};
  60954. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60955. _this._shaderPath = shaderPath;
  60956. options.needAlphaBlending = options.needAlphaBlending || false;
  60957. options.needAlphaTesting = options.needAlphaTesting || false;
  60958. options.attributes = options.attributes || ["position", "normal", "uv"];
  60959. options.uniforms = options.uniforms || ["worldViewProjection"];
  60960. options.uniformBuffers = options.uniformBuffers || [];
  60961. options.samplers = options.samplers || [];
  60962. options.defines = options.defines || [];
  60963. _this._options = options;
  60964. return _this;
  60965. }
  60966. ShaderMaterial.prototype.getClassName = function () {
  60967. return "ShaderMaterial";
  60968. };
  60969. ShaderMaterial.prototype.needAlphaBlending = function () {
  60970. return this._options.needAlphaBlending;
  60971. };
  60972. ShaderMaterial.prototype.needAlphaTesting = function () {
  60973. return this._options.needAlphaTesting;
  60974. };
  60975. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60976. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60977. this._options.uniforms.push(uniformName);
  60978. }
  60979. };
  60980. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60981. if (this._options.samplers.indexOf(name) === -1) {
  60982. this._options.samplers.push(name);
  60983. }
  60984. this._textures[name] = texture;
  60985. return this;
  60986. };
  60987. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60988. if (this._options.samplers.indexOf(name) === -1) {
  60989. this._options.samplers.push(name);
  60990. }
  60991. this._checkUniform(name);
  60992. this._textureArrays[name] = textures;
  60993. return this;
  60994. };
  60995. ShaderMaterial.prototype.setFloat = function (name, value) {
  60996. this._checkUniform(name);
  60997. this._floats[name] = value;
  60998. return this;
  60999. };
  61000. ShaderMaterial.prototype.setInt = function (name, value) {
  61001. this._checkUniform(name);
  61002. this._ints[name] = value;
  61003. return this;
  61004. };
  61005. ShaderMaterial.prototype.setFloats = function (name, value) {
  61006. this._checkUniform(name);
  61007. this._floatsArrays[name] = value;
  61008. return this;
  61009. };
  61010. ShaderMaterial.prototype.setColor3 = function (name, value) {
  61011. this._checkUniform(name);
  61012. this._colors3[name] = value;
  61013. return this;
  61014. };
  61015. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  61016. this._checkUniform(name);
  61017. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  61018. color.toArray(arr, arr.length);
  61019. return arr;
  61020. }, []);
  61021. return this;
  61022. };
  61023. ShaderMaterial.prototype.setColor4 = function (name, value) {
  61024. this._checkUniform(name);
  61025. this._colors4[name] = value;
  61026. return this;
  61027. };
  61028. ShaderMaterial.prototype.setVector2 = function (name, value) {
  61029. this._checkUniform(name);
  61030. this._vectors2[name] = value;
  61031. return this;
  61032. };
  61033. ShaderMaterial.prototype.setVector3 = function (name, value) {
  61034. this._checkUniform(name);
  61035. this._vectors3[name] = value;
  61036. return this;
  61037. };
  61038. ShaderMaterial.prototype.setVector4 = function (name, value) {
  61039. this._checkUniform(name);
  61040. this._vectors4[name] = value;
  61041. return this;
  61042. };
  61043. ShaderMaterial.prototype.setMatrix = function (name, value) {
  61044. this._checkUniform(name);
  61045. this._matrices[name] = value;
  61046. return this;
  61047. };
  61048. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  61049. this._checkUniform(name);
  61050. this._matrices3x3[name] = value;
  61051. return this;
  61052. };
  61053. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  61054. this._checkUniform(name);
  61055. this._matrices2x2[name] = value;
  61056. return this;
  61057. };
  61058. ShaderMaterial.prototype.setArray2 = function (name, value) {
  61059. this._checkUniform(name);
  61060. this._vectors2Arrays[name] = value;
  61061. return this;
  61062. };
  61063. ShaderMaterial.prototype.setArray3 = function (name, value) {
  61064. this._checkUniform(name);
  61065. this._vectors3Arrays[name] = value;
  61066. return this;
  61067. };
  61068. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61069. if (!mesh) {
  61070. return true;
  61071. }
  61072. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  61073. return false;
  61074. }
  61075. return false;
  61076. };
  61077. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  61078. var scene = this.getScene();
  61079. var engine = scene.getEngine();
  61080. if (!this.checkReadyOnEveryCall) {
  61081. if (this._renderId === scene.getRenderId()) {
  61082. if (this._checkCache(scene, mesh, useInstances)) {
  61083. return true;
  61084. }
  61085. }
  61086. }
  61087. // Instances
  61088. var defines = [];
  61089. var attribs = [];
  61090. var fallbacks = new BABYLON.EffectFallbacks();
  61091. for (var index = 0; index < this._options.defines.length; index++) {
  61092. defines.push(this._options.defines[index]);
  61093. }
  61094. for (var index = 0; index < this._options.attributes.length; index++) {
  61095. attribs.push(this._options.attributes[index]);
  61096. }
  61097. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61098. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61099. defines.push("#define VERTEXCOLOR");
  61100. }
  61101. if (useInstances) {
  61102. defines.push("#define INSTANCES");
  61103. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  61104. }
  61105. // Bones
  61106. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61107. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61108. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61109. if (mesh.numBoneInfluencers > 4) {
  61110. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61111. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61112. }
  61113. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61114. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61115. fallbacks.addCPUSkinningFallback(0, mesh);
  61116. if (this._options.uniforms.indexOf("mBones") === -1) {
  61117. this._options.uniforms.push("mBones");
  61118. }
  61119. }
  61120. else {
  61121. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61122. }
  61123. // Textures
  61124. for (var name in this._textures) {
  61125. if (!this._textures[name].isReady()) {
  61126. return false;
  61127. }
  61128. }
  61129. // Alpha test
  61130. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  61131. defines.push("#define ALPHATEST");
  61132. }
  61133. var previousEffect = this._effect;
  61134. var join = defines.join("\n");
  61135. this._effect = engine.createEffect(this._shaderPath, {
  61136. attributes: attribs,
  61137. uniformsNames: this._options.uniforms,
  61138. uniformBuffersNames: this._options.uniformBuffers,
  61139. samplers: this._options.samplers,
  61140. defines: join,
  61141. fallbacks: fallbacks,
  61142. onCompiled: this.onCompiled,
  61143. onError: this.onError
  61144. }, engine);
  61145. if (!this._effect.isReady()) {
  61146. return false;
  61147. }
  61148. if (previousEffect !== this._effect) {
  61149. scene.resetCachedMaterial();
  61150. }
  61151. this._renderId = scene.getRenderId();
  61152. return true;
  61153. };
  61154. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61155. var scene = this.getScene();
  61156. if (!this._effect) {
  61157. return;
  61158. }
  61159. if (this._options.uniforms.indexOf("world") !== -1) {
  61160. this._effect.setMatrix("world", world);
  61161. }
  61162. if (this._options.uniforms.indexOf("worldView") !== -1) {
  61163. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  61164. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  61165. }
  61166. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  61167. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  61168. }
  61169. };
  61170. ShaderMaterial.prototype.bind = function (world, mesh) {
  61171. // Std values
  61172. this.bindOnlyWorldMatrix(world);
  61173. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  61174. if (this._options.uniforms.indexOf("view") !== -1) {
  61175. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  61176. }
  61177. if (this._options.uniforms.indexOf("projection") !== -1) {
  61178. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  61179. }
  61180. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  61181. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  61182. }
  61183. // Bones
  61184. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61185. var name;
  61186. // Texture
  61187. for (name in this._textures) {
  61188. this._effect.setTexture(name, this._textures[name]);
  61189. }
  61190. // Texture arrays
  61191. for (name in this._textureArrays) {
  61192. this._effect.setTextureArray(name, this._textureArrays[name]);
  61193. }
  61194. // Int
  61195. for (name in this._ints) {
  61196. this._effect.setInt(name, this._ints[name]);
  61197. }
  61198. // Float
  61199. for (name in this._floats) {
  61200. this._effect.setFloat(name, this._floats[name]);
  61201. }
  61202. // Floats
  61203. for (name in this._floatsArrays) {
  61204. this._effect.setArray(name, this._floatsArrays[name]);
  61205. }
  61206. // Color3
  61207. for (name in this._colors3) {
  61208. this._effect.setColor3(name, this._colors3[name]);
  61209. }
  61210. for (name in this._colors3Arrays) {
  61211. this._effect.setArray3(name, this._colors3Arrays[name]);
  61212. }
  61213. // Color4
  61214. for (name in this._colors4) {
  61215. var color = this._colors4[name];
  61216. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  61217. }
  61218. // Vector2
  61219. for (name in this._vectors2) {
  61220. this._effect.setVector2(name, this._vectors2[name]);
  61221. }
  61222. // Vector3
  61223. for (name in this._vectors3) {
  61224. this._effect.setVector3(name, this._vectors3[name]);
  61225. }
  61226. // Vector4
  61227. for (name in this._vectors4) {
  61228. this._effect.setVector4(name, this._vectors4[name]);
  61229. }
  61230. // Matrix
  61231. for (name in this._matrices) {
  61232. this._effect.setMatrix(name, this._matrices[name]);
  61233. }
  61234. // Matrix 3x3
  61235. for (name in this._matrices3x3) {
  61236. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  61237. }
  61238. // Matrix 2x2
  61239. for (name in this._matrices2x2) {
  61240. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  61241. }
  61242. // Vector2Array
  61243. for (name in this._vectors2Arrays) {
  61244. this._effect.setArray2(name, this._vectors2Arrays[name]);
  61245. }
  61246. // Vector3Array
  61247. for (name in this._vectors3Arrays) {
  61248. this._effect.setArray3(name, this._vectors3Arrays[name]);
  61249. }
  61250. }
  61251. this._afterBind(mesh);
  61252. };
  61253. ShaderMaterial.prototype.getActiveTextures = function () {
  61254. var activeTextures = _super.prototype.getActiveTextures.call(this);
  61255. for (var name in this._textures) {
  61256. activeTextures.push(this._textures[name]);
  61257. }
  61258. for (var name in this._textureArrays) {
  61259. var array = this._textureArrays[name];
  61260. for (var index = 0; index < array.length; index++) {
  61261. activeTextures.push(array[index]);
  61262. }
  61263. }
  61264. return activeTextures;
  61265. };
  61266. ShaderMaterial.prototype.hasTexture = function (texture) {
  61267. if (_super.prototype.hasTexture.call(this, texture)) {
  61268. return true;
  61269. }
  61270. for (var name in this._textures) {
  61271. if (this._textures[name] === texture) {
  61272. return true;
  61273. }
  61274. }
  61275. for (var name in this._textureArrays) {
  61276. var array = this._textureArrays[name];
  61277. for (var index = 0; index < array.length; index++) {
  61278. if (array[index] === texture) {
  61279. return true;
  61280. }
  61281. }
  61282. }
  61283. return false;
  61284. };
  61285. ShaderMaterial.prototype.clone = function (name) {
  61286. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  61287. return newShaderMaterial;
  61288. };
  61289. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61290. if (forceDisposeTextures) {
  61291. var name;
  61292. for (name in this._textures) {
  61293. this._textures[name].dispose();
  61294. }
  61295. for (name in this._textureArrays) {
  61296. var array = this._textureArrays[name];
  61297. for (var index = 0; index < array.length; index++) {
  61298. array[index].dispose();
  61299. }
  61300. }
  61301. }
  61302. this._textures = {};
  61303. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61304. };
  61305. ShaderMaterial.prototype.serialize = function () {
  61306. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61307. serializationObject.customType = "BABYLON.ShaderMaterial";
  61308. serializationObject.options = this._options;
  61309. serializationObject.shaderPath = this._shaderPath;
  61310. var name;
  61311. // Texture
  61312. serializationObject.textures = {};
  61313. for (name in this._textures) {
  61314. serializationObject.textures[name] = this._textures[name].serialize();
  61315. }
  61316. // Texture arrays
  61317. serializationObject.textureArrays = {};
  61318. for (name in this._textureArrays) {
  61319. serializationObject.textureArrays[name] = [];
  61320. var array = this._textureArrays[name];
  61321. for (var index = 0; index < array.length; index++) {
  61322. serializationObject.textureArrays[name].push(array[index].serialize());
  61323. }
  61324. }
  61325. // Float
  61326. serializationObject.floats = {};
  61327. for (name in this._floats) {
  61328. serializationObject.floats[name] = this._floats[name];
  61329. }
  61330. // Float s
  61331. serializationObject.FloatArrays = {};
  61332. for (name in this._floatsArrays) {
  61333. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  61334. }
  61335. // Color3
  61336. serializationObject.colors3 = {};
  61337. for (name in this._colors3) {
  61338. serializationObject.colors3[name] = this._colors3[name].asArray();
  61339. }
  61340. // Color3 array
  61341. serializationObject.colors3Arrays = {};
  61342. for (name in this._colors3Arrays) {
  61343. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  61344. }
  61345. // Color4
  61346. serializationObject.colors4 = {};
  61347. for (name in this._colors4) {
  61348. serializationObject.colors4[name] = this._colors4[name].asArray();
  61349. }
  61350. // Vector2
  61351. serializationObject.vectors2 = {};
  61352. for (name in this._vectors2) {
  61353. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  61354. }
  61355. // Vector3
  61356. serializationObject.vectors3 = {};
  61357. for (name in this._vectors3) {
  61358. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  61359. }
  61360. // Vector4
  61361. serializationObject.vectors4 = {};
  61362. for (name in this._vectors4) {
  61363. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  61364. }
  61365. // Matrix
  61366. serializationObject.matrices = {};
  61367. for (name in this._matrices) {
  61368. serializationObject.matrices[name] = this._matrices[name].asArray();
  61369. }
  61370. // Matrix 3x3
  61371. serializationObject.matrices3x3 = {};
  61372. for (name in this._matrices3x3) {
  61373. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  61374. }
  61375. // Matrix 2x2
  61376. serializationObject.matrices2x2 = {};
  61377. for (name in this._matrices2x2) {
  61378. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  61379. }
  61380. // Vector2Array
  61381. serializationObject.vectors2Arrays = {};
  61382. for (name in this._vectors2Arrays) {
  61383. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  61384. }
  61385. // Vector3Array
  61386. serializationObject.vectors3Arrays = {};
  61387. for (name in this._vectors3Arrays) {
  61388. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  61389. }
  61390. return serializationObject;
  61391. };
  61392. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  61393. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  61394. var name;
  61395. // Texture
  61396. for (name in source.textures) {
  61397. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  61398. }
  61399. // Texture arrays
  61400. for (name in source.textureArrays) {
  61401. var array = source.textureArrays[name];
  61402. var textureArray = new Array();
  61403. for (var index = 0; index < array.length; index++) {
  61404. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  61405. }
  61406. material.setTextureArray(name, textureArray);
  61407. }
  61408. // Float
  61409. for (name in source.floats) {
  61410. material.setFloat(name, source.floats[name]);
  61411. }
  61412. // Float s
  61413. for (name in source.floatsArrays) {
  61414. material.setFloats(name, source.floatsArrays[name]);
  61415. }
  61416. // Color3
  61417. for (name in source.colors3) {
  61418. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  61419. }
  61420. // Color3 arrays
  61421. for (name in source.colors3Arrays) {
  61422. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  61423. if (i % 3 === 0) {
  61424. arr.push([num]);
  61425. }
  61426. else {
  61427. arr[arr.length - 1].push(num);
  61428. }
  61429. return arr;
  61430. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  61431. material.setColor3Array(name, colors);
  61432. }
  61433. // Color4
  61434. for (name in source.colors4) {
  61435. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  61436. }
  61437. // Vector2
  61438. for (name in source.vectors2) {
  61439. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  61440. }
  61441. // Vector3
  61442. for (name in source.vectors3) {
  61443. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  61444. }
  61445. // Vector4
  61446. for (name in source.vectors4) {
  61447. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  61448. }
  61449. // Matrix
  61450. for (name in source.matrices) {
  61451. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  61452. }
  61453. // Matrix 3x3
  61454. for (name in source.matrices3x3) {
  61455. material.setMatrix3x3(name, source.matrices3x3[name]);
  61456. }
  61457. // Matrix 2x2
  61458. for (name in source.matrices2x2) {
  61459. material.setMatrix2x2(name, source.matrices2x2[name]);
  61460. }
  61461. // Vector2Array
  61462. for (name in source.vectors2Arrays) {
  61463. material.setArray2(name, source.vectors2Arrays[name]);
  61464. }
  61465. // Vector3Array
  61466. for (name in source.vectors3Arrays) {
  61467. material.setArray3(name, source.vectors3Arrays[name]);
  61468. }
  61469. return material;
  61470. };
  61471. return ShaderMaterial;
  61472. }(BABYLON.Material));
  61473. BABYLON.ShaderMaterial = ShaderMaterial;
  61474. })(BABYLON || (BABYLON = {}));
  61475. //# sourceMappingURL=babylon.shaderMaterial.js.map
  61476. var BABYLON;
  61477. (function (BABYLON) {
  61478. var GroundMesh = /** @class */ (function (_super) {
  61479. __extends(GroundMesh, _super);
  61480. function GroundMesh(name, scene) {
  61481. var _this = _super.call(this, name, scene) || this;
  61482. _this.generateOctree = false;
  61483. return _this;
  61484. }
  61485. GroundMesh.prototype.getClassName = function () {
  61486. return "GroundMesh";
  61487. };
  61488. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  61489. get: function () {
  61490. return Math.min(this._subdivisionsX, this._subdivisionsY);
  61491. },
  61492. enumerable: true,
  61493. configurable: true
  61494. });
  61495. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  61496. get: function () {
  61497. return this._subdivisionsX;
  61498. },
  61499. enumerable: true,
  61500. configurable: true
  61501. });
  61502. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  61503. get: function () {
  61504. return this._subdivisionsY;
  61505. },
  61506. enumerable: true,
  61507. configurable: true
  61508. });
  61509. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  61510. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  61511. this._subdivisionsX = chunksCount;
  61512. this._subdivisionsY = chunksCount;
  61513. this.subdivide(chunksCount);
  61514. // Call the octree system optimization if it is defined.
  61515. var thisAsAny = this;
  61516. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  61517. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  61518. }
  61519. };
  61520. /**
  61521. * Returns a height (y) value in the Worl system :
  61522. * the ground altitude at the coordinates (x, z) expressed in the World system.
  61523. * Returns the ground y position if (x, z) are outside the ground surface.
  61524. */
  61525. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  61526. var world = this.getWorldMatrix();
  61527. var invMat = BABYLON.Tmp.Matrix[5];
  61528. world.invertToRef(invMat);
  61529. var tmpVect = BABYLON.Tmp.Vector3[8];
  61530. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  61531. x = tmpVect.x;
  61532. z = tmpVect.z;
  61533. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61534. return this.position.y;
  61535. }
  61536. if (!this._heightQuads || this._heightQuads.length == 0) {
  61537. this._initHeightQuads();
  61538. this._computeHeightQuads();
  61539. }
  61540. var facet = this._getFacetAt(x, z);
  61541. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  61542. // return y in the World system
  61543. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  61544. return tmpVect.y;
  61545. };
  61546. /**
  61547. * Returns a normalized vector (Vector3) orthogonal to the ground
  61548. * at the ground coordinates (x, z) expressed in the World system.
  61549. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  61550. */
  61551. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  61552. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  61553. this.getNormalAtCoordinatesToRef(x, z, normal);
  61554. return normal;
  61555. };
  61556. /**
  61557. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  61558. * at the ground coordinates (x, z) expressed in the World system.
  61559. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  61560. * Returns the GroundMesh.
  61561. */
  61562. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  61563. var world = this.getWorldMatrix();
  61564. var tmpMat = BABYLON.Tmp.Matrix[5];
  61565. world.invertToRef(tmpMat);
  61566. var tmpVect = BABYLON.Tmp.Vector3[8];
  61567. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  61568. x = tmpVect.x;
  61569. z = tmpVect.z;
  61570. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61571. return this;
  61572. }
  61573. if (!this._heightQuads || this._heightQuads.length == 0) {
  61574. this._initHeightQuads();
  61575. this._computeHeightQuads();
  61576. }
  61577. var facet = this._getFacetAt(x, z);
  61578. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  61579. return this;
  61580. };
  61581. /**
  61582. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  61583. * if the ground has been updated.
  61584. * This can be used in the render loop.
  61585. * Returns the GroundMesh.
  61586. */
  61587. GroundMesh.prototype.updateCoordinateHeights = function () {
  61588. if (!this._heightQuads || this._heightQuads.length == 0) {
  61589. this._initHeightQuads();
  61590. }
  61591. this._computeHeightQuads();
  61592. return this;
  61593. };
  61594. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  61595. GroundMesh.prototype._getFacetAt = function (x, z) {
  61596. // retrieve col and row from x, z coordinates in the ground local system
  61597. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  61598. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  61599. var quad = this._heightQuads[row * this._subdivisionsX + col];
  61600. var facet;
  61601. if (z < quad.slope.x * x + quad.slope.y) {
  61602. facet = quad.facet1;
  61603. }
  61604. else {
  61605. facet = quad.facet2;
  61606. }
  61607. return facet;
  61608. };
  61609. // Creates and populates the heightMap array with "facet" elements :
  61610. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  61611. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61612. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61613. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61614. // Returns the GroundMesh.
  61615. GroundMesh.prototype._initHeightQuads = function () {
  61616. var subdivisionsX = this._subdivisionsX;
  61617. var subdivisionsY = this._subdivisionsY;
  61618. this._heightQuads = new Array();
  61619. for (var row = 0; row < subdivisionsY; row++) {
  61620. for (var col = 0; col < subdivisionsX; col++) {
  61621. 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) };
  61622. this._heightQuads[row * subdivisionsX + col] = quad;
  61623. }
  61624. }
  61625. return this;
  61626. };
  61627. // Compute each quad element values and update the the heightMap array :
  61628. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61629. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61630. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61631. // Returns the GroundMesh.
  61632. GroundMesh.prototype._computeHeightQuads = function () {
  61633. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61634. if (!positions) {
  61635. return this;
  61636. }
  61637. var v1 = BABYLON.Tmp.Vector3[3];
  61638. var v2 = BABYLON.Tmp.Vector3[2];
  61639. var v3 = BABYLON.Tmp.Vector3[1];
  61640. var v4 = BABYLON.Tmp.Vector3[0];
  61641. var v1v2 = BABYLON.Tmp.Vector3[4];
  61642. var v1v3 = BABYLON.Tmp.Vector3[5];
  61643. var v1v4 = BABYLON.Tmp.Vector3[6];
  61644. var norm1 = BABYLON.Tmp.Vector3[7];
  61645. var norm2 = BABYLON.Tmp.Vector3[8];
  61646. var i = 0;
  61647. var j = 0;
  61648. var k = 0;
  61649. var cd = 0; // 2D slope coefficient : z = cd * x + h
  61650. var h = 0;
  61651. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  61652. var d2 = 0;
  61653. var subdivisionsX = this._subdivisionsX;
  61654. var subdivisionsY = this._subdivisionsY;
  61655. for (var row = 0; row < subdivisionsY; row++) {
  61656. for (var col = 0; col < subdivisionsX; col++) {
  61657. i = col * 3;
  61658. j = row * (subdivisionsX + 1) * 3;
  61659. k = (row + 1) * (subdivisionsX + 1) * 3;
  61660. v1.x = positions[j + i];
  61661. v1.y = positions[j + i + 1];
  61662. v1.z = positions[j + i + 2];
  61663. v2.x = positions[j + i + 3];
  61664. v2.y = positions[j + i + 4];
  61665. v2.z = positions[j + i + 5];
  61666. v3.x = positions[k + i];
  61667. v3.y = positions[k + i + 1];
  61668. v3.z = positions[k + i + 2];
  61669. v4.x = positions[k + i + 3];
  61670. v4.y = positions[k + i + 4];
  61671. v4.z = positions[k + i + 5];
  61672. // 2D slope V1V4
  61673. cd = (v4.z - v1.z) / (v4.x - v1.x);
  61674. h = v1.z - cd * v1.x; // v1 belongs to the slope
  61675. // facet equations :
  61676. // we compute each facet normal vector
  61677. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  61678. // we compute the value d by applying the equation to v1 which belongs to the plane
  61679. // then we store the facet equation in a Vector4
  61680. v2.subtractToRef(v1, v1v2);
  61681. v3.subtractToRef(v1, v1v3);
  61682. v4.subtractToRef(v1, v1v4);
  61683. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  61684. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  61685. norm1.normalize();
  61686. norm2.normalize();
  61687. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  61688. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  61689. var quad = this._heightQuads[row * subdivisionsX + col];
  61690. quad.slope.copyFromFloats(cd, h);
  61691. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  61692. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  61693. }
  61694. }
  61695. return this;
  61696. };
  61697. GroundMesh.prototype.serialize = function (serializationObject) {
  61698. _super.prototype.serialize.call(this, serializationObject);
  61699. serializationObject.subdivisionsX = this._subdivisionsX;
  61700. serializationObject.subdivisionsY = this._subdivisionsY;
  61701. serializationObject.minX = this._minX;
  61702. serializationObject.maxX = this._maxX;
  61703. serializationObject.minZ = this._minZ;
  61704. serializationObject.maxZ = this._maxZ;
  61705. serializationObject.width = this._width;
  61706. serializationObject.height = this._height;
  61707. };
  61708. GroundMesh.Parse = function (parsedMesh, scene) {
  61709. var result = new GroundMesh(parsedMesh.name, scene);
  61710. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  61711. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  61712. result._minX = parsedMesh.minX;
  61713. result._maxX = parsedMesh.maxX;
  61714. result._minZ = parsedMesh.minZ;
  61715. result._maxZ = parsedMesh.maxZ;
  61716. result._width = parsedMesh.width;
  61717. result._height = parsedMesh.height;
  61718. return result;
  61719. };
  61720. return GroundMesh;
  61721. }(BABYLON.Mesh));
  61722. BABYLON.GroundMesh = GroundMesh;
  61723. })(BABYLON || (BABYLON = {}));
  61724. //# sourceMappingURL=babylon.groundMesh.js.map
  61725. var BABYLON;
  61726. (function (BABYLON) {
  61727. /**
  61728. * Creates an instance based on a source mesh.
  61729. */
  61730. var InstancedMesh = /** @class */ (function (_super) {
  61731. __extends(InstancedMesh, _super);
  61732. function InstancedMesh(name, source) {
  61733. var _this = _super.call(this, name, source.getScene()) || this;
  61734. source.instances.push(_this);
  61735. _this._sourceMesh = source;
  61736. _this.position.copyFrom(source.position);
  61737. _this.rotation.copyFrom(source.rotation);
  61738. _this.scaling.copyFrom(source.scaling);
  61739. if (source.rotationQuaternion) {
  61740. _this.rotationQuaternion = source.rotationQuaternion.clone();
  61741. }
  61742. _this.infiniteDistance = source.infiniteDistance;
  61743. _this.setPivotMatrix(source.getPivotMatrix());
  61744. _this.refreshBoundingInfo();
  61745. _this._syncSubMeshes();
  61746. return _this;
  61747. }
  61748. /**
  61749. * Returns the string "InstancedMesh".
  61750. */
  61751. InstancedMesh.prototype.getClassName = function () {
  61752. return "InstancedMesh";
  61753. };
  61754. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  61755. // Methods
  61756. get: function () {
  61757. return this._sourceMesh.receiveShadows;
  61758. },
  61759. enumerable: true,
  61760. configurable: true
  61761. });
  61762. Object.defineProperty(InstancedMesh.prototype, "material", {
  61763. get: function () {
  61764. return this._sourceMesh.material;
  61765. },
  61766. enumerable: true,
  61767. configurable: true
  61768. });
  61769. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  61770. get: function () {
  61771. return this._sourceMesh.visibility;
  61772. },
  61773. enumerable: true,
  61774. configurable: true
  61775. });
  61776. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  61777. get: function () {
  61778. return this._sourceMesh.skeleton;
  61779. },
  61780. enumerable: true,
  61781. configurable: true
  61782. });
  61783. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  61784. get: function () {
  61785. return this._sourceMesh.renderingGroupId;
  61786. },
  61787. set: function (value) {
  61788. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  61789. return;
  61790. }
  61791. //no-op with warning
  61792. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  61793. },
  61794. enumerable: true,
  61795. configurable: true
  61796. });
  61797. /**
  61798. * Returns the total number of vertices (integer).
  61799. */
  61800. InstancedMesh.prototype.getTotalVertices = function () {
  61801. return this._sourceMesh.getTotalVertices();
  61802. };
  61803. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  61804. get: function () {
  61805. return this._sourceMesh;
  61806. },
  61807. enumerable: true,
  61808. configurable: true
  61809. });
  61810. /**
  61811. * Is this node ready to be used/rendered
  61812. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  61813. * @return {boolean} is it ready
  61814. */
  61815. InstancedMesh.prototype.isReady = function (completeCheck) {
  61816. if (completeCheck === void 0) { completeCheck = false; }
  61817. return this._sourceMesh.isReady(completeCheck, true);
  61818. };
  61819. /**
  61820. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  61821. */
  61822. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  61823. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  61824. };
  61825. /**
  61826. * Sets the vertex data of the mesh geometry for the requested `kind`.
  61827. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  61828. * The `data` are either a numeric array either a Float32Array.
  61829. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  61830. * 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).
  61831. * Note that a new underlying VertexBuffer object is created each call.
  61832. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  61833. *
  61834. * Possible `kind` values :
  61835. * - BABYLON.VertexBuffer.PositionKind
  61836. * - BABYLON.VertexBuffer.UVKind
  61837. * - BABYLON.VertexBuffer.UV2Kind
  61838. * - BABYLON.VertexBuffer.UV3Kind
  61839. * - BABYLON.VertexBuffer.UV4Kind
  61840. * - BABYLON.VertexBuffer.UV5Kind
  61841. * - BABYLON.VertexBuffer.UV6Kind
  61842. * - BABYLON.VertexBuffer.ColorKind
  61843. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61844. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61845. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61846. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61847. *
  61848. * Returns the Mesh.
  61849. */
  61850. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  61851. if (this.sourceMesh) {
  61852. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  61853. }
  61854. return this.sourceMesh;
  61855. };
  61856. /**
  61857. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  61858. * If the mesh has no geometry, it is simply returned as it is.
  61859. * The `data` are either a numeric array either a Float32Array.
  61860. * No new underlying VertexBuffer object is created.
  61861. * 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.
  61862. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  61863. *
  61864. * Possible `kind` values :
  61865. * - BABYLON.VertexBuffer.PositionKind
  61866. * - BABYLON.VertexBuffer.UVKind
  61867. * - BABYLON.VertexBuffer.UV2Kind
  61868. * - BABYLON.VertexBuffer.UV3Kind
  61869. * - BABYLON.VertexBuffer.UV4Kind
  61870. * - BABYLON.VertexBuffer.UV5Kind
  61871. * - BABYLON.VertexBuffer.UV6Kind
  61872. * - BABYLON.VertexBuffer.ColorKind
  61873. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61874. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61875. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61876. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61877. *
  61878. * Returns the Mesh.
  61879. */
  61880. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  61881. if (this.sourceMesh) {
  61882. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  61883. }
  61884. return this.sourceMesh;
  61885. };
  61886. /**
  61887. * Sets the mesh indices.
  61888. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  61889. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  61890. * This method creates a new index buffer each call.
  61891. * Returns the Mesh.
  61892. */
  61893. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  61894. if (totalVertices === void 0) { totalVertices = null; }
  61895. if (this.sourceMesh) {
  61896. this.sourceMesh.setIndices(indices, totalVertices);
  61897. }
  61898. return this.sourceMesh;
  61899. };
  61900. /**
  61901. * Boolean : True if the mesh owns the requested kind of data.
  61902. */
  61903. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  61904. return this._sourceMesh.isVerticesDataPresent(kind);
  61905. };
  61906. /**
  61907. * Returns an array of indices (IndicesArray).
  61908. */
  61909. InstancedMesh.prototype.getIndices = function () {
  61910. return this._sourceMesh.getIndices();
  61911. };
  61912. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  61913. get: function () {
  61914. return this._sourceMesh._positions;
  61915. },
  61916. enumerable: true,
  61917. configurable: true
  61918. });
  61919. /**
  61920. * Sets a new updated BoundingInfo to the mesh.
  61921. * Returns the mesh.
  61922. */
  61923. InstancedMesh.prototype.refreshBoundingInfo = function () {
  61924. var meshBB = this._sourceMesh.getBoundingInfo();
  61925. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61926. this._updateBoundingInfo();
  61927. return this;
  61928. };
  61929. /** @hidden */
  61930. InstancedMesh.prototype._preActivate = function () {
  61931. if (this._currentLOD) {
  61932. this._currentLOD._preActivate();
  61933. }
  61934. return this;
  61935. };
  61936. /** @hidden */
  61937. InstancedMesh.prototype._activate = function (renderId) {
  61938. if (this._currentLOD) {
  61939. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61940. }
  61941. return this;
  61942. };
  61943. /**
  61944. * Returns the current associated LOD AbstractMesh.
  61945. */
  61946. InstancedMesh.prototype.getLOD = function (camera) {
  61947. if (!camera) {
  61948. return this;
  61949. }
  61950. var boundingInfo = this.getBoundingInfo();
  61951. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61952. if (this._currentLOD === this.sourceMesh) {
  61953. return this;
  61954. }
  61955. return this._currentLOD;
  61956. };
  61957. /** @hidden */
  61958. InstancedMesh.prototype._syncSubMeshes = function () {
  61959. this.releaseSubMeshes();
  61960. if (this._sourceMesh.subMeshes) {
  61961. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61962. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61963. }
  61964. }
  61965. return this;
  61966. };
  61967. /** @hidden */
  61968. InstancedMesh.prototype._generatePointsArray = function () {
  61969. return this._sourceMesh._generatePointsArray();
  61970. };
  61971. /**
  61972. * Creates a new InstancedMesh from the current mesh.
  61973. * - name (string) : the cloned mesh name
  61974. * - newParent (optional Node) : the optional Node to parent the clone to.
  61975. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61976. *
  61977. * Returns the clone.
  61978. */
  61979. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61980. var result = this._sourceMesh.createInstance(name);
  61981. // Deep copy
  61982. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61983. // Bounding info
  61984. this.refreshBoundingInfo();
  61985. // Parent
  61986. if (newParent) {
  61987. result.parent = newParent;
  61988. }
  61989. if (!doNotCloneChildren) {
  61990. // Children
  61991. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61992. var mesh = this.getScene().meshes[index];
  61993. if (mesh.parent === this) {
  61994. mesh.clone(mesh.name, result);
  61995. }
  61996. }
  61997. }
  61998. result.computeWorldMatrix(true);
  61999. return result;
  62000. };
  62001. /**
  62002. * Disposes the InstancedMesh.
  62003. * Returns nothing.
  62004. */
  62005. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  62006. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  62007. // Remove from mesh
  62008. var index = this._sourceMesh.instances.indexOf(this);
  62009. this._sourceMesh.instances.splice(index, 1);
  62010. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  62011. };
  62012. return InstancedMesh;
  62013. }(BABYLON.AbstractMesh));
  62014. BABYLON.InstancedMesh = InstancedMesh;
  62015. })(BABYLON || (BABYLON = {}));
  62016. //# sourceMappingURL=babylon.instancedMesh.js.map
  62017. var BABYLON;
  62018. (function (BABYLON) {
  62019. var LinesMesh = /** @class */ (function (_super) {
  62020. __extends(LinesMesh, _super);
  62021. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  62022. if (scene === void 0) { scene = null; }
  62023. if (parent === void 0) { parent = null; }
  62024. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  62025. _this.useVertexColor = useVertexColor;
  62026. _this.useVertexAlpha = useVertexAlpha;
  62027. _this.color = new BABYLON.Color3(1, 1, 1);
  62028. _this.alpha = 1;
  62029. if (source) {
  62030. _this.color = source.color.clone();
  62031. _this.alpha = source.alpha;
  62032. _this.useVertexColor = source.useVertexColor;
  62033. _this.useVertexAlpha = source.useVertexAlpha;
  62034. }
  62035. _this._intersectionThreshold = 0.1;
  62036. var defines = [];
  62037. var options = {
  62038. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  62039. uniforms: ["world", "viewProjection"],
  62040. needAlphaBlending: true,
  62041. defines: defines
  62042. };
  62043. if (useVertexAlpha === false) {
  62044. options.needAlphaBlending = false;
  62045. }
  62046. if (!useVertexColor) {
  62047. options.uniforms.push("color");
  62048. }
  62049. else {
  62050. options.defines.push("#define VERTEXCOLOR");
  62051. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  62052. }
  62053. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  62054. return _this;
  62055. }
  62056. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  62057. /**
  62058. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62059. * This margin is expressed in world space coordinates, so its value may vary.
  62060. * Default value is 0.1
  62061. * @returns the intersection Threshold value.
  62062. */
  62063. get: function () {
  62064. return this._intersectionThreshold;
  62065. },
  62066. /**
  62067. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62068. * This margin is expressed in world space coordinates, so its value may vary.
  62069. * @param value the new threshold to apply
  62070. */
  62071. set: function (value) {
  62072. if (this._intersectionThreshold === value) {
  62073. return;
  62074. }
  62075. this._intersectionThreshold = value;
  62076. if (this.geometry) {
  62077. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  62078. }
  62079. },
  62080. enumerable: true,
  62081. configurable: true
  62082. });
  62083. /**
  62084. * Returns the string "LineMesh"
  62085. */
  62086. LinesMesh.prototype.getClassName = function () {
  62087. return "LinesMesh";
  62088. };
  62089. Object.defineProperty(LinesMesh.prototype, "material", {
  62090. /**
  62091. * @hidden
  62092. */
  62093. get: function () {
  62094. return this._colorShader;
  62095. },
  62096. /**
  62097. * @hidden
  62098. */
  62099. set: function (value) {
  62100. // Do nothing
  62101. },
  62102. enumerable: true,
  62103. configurable: true
  62104. });
  62105. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  62106. /**
  62107. * @hidden
  62108. */
  62109. get: function () {
  62110. return false;
  62111. },
  62112. enumerable: true,
  62113. configurable: true
  62114. });
  62115. /** @hidden */
  62116. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  62117. if (!this._geometry) {
  62118. return this;
  62119. }
  62120. // VBOs
  62121. this._geometry._bind(this._colorShader.getEffect());
  62122. // Color
  62123. if (!this.useVertexColor) {
  62124. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  62125. }
  62126. return this;
  62127. };
  62128. /** @hidden */
  62129. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  62130. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  62131. return this;
  62132. }
  62133. var engine = this.getScene().getEngine();
  62134. // Draw order
  62135. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  62136. return this;
  62137. };
  62138. LinesMesh.prototype.dispose = function (doNotRecurse) {
  62139. this._colorShader.dispose();
  62140. _super.prototype.dispose.call(this, doNotRecurse);
  62141. };
  62142. /**
  62143. * Returns a new LineMesh object cloned from the current one.
  62144. */
  62145. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62146. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  62147. };
  62148. return LinesMesh;
  62149. }(BABYLON.Mesh));
  62150. BABYLON.LinesMesh = LinesMesh;
  62151. })(BABYLON || (BABYLON = {}));
  62152. //# sourceMappingURL=babylon.linesMesh.js.map
  62153. var BABYLON;
  62154. (function (BABYLON) {
  62155. /**
  62156. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62157. * The underlying implementation relies on an associative array to ensure the best performances.
  62158. * The value can be anything including 'null' but except 'undefined'
  62159. */
  62160. var StringDictionary = /** @class */ (function () {
  62161. function StringDictionary() {
  62162. this._count = 0;
  62163. this._data = {};
  62164. }
  62165. /**
  62166. * This will clear this dictionary and copy the content from the 'source' one.
  62167. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62168. * @param source the dictionary to take the content from and copy to this dictionary
  62169. */
  62170. StringDictionary.prototype.copyFrom = function (source) {
  62171. var _this = this;
  62172. this.clear();
  62173. source.forEach(function (t, v) { return _this.add(t, v); });
  62174. };
  62175. /**
  62176. * Get a value based from its key
  62177. * @param key the given key to get the matching value from
  62178. * @return the value if found, otherwise undefined is returned
  62179. */
  62180. StringDictionary.prototype.get = function (key) {
  62181. var val = this._data[key];
  62182. if (val !== undefined) {
  62183. return val;
  62184. }
  62185. return undefined;
  62186. };
  62187. /**
  62188. * Get a value from its key or add it if it doesn't exist.
  62189. * This method will ensure you that a given key/data will be present in the dictionary.
  62190. * @param key the given key to get the matching value from
  62191. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62192. * The factory will only be invoked if there's no data for the given key.
  62193. * @return the value corresponding to the key.
  62194. */
  62195. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62196. var val = this.get(key);
  62197. if (val !== undefined) {
  62198. return val;
  62199. }
  62200. val = factory(key);
  62201. if (val) {
  62202. this.add(key, val);
  62203. }
  62204. return val;
  62205. };
  62206. /**
  62207. * Get a value from its key if present in the dictionary otherwise add it
  62208. * @param key the key to get the value from
  62209. * @param val if there's no such key/value pair in the dictionary add it with this value
  62210. * @return the value corresponding to the key
  62211. */
  62212. StringDictionary.prototype.getOrAdd = function (key, val) {
  62213. var curVal = this.get(key);
  62214. if (curVal !== undefined) {
  62215. return curVal;
  62216. }
  62217. this.add(key, val);
  62218. return val;
  62219. };
  62220. /**
  62221. * Check if there's a given key in the dictionary
  62222. * @param key the key to check for
  62223. * @return true if the key is present, false otherwise
  62224. */
  62225. StringDictionary.prototype.contains = function (key) {
  62226. return this._data[key] !== undefined;
  62227. };
  62228. /**
  62229. * Add a new key and its corresponding value
  62230. * @param key the key to add
  62231. * @param value the value corresponding to the key
  62232. * @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
  62233. */
  62234. StringDictionary.prototype.add = function (key, value) {
  62235. if (this._data[key] !== undefined) {
  62236. return false;
  62237. }
  62238. this._data[key] = value;
  62239. ++this._count;
  62240. return true;
  62241. };
  62242. StringDictionary.prototype.set = function (key, value) {
  62243. if (this._data[key] === undefined) {
  62244. return false;
  62245. }
  62246. this._data[key] = value;
  62247. return true;
  62248. };
  62249. /**
  62250. * Get the element of the given key and remove it from the dictionary
  62251. * @param key
  62252. */
  62253. StringDictionary.prototype.getAndRemove = function (key) {
  62254. var val = this.get(key);
  62255. if (val !== undefined) {
  62256. delete this._data[key];
  62257. --this._count;
  62258. return val;
  62259. }
  62260. return null;
  62261. };
  62262. /**
  62263. * Remove a key/value from the dictionary.
  62264. * @param key the key to remove
  62265. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62266. */
  62267. StringDictionary.prototype.remove = function (key) {
  62268. if (this.contains(key)) {
  62269. delete this._data[key];
  62270. --this._count;
  62271. return true;
  62272. }
  62273. return false;
  62274. };
  62275. /**
  62276. * Clear the whole content of the dictionary
  62277. */
  62278. StringDictionary.prototype.clear = function () {
  62279. this._data = {};
  62280. this._count = 0;
  62281. };
  62282. Object.defineProperty(StringDictionary.prototype, "count", {
  62283. get: function () {
  62284. return this._count;
  62285. },
  62286. enumerable: true,
  62287. configurable: true
  62288. });
  62289. /**
  62290. * Execute a callback on each key/val of the dictionary.
  62291. * Note that you can remove any element in this dictionary in the callback implementation
  62292. * @param callback the callback to execute on a given key/value pair
  62293. */
  62294. StringDictionary.prototype.forEach = function (callback) {
  62295. for (var cur in this._data) {
  62296. var val = this._data[cur];
  62297. callback(cur, val);
  62298. }
  62299. };
  62300. /**
  62301. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62302. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62303. * Note that you can remove any element in this dictionary in the callback implementation
  62304. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62305. */
  62306. StringDictionary.prototype.first = function (callback) {
  62307. for (var cur in this._data) {
  62308. var val = this._data[cur];
  62309. var res = callback(cur, val);
  62310. if (res) {
  62311. return res;
  62312. }
  62313. }
  62314. return null;
  62315. };
  62316. return StringDictionary;
  62317. }());
  62318. BABYLON.StringDictionary = StringDictionary;
  62319. })(BABYLON || (BABYLON = {}));
  62320. //# sourceMappingURL=babylon.stringDictionary.js.map
  62321. var BABYLON;
  62322. (function (BABYLON) {
  62323. var Debug;
  62324. (function (Debug) {
  62325. /**
  62326. * Class used to render a debug view of a given skeleton
  62327. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  62328. */
  62329. var SkeletonViewer = /** @class */ (function () {
  62330. /**
  62331. * Creates a new SkeletonViewer
  62332. * @param skeleton defines the skeleton to render
  62333. * @param mesh defines the mesh attached to the skeleton
  62334. * @param scene defines the hosting scene
  62335. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  62336. * @param renderingGroupId defines the rendering group id to use with the viewer
  62337. */
  62338. function SkeletonViewer(
  62339. /** defines the skeleton to render */
  62340. skeleton,
  62341. /** defines the mesh attached to the skeleton */
  62342. mesh, scene,
  62343. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  62344. autoUpdateBonesMatrices,
  62345. /** defines the rendering group id to use with the viewer */
  62346. renderingGroupId) {
  62347. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62348. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62349. this.skeleton = skeleton;
  62350. this.mesh = mesh;
  62351. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62352. this.renderingGroupId = renderingGroupId;
  62353. /** Gets or sets the color used to render the skeleton */
  62354. this.color = BABYLON.Color3.White();
  62355. this._debugLines = new Array();
  62356. this._isEnabled = false;
  62357. this._scene = scene;
  62358. this.update();
  62359. this._renderFunction = this.update.bind(this);
  62360. }
  62361. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62362. get: function () {
  62363. return this._isEnabled;
  62364. },
  62365. /** Gets or sets a boolean indicating if the viewer is enabled */
  62366. set: function (value) {
  62367. if (this._isEnabled === value) {
  62368. return;
  62369. }
  62370. this._isEnabled = value;
  62371. if (value) {
  62372. this._scene.registerBeforeRender(this._renderFunction);
  62373. }
  62374. else {
  62375. this._scene.unregisterBeforeRender(this._renderFunction);
  62376. }
  62377. },
  62378. enumerable: true,
  62379. configurable: true
  62380. });
  62381. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  62382. if (x === void 0) { x = 0; }
  62383. if (y === void 0) { y = 0; }
  62384. if (z === void 0) { z = 0; }
  62385. var tmat = BABYLON.Tmp.Matrix[0];
  62386. var parentBone = bone.getParent();
  62387. tmat.copyFrom(bone.getLocalMatrix());
  62388. if (x !== 0 || y !== 0 || z !== 0) {
  62389. var tmat2 = BABYLON.Tmp.Matrix[1];
  62390. BABYLON.Matrix.IdentityToRef(tmat2);
  62391. tmat2.m[12] = x;
  62392. tmat2.m[13] = y;
  62393. tmat2.m[14] = z;
  62394. tmat2.multiplyToRef(tmat, tmat);
  62395. }
  62396. if (parentBone) {
  62397. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  62398. }
  62399. tmat.multiplyToRef(meshMat, tmat);
  62400. position.x = tmat.m[12];
  62401. position.y = tmat.m[13];
  62402. position.z = tmat.m[14];
  62403. };
  62404. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  62405. var len = bones.length;
  62406. var meshPos = this.mesh.position;
  62407. for (var i = 0; i < len; i++) {
  62408. var bone = bones[i];
  62409. var points = this._debugLines[i];
  62410. if (!points) {
  62411. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62412. this._debugLines[i] = points;
  62413. }
  62414. this._getBonePosition(points[0], bone, meshMat);
  62415. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  62416. points[0].subtractInPlace(meshPos);
  62417. points[1].subtractInPlace(meshPos);
  62418. }
  62419. };
  62420. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  62421. var len = bones.length;
  62422. var boneNum = 0;
  62423. var meshPos = this.mesh.position;
  62424. for (var i = len - 1; i >= 0; i--) {
  62425. var childBone = bones[i];
  62426. var parentBone = childBone.getParent();
  62427. if (!parentBone) {
  62428. continue;
  62429. }
  62430. var points = this._debugLines[boneNum];
  62431. if (!points) {
  62432. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62433. this._debugLines[boneNum] = points;
  62434. }
  62435. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  62436. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  62437. points[0].subtractInPlace(meshPos);
  62438. points[1].subtractInPlace(meshPos);
  62439. boneNum++;
  62440. }
  62441. };
  62442. /** Update the viewer to sync with current skeleton state */
  62443. SkeletonViewer.prototype.update = function () {
  62444. if (this.autoUpdateBonesMatrices) {
  62445. this.skeleton.computeAbsoluteTransforms();
  62446. }
  62447. if (this.skeleton.bones[0].length === undefined) {
  62448. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62449. }
  62450. else {
  62451. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62452. }
  62453. if (!this._debugMesh) {
  62454. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  62455. this._debugMesh.renderingGroupId = this.renderingGroupId;
  62456. }
  62457. else {
  62458. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  62459. }
  62460. this._debugMesh.position.copyFrom(this.mesh.position);
  62461. this._debugMesh.color = this.color;
  62462. };
  62463. /** Release associated resources */
  62464. SkeletonViewer.prototype.dispose = function () {
  62465. if (this._debugMesh) {
  62466. this.isEnabled = false;
  62467. this._debugMesh.dispose();
  62468. this._debugMesh = null;
  62469. }
  62470. };
  62471. return SkeletonViewer;
  62472. }());
  62473. Debug.SkeletonViewer = SkeletonViewer;
  62474. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62475. })(BABYLON || (BABYLON = {}));
  62476. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62477. /**
  62478. * Module Debug contains the (visual) components to debug a scene correctly
  62479. */
  62480. var BABYLON;
  62481. (function (BABYLON) {
  62482. var Debug;
  62483. (function (Debug) {
  62484. /**
  62485. * The Axes viewer will show 3 axes in a specific point in space
  62486. */
  62487. var AxesViewer = /** @class */ (function () {
  62488. /**
  62489. * Creates a new AxesViewer
  62490. * @param scene defines the hosting scene
  62491. * @param scaleLines defines a number used to scale line length (1 by default)
  62492. */
  62493. function AxesViewer(scene, scaleLines) {
  62494. if (scaleLines === void 0) { scaleLines = 1; }
  62495. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62496. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62497. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62498. /**
  62499. * Gets or sets a number used to scale line length
  62500. */
  62501. this.scaleLines = 1;
  62502. this.scaleLines = scaleLines;
  62503. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62504. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62505. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62506. this._xmesh.renderingGroupId = 2;
  62507. this._ymesh.renderingGroupId = 2;
  62508. this._zmesh.renderingGroupId = 2;
  62509. this._xmesh.material.checkReadyOnlyOnce = true;
  62510. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62511. this._ymesh.material.checkReadyOnlyOnce = true;
  62512. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62513. this._zmesh.material.checkReadyOnlyOnce = true;
  62514. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62515. this.scene = scene;
  62516. }
  62517. /**
  62518. * Force the viewer to update
  62519. * @param position defines the position of the viewer
  62520. * @param xaxis defines the x axis of the viewer
  62521. * @param yaxis defines the y axis of the viewer
  62522. * @param zaxis defines the z axis of the viewer
  62523. */
  62524. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62525. var scaleLines = this.scaleLines;
  62526. if (this._xmesh) {
  62527. this._xmesh.position.copyFrom(position);
  62528. }
  62529. if (this._ymesh) {
  62530. this._ymesh.position.copyFrom(position);
  62531. }
  62532. if (this._zmesh) {
  62533. this._zmesh.position.copyFrom(position);
  62534. }
  62535. var point2 = this._xline[1];
  62536. point2.x = xaxis.x * scaleLines;
  62537. point2.y = xaxis.y * scaleLines;
  62538. point2.z = xaxis.z * scaleLines;
  62539. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  62540. point2 = this._yline[1];
  62541. point2.x = yaxis.x * scaleLines;
  62542. point2.y = yaxis.y * scaleLines;
  62543. point2.z = yaxis.z * scaleLines;
  62544. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  62545. point2 = this._zline[1];
  62546. point2.x = zaxis.x * scaleLines;
  62547. point2.y = zaxis.y * scaleLines;
  62548. point2.z = zaxis.z * scaleLines;
  62549. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  62550. };
  62551. /** Releases resources */
  62552. AxesViewer.prototype.dispose = function () {
  62553. if (this._xmesh) {
  62554. this._xmesh.dispose();
  62555. }
  62556. if (this._ymesh) {
  62557. this._ymesh.dispose();
  62558. }
  62559. if (this._zmesh) {
  62560. this._zmesh.dispose();
  62561. }
  62562. this._xmesh = null;
  62563. this._ymesh = null;
  62564. this._zmesh = null;
  62565. this.scene = null;
  62566. };
  62567. return AxesViewer;
  62568. }());
  62569. Debug.AxesViewer = AxesViewer;
  62570. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62571. })(BABYLON || (BABYLON = {}));
  62572. //# sourceMappingURL=babylon.axesViewer.js.map
  62573. var BABYLON;
  62574. (function (BABYLON) {
  62575. var Debug;
  62576. (function (Debug) {
  62577. /**
  62578. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  62579. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  62580. */
  62581. var BoneAxesViewer = /** @class */ (function (_super) {
  62582. __extends(BoneAxesViewer, _super);
  62583. /**
  62584. * Creates a new BoneAxesViewer
  62585. * @param scene defines the hosting scene
  62586. * @param bone defines the target bone
  62587. * @param mesh defines the target mesh
  62588. * @param scaleLines defines a scaling factor for line length (1 by default)
  62589. */
  62590. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62591. if (scaleLines === void 0) { scaleLines = 1; }
  62592. var _this = _super.call(this, scene, scaleLines) || this;
  62593. /** Gets current position */
  62594. _this.pos = BABYLON.Vector3.Zero();
  62595. /** Gets direction of X axis */
  62596. _this.xaxis = BABYLON.Vector3.Zero();
  62597. /** Gets direction of Y axis */
  62598. _this.yaxis = BABYLON.Vector3.Zero();
  62599. /** Gets direction of Z axis */
  62600. _this.zaxis = BABYLON.Vector3.Zero();
  62601. _this.mesh = mesh;
  62602. _this.bone = bone;
  62603. return _this;
  62604. }
  62605. /**
  62606. * Force the viewer to update
  62607. */
  62608. BoneAxesViewer.prototype.update = function () {
  62609. if (!this.mesh || !this.bone) {
  62610. return;
  62611. }
  62612. var bone = this.bone;
  62613. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62614. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62615. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62616. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62617. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62618. };
  62619. /** Releases resources */
  62620. BoneAxesViewer.prototype.dispose = function () {
  62621. if (this.mesh) {
  62622. this.mesh = null;
  62623. this.bone = null;
  62624. _super.prototype.dispose.call(this);
  62625. }
  62626. };
  62627. return BoneAxesViewer;
  62628. }(Debug.AxesViewer));
  62629. Debug.BoneAxesViewer = BoneAxesViewer;
  62630. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62631. })(BABYLON || (BABYLON = {}));
  62632. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62633. var BABYLON;
  62634. (function (BABYLON) {
  62635. /**
  62636. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62637. * in order to better appreciate the issue one might have.
  62638. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62639. */
  62640. var RayHelper = /** @class */ (function () {
  62641. /**
  62642. * Instantiate a new ray helper.
  62643. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62644. * in order to better appreciate the issue one might have.
  62645. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62646. * @param ray Defines the ray we are currently tryin to visualize
  62647. */
  62648. function RayHelper(ray) {
  62649. this.ray = ray;
  62650. }
  62651. /**
  62652. * Helper function to create a colored helper in a scene in one line.
  62653. * @param ray Defines the ray we are currently tryin to visualize
  62654. * @param scene Defines the scene the ray is used in
  62655. * @param color Defines the color we want to see the ray in
  62656. * @returns The newly created ray helper.
  62657. */
  62658. RayHelper.CreateAndShow = function (ray, scene, color) {
  62659. var helper = new RayHelper(ray);
  62660. helper.show(scene, color);
  62661. return helper;
  62662. };
  62663. /**
  62664. * Shows the ray we are willing to debug.
  62665. * @param scene Defines the scene the ray needs to be rendered in
  62666. * @param color Defines the color the ray needs to be rendered in
  62667. */
  62668. RayHelper.prototype.show = function (scene, color) {
  62669. if (!this._renderFunction && this.ray) {
  62670. var ray = this.ray;
  62671. this._renderFunction = this._render.bind(this);
  62672. this._scene = scene;
  62673. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62674. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62675. if (this._renderFunction) {
  62676. this._scene.registerBeforeRender(this._renderFunction);
  62677. }
  62678. }
  62679. if (color && this._renderLine) {
  62680. this._renderLine.color.copyFrom(color);
  62681. }
  62682. };
  62683. /**
  62684. * Hides the ray we are debugging.
  62685. */
  62686. RayHelper.prototype.hide = function () {
  62687. if (this._renderFunction && this._scene) {
  62688. this._scene.unregisterBeforeRender(this._renderFunction);
  62689. this._scene = null;
  62690. this._renderFunction = null;
  62691. if (this._renderLine) {
  62692. this._renderLine.dispose();
  62693. this._renderLine = null;
  62694. }
  62695. this._renderPoints = [];
  62696. }
  62697. };
  62698. RayHelper.prototype._render = function () {
  62699. var ray = this.ray;
  62700. if (!ray) {
  62701. return;
  62702. }
  62703. var point = this._renderPoints[1];
  62704. var len = Math.min(ray.length, 1000000);
  62705. point.copyFrom(ray.direction);
  62706. point.scaleInPlace(len);
  62707. point.addInPlace(ray.origin);
  62708. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62709. };
  62710. /**
  62711. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  62712. * @param mesh Defines the mesh we want the helper attached to
  62713. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  62714. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  62715. * @param length Defines the length of the ray
  62716. */
  62717. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62718. this._attachedToMesh = mesh;
  62719. var ray = this.ray;
  62720. if (!ray) {
  62721. return;
  62722. }
  62723. if (!ray.direction) {
  62724. ray.direction = BABYLON.Vector3.Zero();
  62725. }
  62726. if (!ray.origin) {
  62727. ray.origin = BABYLON.Vector3.Zero();
  62728. }
  62729. if (length) {
  62730. ray.length = length;
  62731. }
  62732. if (!meshSpaceOrigin) {
  62733. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62734. }
  62735. if (!meshSpaceDirection) {
  62736. // -1 so that this will work with Mesh.lookAt
  62737. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62738. }
  62739. if (!this._meshSpaceDirection) {
  62740. this._meshSpaceDirection = meshSpaceDirection.clone();
  62741. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62742. }
  62743. else {
  62744. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62745. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62746. }
  62747. if (!this._updateToMeshFunction) {
  62748. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62749. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62750. }
  62751. this._updateToMesh();
  62752. };
  62753. /**
  62754. * Detach the ray helper from the mesh it has previously been attached to.
  62755. */
  62756. RayHelper.prototype.detachFromMesh = function () {
  62757. if (this._attachedToMesh) {
  62758. if (this._updateToMeshFunction) {
  62759. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62760. }
  62761. this._attachedToMesh = null;
  62762. this._updateToMeshFunction = null;
  62763. }
  62764. };
  62765. RayHelper.prototype._updateToMesh = function () {
  62766. var ray = this.ray;
  62767. if (!this._attachedToMesh || !ray) {
  62768. return;
  62769. }
  62770. if (this._attachedToMesh._isDisposed) {
  62771. this.detachFromMesh();
  62772. return;
  62773. }
  62774. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62775. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62776. };
  62777. /**
  62778. * Dispose the helper and release its associated resources.
  62779. */
  62780. RayHelper.prototype.dispose = function () {
  62781. this.hide();
  62782. this.detachFromMesh();
  62783. this.ray = null;
  62784. };
  62785. return RayHelper;
  62786. }());
  62787. BABYLON.RayHelper = RayHelper;
  62788. })(BABYLON || (BABYLON = {}));
  62789. //# sourceMappingURL=babylon.rayHelper.js.map
  62790. var BABYLON;
  62791. (function (BABYLON) {
  62792. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  62793. get: function () {
  62794. if (!this._debugLayer) {
  62795. this._debugLayer = new DebugLayer(this);
  62796. }
  62797. return this._debugLayer;
  62798. },
  62799. enumerable: true,
  62800. configurable: true
  62801. });
  62802. /**
  62803. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62804. * what is happening in your scene
  62805. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62806. */
  62807. var DebugLayer = /** @class */ (function () {
  62808. /**
  62809. * Instantiates a new debug layer.
  62810. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62811. * what is happening in your scene
  62812. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62813. * @param scene Defines the scene to inspect
  62814. */
  62815. function DebugLayer(scene) {
  62816. var _this = this;
  62817. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62818. /**
  62819. * Observable triggered when a property is changed through the inspector.
  62820. */
  62821. this.onPropertyChangedObservable = new BABYLON.Observable();
  62822. this._scene = scene;
  62823. this._scene.onDisposeObservable.add(function () {
  62824. // Debug layer
  62825. if (_this._scene._debugLayer) {
  62826. _this._scene._debugLayer.hide();
  62827. }
  62828. });
  62829. }
  62830. /** Creates the inspector window. */
  62831. DebugLayer.prototype._createInspector = function (config) {
  62832. if (config === void 0) { config = {}; }
  62833. var popup = config.popup || false;
  62834. var initialTab = config.initialTab || 0;
  62835. var parentElement = config.parentElement || null;
  62836. if (!this._inspector) {
  62837. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62838. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62839. } // else nothing to do as instance is already created
  62840. };
  62841. /**
  62842. * Get if the inspector is visible or not.
  62843. * @returns true if visible otherwise, false
  62844. */
  62845. DebugLayer.prototype.isVisible = function () {
  62846. if (!this._inspector) {
  62847. return false;
  62848. }
  62849. return true;
  62850. };
  62851. /**
  62852. * Hide the inspector and close its window.
  62853. */
  62854. DebugLayer.prototype.hide = function () {
  62855. if (this._inspector) {
  62856. try {
  62857. this._inspector.dispose();
  62858. }
  62859. catch (e) {
  62860. // If the inspector has been removed directly from the inspector tool
  62861. }
  62862. this.onPropertyChangedObservable.clear();
  62863. this._inspector = null;
  62864. }
  62865. };
  62866. /**
  62867. *
  62868. * Launch the debugLayer.
  62869. *
  62870. * initialTab:
  62871. * | Value | Tab Name |
  62872. * | --- | --- |
  62873. * | 0 | Scene |
  62874. * | 1 | Console |
  62875. * | 2 | Stats |
  62876. * | 3 | Textures |
  62877. * | 4 | Mesh |
  62878. * | 5 | Light |
  62879. * | 6 | Material |
  62880. * | 7 | GLTF |
  62881. * | 8 | GUI |
  62882. * | 9 | Physics |
  62883. * | 10 | Camera |
  62884. * | 11 | Audio |
  62885. *
  62886. * @param config Define the configuration of the inspector
  62887. */
  62888. DebugLayer.prototype.show = function (config) {
  62889. if (config === void 0) { config = {}; }
  62890. if (typeof this.BJSINSPECTOR == 'undefined') {
  62891. // Load inspector and add it to the DOM
  62892. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62893. }
  62894. else {
  62895. // Otherwise creates the inspector
  62896. this._createInspector(config);
  62897. }
  62898. };
  62899. /**
  62900. * Gets the active tab
  62901. * @return the index of the active tab or -1 if the inspector is hidden
  62902. */
  62903. DebugLayer.prototype.getActiveTab = function () {
  62904. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  62905. };
  62906. /**
  62907. * Define the url to get the inspector script from.
  62908. * By default it uses the babylonjs CDN.
  62909. * @ignoreNaming
  62910. */
  62911. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62912. return DebugLayer;
  62913. }());
  62914. BABYLON.DebugLayer = DebugLayer;
  62915. })(BABYLON || (BABYLON = {}));
  62916. //# sourceMappingURL=babylon.debugLayer.js.map
  62917. var BABYLON;
  62918. (function (BABYLON) {
  62919. var Debug;
  62920. (function (Debug) {
  62921. /**
  62922. * Used to show the physics impostor around the specific mesh
  62923. */
  62924. var PhysicsViewer = /** @class */ (function () {
  62925. /**
  62926. * Creates a new PhysicsViewer
  62927. * @param scene defines the hosting scene
  62928. */
  62929. function PhysicsViewer(scene) {
  62930. /** @hidden */
  62931. this._impostors = [];
  62932. /** @hidden */
  62933. this._meshes = [];
  62934. /** @hidden */
  62935. this._numMeshes = 0;
  62936. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62937. var physicEngine = this._scene.getPhysicsEngine();
  62938. if (physicEngine) {
  62939. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  62940. }
  62941. }
  62942. /** @hidden */
  62943. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62944. var plugin = this._physicsEnginePlugin;
  62945. for (var i = 0; i < this._numMeshes; i++) {
  62946. var impostor = this._impostors[i];
  62947. if (!impostor) {
  62948. continue;
  62949. }
  62950. if (impostor.isDisposed) {
  62951. this.hideImpostor(this._impostors[i--]);
  62952. }
  62953. else {
  62954. var mesh = this._meshes[i];
  62955. if (mesh && plugin) {
  62956. plugin.syncMeshWithImpostor(mesh, impostor);
  62957. }
  62958. }
  62959. }
  62960. };
  62961. /**
  62962. * Renders a specified physic impostor
  62963. * @param impostor defines the impostor to render
  62964. */
  62965. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62966. if (!this._scene) {
  62967. return;
  62968. }
  62969. for (var i = 0; i < this._numMeshes; i++) {
  62970. if (this._impostors[i] == impostor) {
  62971. return;
  62972. }
  62973. }
  62974. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62975. if (debugMesh) {
  62976. this._impostors[this._numMeshes] = impostor;
  62977. this._meshes[this._numMeshes] = debugMesh;
  62978. if (this._numMeshes === 0) {
  62979. this._renderFunction = this._updateDebugMeshes.bind(this);
  62980. this._scene.registerBeforeRender(this._renderFunction);
  62981. }
  62982. this._numMeshes++;
  62983. }
  62984. };
  62985. /**
  62986. * Hides a specified physic impostor
  62987. * @param impostor defines the impostor to hide
  62988. */
  62989. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62990. if (!impostor || !this._scene) {
  62991. return;
  62992. }
  62993. var removed = false;
  62994. for (var i = 0; i < this._numMeshes; i++) {
  62995. if (this._impostors[i] == impostor) {
  62996. var mesh = this._meshes[i];
  62997. if (!mesh) {
  62998. continue;
  62999. }
  63000. this._scene.removeMesh(mesh);
  63001. mesh.dispose();
  63002. this._numMeshes--;
  63003. if (this._numMeshes > 0) {
  63004. this._meshes[i] = this._meshes[this._numMeshes];
  63005. this._impostors[i] = this._impostors[this._numMeshes];
  63006. this._meshes[this._numMeshes] = null;
  63007. this._impostors[this._numMeshes] = null;
  63008. }
  63009. else {
  63010. this._meshes[0] = null;
  63011. this._impostors[0] = null;
  63012. }
  63013. removed = true;
  63014. break;
  63015. }
  63016. }
  63017. if (removed && this._numMeshes === 0) {
  63018. this._scene.unregisterBeforeRender(this._renderFunction);
  63019. }
  63020. };
  63021. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63022. if (!this._debugMaterial) {
  63023. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63024. this._debugMaterial.wireframe = true;
  63025. }
  63026. return this._debugMaterial;
  63027. };
  63028. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63029. if (!this._debugBoxMesh) {
  63030. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63031. this._debugBoxMesh.renderingGroupId = 1;
  63032. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63033. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63034. scene.removeMesh(this._debugBoxMesh);
  63035. }
  63036. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63037. };
  63038. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63039. if (!this._debugSphereMesh) {
  63040. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63041. this._debugSphereMesh.renderingGroupId = 1;
  63042. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63043. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63044. scene.removeMesh(this._debugSphereMesh);
  63045. }
  63046. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63047. };
  63048. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63049. var mesh = null;
  63050. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63051. mesh = this._getDebugBoxMesh(scene);
  63052. impostor.getBoxSizeToRef(mesh.scaling);
  63053. }
  63054. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63055. mesh = this._getDebugSphereMesh(scene);
  63056. var radius = impostor.getRadius();
  63057. mesh.scaling.x = radius * 2;
  63058. mesh.scaling.y = radius * 2;
  63059. mesh.scaling.z = radius * 2;
  63060. }
  63061. return mesh;
  63062. };
  63063. /** Releases all resources */
  63064. PhysicsViewer.prototype.dispose = function () {
  63065. for (var i = 0; i < this._numMeshes; i++) {
  63066. this.hideImpostor(this._impostors[i]);
  63067. }
  63068. if (this._debugBoxMesh) {
  63069. this._debugBoxMesh.dispose();
  63070. }
  63071. if (this._debugSphereMesh) {
  63072. this._debugSphereMesh.dispose();
  63073. }
  63074. if (this._debugMaterial) {
  63075. this._debugMaterial.dispose();
  63076. }
  63077. this._impostors.length = 0;
  63078. this._scene = null;
  63079. this._physicsEnginePlugin = null;
  63080. };
  63081. return PhysicsViewer;
  63082. }());
  63083. Debug.PhysicsViewer = PhysicsViewer;
  63084. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63085. })(BABYLON || (BABYLON = {}));
  63086. //# sourceMappingURL=babylon.physicsViewer.js.map
  63087. var BABYLON;
  63088. (function (BABYLON) {
  63089. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  63090. get: function () {
  63091. return this._forceShowBoundingBoxes || false;
  63092. },
  63093. set: function (value) {
  63094. this._forceShowBoundingBoxes = value;
  63095. // Lazyly creates a BB renderer if needed.
  63096. if (value) {
  63097. this.getBoundingBoxRenderer();
  63098. }
  63099. },
  63100. enumerable: true,
  63101. configurable: true
  63102. });
  63103. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  63104. if (!this._boundingBoxRenderer) {
  63105. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  63106. }
  63107. return this._boundingBoxRenderer;
  63108. };
  63109. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  63110. get: function () {
  63111. return this._showBoundingBox || false;
  63112. },
  63113. set: function (value) {
  63114. this._showBoundingBox = value;
  63115. // Lazyly creates a BB renderer if needed.
  63116. if (value) {
  63117. this.getScene().getBoundingBoxRenderer();
  63118. }
  63119. },
  63120. enumerable: true,
  63121. configurable: true
  63122. });
  63123. /**
  63124. * Component responsible of rendering the bounding box of the meshes in a scene.
  63125. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  63126. */
  63127. var BoundingBoxRenderer = /** @class */ (function () {
  63128. /**
  63129. * Instantiates a new bounding box renderer in a scene.
  63130. * @param scene the scene the renderer renders in
  63131. */
  63132. function BoundingBoxRenderer(scene) {
  63133. /**
  63134. * The component name helpfull to identify the component in the list of scene components.
  63135. */
  63136. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  63137. /**
  63138. * Color of the bounding box lines placed in front of an object
  63139. */
  63140. this.frontColor = new BABYLON.Color3(1, 1, 1);
  63141. /**
  63142. * Color of the bounding box lines placed behind an object
  63143. */
  63144. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  63145. /**
  63146. * Defines if the renderer should show the back lines or not
  63147. */
  63148. this.showBackLines = true;
  63149. /**
  63150. * @hidden
  63151. */
  63152. this.renderList = new BABYLON.SmartArray(32);
  63153. this._vertexBuffers = {};
  63154. this.scene = scene;
  63155. scene._addComponent(this);
  63156. }
  63157. /**
  63158. * Registers the component in a given scene
  63159. */
  63160. BoundingBoxRenderer.prototype.register = function () {
  63161. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  63162. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  63163. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  63164. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  63165. };
  63166. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  63167. if (mesh.showSubMeshesBoundingBox) {
  63168. var boundingInfo = subMesh.getBoundingInfo();
  63169. if (boundingInfo !== null && boundingInfo !== undefined) {
  63170. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  63171. this.renderList.push(boundingInfo.boundingBox);
  63172. }
  63173. }
  63174. };
  63175. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  63176. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  63177. var boundingInfo = sourceMesh.getBoundingInfo();
  63178. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  63179. this.renderList.push(boundingInfo.boundingBox);
  63180. }
  63181. };
  63182. BoundingBoxRenderer.prototype._prepareRessources = function () {
  63183. if (this._colorShader) {
  63184. return;
  63185. }
  63186. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  63187. attributes: [BABYLON.VertexBuffer.PositionKind],
  63188. uniforms: ["world", "viewProjection", "color"]
  63189. });
  63190. var engine = this.scene.getEngine();
  63191. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  63192. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  63193. this._createIndexBuffer();
  63194. };
  63195. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  63196. var engine = this.scene.getEngine();
  63197. 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]);
  63198. };
  63199. /**
  63200. * Rebuilds the elements related to this component in case of
  63201. * context lost for instance.
  63202. */
  63203. BoundingBoxRenderer.prototype.rebuild = function () {
  63204. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63205. if (vb) {
  63206. vb._rebuild();
  63207. }
  63208. this._createIndexBuffer();
  63209. };
  63210. /**
  63211. * @hidden
  63212. */
  63213. BoundingBoxRenderer.prototype.reset = function () {
  63214. this.renderList.reset();
  63215. };
  63216. /**
  63217. * Render the bounding boxes of a specific rendering group
  63218. * @param renderingGroupId defines the rendering group to render
  63219. */
  63220. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  63221. if (this.renderList.length === 0) {
  63222. return;
  63223. }
  63224. this._prepareRessources();
  63225. if (!this._colorShader.isReady()) {
  63226. return;
  63227. }
  63228. var engine = this.scene.getEngine();
  63229. engine.setDepthWrite(false);
  63230. this._colorShader._preBind();
  63231. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  63232. var boundingBox = this.renderList.data[boundingBoxIndex];
  63233. if (boundingBox._tag !== renderingGroupId) {
  63234. continue;
  63235. }
  63236. var min = boundingBox.minimum;
  63237. var max = boundingBox.maximum;
  63238. var diff = max.subtract(min);
  63239. var median = min.add(diff.scale(0.5));
  63240. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63241. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63242. .multiply(boundingBox.getWorldMatrix());
  63243. // VBOs
  63244. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63245. if (this.showBackLines) {
  63246. // Back
  63247. engine.setDepthFunctionToGreaterOrEqual();
  63248. this.scene.resetCachedMaterial();
  63249. this._colorShader.setColor4("color", this.backColor.toColor4());
  63250. this._colorShader.bind(worldMatrix);
  63251. // Draw order
  63252. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63253. }
  63254. // Front
  63255. engine.setDepthFunctionToLess();
  63256. this.scene.resetCachedMaterial();
  63257. this._colorShader.setColor4("color", this.frontColor.toColor4());
  63258. this._colorShader.bind(worldMatrix);
  63259. // Draw order
  63260. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63261. }
  63262. this._colorShader.unbind();
  63263. engine.setDepthFunctionToLessOrEqual();
  63264. engine.setDepthWrite(true);
  63265. };
  63266. /**
  63267. * In case of occlusion queries, we can render the occlusion bounding box through this method
  63268. * @param mesh Define the mesh to render the occlusion bounding box for
  63269. */
  63270. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  63271. this._prepareRessources();
  63272. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  63273. return;
  63274. }
  63275. var engine = this.scene.getEngine();
  63276. engine.setDepthWrite(false);
  63277. engine.setColorWrite(false);
  63278. this._colorShader._preBind();
  63279. var boundingBox = mesh._boundingInfo.boundingBox;
  63280. var min = boundingBox.minimum;
  63281. var max = boundingBox.maximum;
  63282. var diff = max.subtract(min);
  63283. var median = min.add(diff.scale(0.5));
  63284. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63285. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63286. .multiply(boundingBox.getWorldMatrix());
  63287. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63288. engine.setDepthFunctionToLess();
  63289. this.scene.resetCachedMaterial();
  63290. this._colorShader.bind(worldMatrix);
  63291. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63292. this._colorShader.unbind();
  63293. engine.setDepthFunctionToLessOrEqual();
  63294. engine.setDepthWrite(true);
  63295. engine.setColorWrite(true);
  63296. };
  63297. /**
  63298. * Dispose and release the resources attached to this renderer.
  63299. */
  63300. BoundingBoxRenderer.prototype.dispose = function () {
  63301. if (!this._colorShader) {
  63302. return;
  63303. }
  63304. this.renderList.dispose();
  63305. this._colorShader.dispose();
  63306. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63307. if (buffer) {
  63308. buffer.dispose();
  63309. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63310. }
  63311. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  63312. };
  63313. return BoundingBoxRenderer;
  63314. }());
  63315. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63316. })(BABYLON || (BABYLON = {}));
  63317. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63318. var BABYLON;
  63319. (function (BABYLON) {
  63320. BABYLON.Engine.prototype.createTransformFeedback = function () {
  63321. return this._gl.createTransformFeedback();
  63322. };
  63323. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  63324. this._gl.deleteTransformFeedback(value);
  63325. };
  63326. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  63327. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  63328. };
  63329. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  63330. if (usePoints === void 0) { usePoints = true; }
  63331. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  63332. };
  63333. BABYLON.Engine.prototype.endTransformFeedback = function () {
  63334. this._gl.endTransformFeedback();
  63335. };
  63336. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  63337. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  63338. };
  63339. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  63340. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  63341. };
  63342. })(BABYLON || (BABYLON = {}));
  63343. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  63344. var BABYLON;
  63345. (function (BABYLON) {
  63346. /**
  63347. * This represents a GPU particle system in Babylon
  63348. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  63349. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  63350. */
  63351. var GPUParticleSystem = /** @class */ (function (_super) {
  63352. __extends(GPUParticleSystem, _super);
  63353. /**
  63354. * Instantiates a GPU particle system.
  63355. * 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.
  63356. * @param name The name of the particle system
  63357. * @param options The options used to create the system
  63358. * @param scene The scene the particle system belongs to
  63359. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  63360. */
  63361. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  63362. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  63363. var _this = _super.call(this, name) || this;
  63364. /**
  63365. * The layer mask we are rendering the particles through.
  63366. */
  63367. _this.layerMask = 0x0FFFFFFF;
  63368. _this._accumulatedCount = 0;
  63369. _this._targetIndex = 0;
  63370. _this._currentRenderId = -1;
  63371. _this._started = false;
  63372. _this._stopped = false;
  63373. _this._timeDelta = 0;
  63374. _this._attributesStrideSize = 21;
  63375. _this._actualFrame = 0;
  63376. _this._rawTextureWidth = 256;
  63377. /**
  63378. * An event triggered when the system is disposed.
  63379. */
  63380. _this.onDisposeObservable = new BABYLON.Observable();
  63381. /**
  63382. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  63383. * to override the particles.
  63384. */
  63385. _this.forceDepthWrite = false;
  63386. _this._preWarmDone = false;
  63387. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63388. // Setup the default processing configuration to the scene.
  63389. _this._attachImageProcessingConfiguration(null);
  63390. _this._engine = _this._scene.getEngine();
  63391. if (!options.randomTextureSize) {
  63392. delete options.randomTextureSize;
  63393. }
  63394. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  63395. var optionsAsNumber = options;
  63396. if (isFinite(optionsAsNumber)) {
  63397. fullOptions.capacity = optionsAsNumber;
  63398. }
  63399. _this._capacity = fullOptions.capacity;
  63400. _this._activeCount = fullOptions.capacity;
  63401. _this._currentActiveCount = 0;
  63402. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  63403. _this._scene.particleSystems.push(_this);
  63404. _this._updateEffectOptions = {
  63405. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  63406. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  63407. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  63408. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  63409. uniformBuffersNames: [],
  63410. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  63411. defines: "",
  63412. fallbacks: null,
  63413. onCompiled: null,
  63414. onError: null,
  63415. indexParameters: null,
  63416. maxSimultaneousLights: 0,
  63417. transformFeedbackVaryings: []
  63418. };
  63419. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  63420. // Random data
  63421. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  63422. var d = [];
  63423. for (var i = 0; i < maxTextureSize; ++i) {
  63424. d.push(Math.random());
  63425. d.push(Math.random());
  63426. d.push(Math.random());
  63427. d.push(Math.random());
  63428. }
  63429. _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);
  63430. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63431. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63432. d = [];
  63433. for (var i = 0; i < maxTextureSize; ++i) {
  63434. d.push(Math.random());
  63435. d.push(Math.random());
  63436. d.push(Math.random());
  63437. d.push(Math.random());
  63438. }
  63439. _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);
  63440. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63441. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63442. _this._randomTextureSize = maxTextureSize;
  63443. return _this;
  63444. }
  63445. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  63446. /**
  63447. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  63448. */
  63449. get: function () {
  63450. if (!BABYLON.Engine.LastCreatedEngine) {
  63451. return false;
  63452. }
  63453. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  63454. },
  63455. enumerable: true,
  63456. configurable: true
  63457. });
  63458. /**
  63459. * Gets the maximum number of particles active at the same time.
  63460. * @returns The max number of active particles.
  63461. */
  63462. GPUParticleSystem.prototype.getCapacity = function () {
  63463. return this._capacity;
  63464. };
  63465. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  63466. /**
  63467. * Gets or set the number of active particles
  63468. */
  63469. get: function () {
  63470. return this._activeCount;
  63471. },
  63472. set: function (value) {
  63473. this._activeCount = Math.min(value, this._capacity);
  63474. },
  63475. enumerable: true,
  63476. configurable: true
  63477. });
  63478. /**
  63479. * Is this system ready to be used/rendered
  63480. * @return true if the system is ready
  63481. */
  63482. GPUParticleSystem.prototype.isReady = function () {
  63483. if (!this._updateEffect) {
  63484. this._recreateUpdateEffect();
  63485. this._recreateRenderEffect();
  63486. return false;
  63487. }
  63488. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  63489. return false;
  63490. }
  63491. return true;
  63492. };
  63493. /**
  63494. * Gets if the system has been started. (Note: this will still be true after stop is called)
  63495. * @returns True if it has been started, otherwise false.
  63496. */
  63497. GPUParticleSystem.prototype.isStarted = function () {
  63498. return this._started;
  63499. };
  63500. /**
  63501. * Starts the particle system and begins to emit
  63502. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  63503. */
  63504. GPUParticleSystem.prototype.start = function (delay) {
  63505. var _this = this;
  63506. if (delay === void 0) { delay = this.startDelay; }
  63507. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  63508. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  63509. }
  63510. if (delay) {
  63511. setTimeout(function () {
  63512. _this.start(0);
  63513. }, delay);
  63514. return;
  63515. }
  63516. this._started = true;
  63517. this._stopped = false;
  63518. this._preWarmDone = false;
  63519. // Animations
  63520. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  63521. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  63522. }
  63523. };
  63524. /**
  63525. * Stops the particle system.
  63526. */
  63527. GPUParticleSystem.prototype.stop = function () {
  63528. this._stopped = true;
  63529. };
  63530. /**
  63531. * Remove all active particles
  63532. */
  63533. GPUParticleSystem.prototype.reset = function () {
  63534. this._releaseBuffers();
  63535. this._releaseVAOs();
  63536. this._currentActiveCount = 0;
  63537. this._targetIndex = 0;
  63538. };
  63539. /**
  63540. * Returns the string "GPUParticleSystem"
  63541. * @returns a string containing the class name
  63542. */
  63543. GPUParticleSystem.prototype.getClassName = function () {
  63544. return "GPUParticleSystem";
  63545. };
  63546. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  63547. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  63548. this._releaseBuffers();
  63549. return this;
  63550. };
  63551. /**
  63552. * Adds a new color gradient
  63553. * @param gradient defines the gradient to use (between 0 and 1)
  63554. * @param color1 defines the color to affect to the specified gradient
  63555. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  63556. * @returns the current particle system
  63557. */
  63558. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  63559. if (!this._colorGradients) {
  63560. this._colorGradients = [];
  63561. }
  63562. var colorGradient = new BABYLON.ColorGradient();
  63563. colorGradient.gradient = gradient;
  63564. colorGradient.color1 = color1;
  63565. this._colorGradients.push(colorGradient);
  63566. this._colorGradients.sort(function (a, b) {
  63567. if (a.gradient < b.gradient) {
  63568. return -1;
  63569. }
  63570. else if (a.gradient > b.gradient) {
  63571. return 1;
  63572. }
  63573. return 0;
  63574. });
  63575. if (this._colorGradientsTexture) {
  63576. this._colorGradientsTexture.dispose();
  63577. this._colorGradientsTexture = null;
  63578. }
  63579. this._releaseBuffers();
  63580. return this;
  63581. };
  63582. /**
  63583. * Remove a specific color gradient
  63584. * @param gradient defines the gradient to remove
  63585. * @returns the current particle system
  63586. */
  63587. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  63588. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  63589. this._colorGradientsTexture = null;
  63590. return this;
  63591. };
  63592. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  63593. var valueGradient = new BABYLON.FactorGradient();
  63594. valueGradient.gradient = gradient;
  63595. valueGradient.factor1 = factor;
  63596. factorGradients.push(valueGradient);
  63597. factorGradients.sort(function (a, b) {
  63598. if (a.gradient < b.gradient) {
  63599. return -1;
  63600. }
  63601. else if (a.gradient > b.gradient) {
  63602. return 1;
  63603. }
  63604. return 0;
  63605. });
  63606. this._releaseBuffers();
  63607. };
  63608. /**
  63609. * Adds a new size gradient
  63610. * @param gradient defines the gradient to use (between 0 and 1)
  63611. * @param factor defines the size factor to affect to the specified gradient
  63612. * @returns the current particle system
  63613. */
  63614. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  63615. if (!this._sizeGradients) {
  63616. this._sizeGradients = [];
  63617. }
  63618. this._addFactorGradient(this._sizeGradients, gradient, factor);
  63619. if (this._sizeGradientsTexture) {
  63620. this._sizeGradientsTexture.dispose();
  63621. this._sizeGradientsTexture = null;
  63622. }
  63623. this._releaseBuffers();
  63624. return this;
  63625. };
  63626. /**
  63627. * Remove a specific size gradient
  63628. * @param gradient defines the gradient to remove
  63629. * @returns the current particle system
  63630. */
  63631. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  63632. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  63633. this._sizeGradientsTexture = null;
  63634. return this;
  63635. };
  63636. /**
  63637. * Adds a new angular speed gradient
  63638. * @param gradient defines the gradient to use (between 0 and 1)
  63639. * @param factor defines the angular speed to affect to the specified gradient
  63640. * @returns the current particle system
  63641. */
  63642. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  63643. if (!this._angularSpeedGradients) {
  63644. this._angularSpeedGradients = [];
  63645. }
  63646. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  63647. if (this._angularSpeedGradientsTexture) {
  63648. this._angularSpeedGradientsTexture.dispose();
  63649. this._angularSpeedGradientsTexture = null;
  63650. }
  63651. this._releaseBuffers();
  63652. return this;
  63653. };
  63654. /**
  63655. * Remove a specific angular speed gradient
  63656. * @param gradient defines the gradient to remove
  63657. * @returns the current particle system
  63658. */
  63659. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  63660. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  63661. this._angularSpeedGradientsTexture = null;
  63662. return this;
  63663. };
  63664. /**
  63665. * Adds a new velocity gradient
  63666. * @param gradient defines the gradient to use (between 0 and 1)
  63667. * @param factor defines the velocity to affect to the specified gradient
  63668. * @returns the current particle system
  63669. */
  63670. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  63671. if (!this._velocityGradients) {
  63672. this._velocityGradients = [];
  63673. }
  63674. this._addFactorGradient(this._velocityGradients, gradient, factor);
  63675. if (this._velocityGradientsTexture) {
  63676. this._velocityGradientsTexture.dispose();
  63677. this._velocityGradientsTexture = null;
  63678. }
  63679. this._releaseBuffers();
  63680. return this;
  63681. };
  63682. /**
  63683. * Remove a specific velocity gradient
  63684. * @param gradient defines the gradient to remove
  63685. * @returns the current particle system
  63686. */
  63687. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  63688. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  63689. this._velocityGradientsTexture = null;
  63690. return this;
  63691. };
  63692. /**
  63693. * Adds a new limit velocity gradient
  63694. * @param gradient defines the gradient to use (between 0 and 1)
  63695. * @param factor defines the limit velocity value to affect to the specified gradient
  63696. * @returns the current particle system
  63697. */
  63698. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  63699. if (!this._limitVelocityGradients) {
  63700. this._limitVelocityGradients = [];
  63701. }
  63702. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  63703. if (this._limitVelocityGradientsTexture) {
  63704. this._limitVelocityGradientsTexture.dispose();
  63705. this._limitVelocityGradientsTexture = null;
  63706. }
  63707. this._releaseBuffers();
  63708. return this;
  63709. };
  63710. /**
  63711. * Remove a specific limit velocity gradient
  63712. * @param gradient defines the gradient to remove
  63713. * @returns the current particle system
  63714. */
  63715. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  63716. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  63717. this._limitVelocityGradientsTexture = null;
  63718. return this;
  63719. };
  63720. /**
  63721. * Adds a new drag gradient
  63722. * @param gradient defines the gradient to use (between 0 and 1)
  63723. * @param factor defines the drag value to affect to the specified gradient
  63724. * @returns the current particle system
  63725. */
  63726. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  63727. if (!this._dragGradients) {
  63728. this._dragGradients = [];
  63729. }
  63730. this._addFactorGradient(this._dragGradients, gradient, factor);
  63731. if (this._dragGradientsTexture) {
  63732. this._dragGradientsTexture.dispose();
  63733. this._dragGradientsTexture = null;
  63734. }
  63735. this._releaseBuffers();
  63736. return this;
  63737. };
  63738. /**
  63739. * Remove a specific drag gradient
  63740. * @param gradient defines the gradient to remove
  63741. * @returns the current particle system
  63742. */
  63743. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  63744. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  63745. this._dragGradientsTexture = null;
  63746. return this;
  63747. };
  63748. /**
  63749. * Not supported by GPUParticleSystem
  63750. * @param gradient defines the gradient to use (between 0 and 1)
  63751. * @param factor defines the emit rate value to affect to the specified gradient
  63752. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63753. * @returns the current particle system
  63754. */
  63755. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  63756. // Do nothing as emit rate is not supported by GPUParticleSystem
  63757. return this;
  63758. };
  63759. /**
  63760. * Not supported by GPUParticleSystem
  63761. * @param gradient defines the gradient to remove
  63762. * @returns the current particle system
  63763. */
  63764. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  63765. // Do nothing as emit rate is not supported by GPUParticleSystem
  63766. return this;
  63767. };
  63768. /**
  63769. * Not supported by GPUParticleSystem
  63770. * @param gradient defines the gradient to use (between 0 and 1)
  63771. * @param factor defines the start size value to affect to the specified gradient
  63772. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63773. * @returns the current particle system
  63774. */
  63775. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  63776. // Do nothing as start size is not supported by GPUParticleSystem
  63777. return this;
  63778. };
  63779. /**
  63780. * Not supported by GPUParticleSystem
  63781. * @param gradient defines the gradient to remove
  63782. * @returns the current particle system
  63783. */
  63784. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  63785. // Do nothing as start size is not supported by GPUParticleSystem
  63786. return this;
  63787. };
  63788. /**
  63789. * Not supported by GPUParticleSystem
  63790. * @param gradient defines the gradient to use (between 0 and 1)
  63791. * @param min defines the color remap minimal range
  63792. * @param max defines the color remap maximal range
  63793. * @returns the current particle system
  63794. */
  63795. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  63796. // Do nothing as start size is not supported by GPUParticleSystem
  63797. return this;
  63798. };
  63799. /**
  63800. * Not supported by GPUParticleSystem
  63801. * @param gradient defines the gradient to remove
  63802. * @returns the current particle system
  63803. */
  63804. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  63805. // Do nothing as start size is not supported by GPUParticleSystem
  63806. return this;
  63807. };
  63808. /**
  63809. * Not supported by GPUParticleSystem
  63810. * @param gradient defines the gradient to use (between 0 and 1)
  63811. * @param min defines the alpha remap minimal range
  63812. * @param max defines the alpha remap maximal range
  63813. * @returns the current particle system
  63814. */
  63815. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  63816. // Do nothing as start size is not supported by GPUParticleSystem
  63817. return this;
  63818. };
  63819. /**
  63820. * Not supported by GPUParticleSystem
  63821. * @param gradient defines the gradient to remove
  63822. * @returns the current particle system
  63823. */
  63824. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  63825. // Do nothing as start size is not supported by GPUParticleSystem
  63826. return this;
  63827. };
  63828. /**
  63829. * Not supported by GPUParticleSystem
  63830. * @param gradient defines the gradient to use (between 0 and 1)
  63831. * @param color defines the color to affect to the specified gradient
  63832. * @returns the current particle system
  63833. */
  63834. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  63835. //Not supported by GPUParticleSystem
  63836. return this;
  63837. };
  63838. /**
  63839. * Not supported by GPUParticleSystem
  63840. * @param gradient defines the gradient to remove
  63841. * @returns the current particle system
  63842. */
  63843. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  63844. //Not supported by GPUParticleSystem
  63845. return this;
  63846. };
  63847. /**
  63848. * Not supported by GPUParticleSystem
  63849. * @returns the list of ramp gradients
  63850. */
  63851. GPUParticleSystem.prototype.getRampGradients = function () {
  63852. return null;
  63853. };
  63854. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  63855. /**
  63856. * Not supported by GPUParticleSystem
  63857. * Gets or sets a boolean indicating that ramp gradients must be used
  63858. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  63859. */
  63860. get: function () {
  63861. //Not supported by GPUParticleSystem
  63862. return false;
  63863. },
  63864. set: function (value) {
  63865. //Not supported by GPUParticleSystem
  63866. },
  63867. enumerable: true,
  63868. configurable: true
  63869. });
  63870. /**
  63871. * Not supported by GPUParticleSystem
  63872. * @param gradient defines the gradient to use (between 0 and 1)
  63873. * @param factor defines the life time factor to affect to the specified gradient
  63874. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63875. * @returns the current particle system
  63876. */
  63877. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  63878. //Not supported by GPUParticleSystem
  63879. return this;
  63880. };
  63881. /**
  63882. * Not supported by GPUParticleSystem
  63883. * @param gradient defines the gradient to remove
  63884. * @returns the current particle system
  63885. */
  63886. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  63887. //Not supported by GPUParticleSystem
  63888. return this;
  63889. };
  63890. GPUParticleSystem.prototype._reset = function () {
  63891. this._releaseBuffers();
  63892. };
  63893. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  63894. var updateVertexBuffers = {};
  63895. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  63896. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  63897. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  63898. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  63899. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  63900. var offset = 12;
  63901. if (!this._colorGradientsTexture) {
  63902. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  63903. offset += 4;
  63904. }
  63905. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  63906. offset += 3;
  63907. if (!this._isBillboardBased) {
  63908. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  63909. offset += 3;
  63910. }
  63911. if (this._angularSpeedGradientsTexture) {
  63912. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  63913. offset += 1;
  63914. }
  63915. else {
  63916. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  63917. offset += 2;
  63918. }
  63919. if (this._isAnimationSheetEnabled) {
  63920. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  63921. offset += 1;
  63922. if (this.spriteRandomStartCell) {
  63923. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  63924. offset += 1;
  63925. }
  63926. }
  63927. if (this.noiseTexture) {
  63928. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  63929. offset += 3;
  63930. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  63931. offset += 3;
  63932. }
  63933. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  63934. this._engine.bindArrayBuffer(null);
  63935. return vao;
  63936. };
  63937. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  63938. var renderVertexBuffers = {};
  63939. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  63940. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  63941. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  63942. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  63943. var offset = 12;
  63944. if (!this._colorGradientsTexture) {
  63945. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  63946. offset += 4;
  63947. }
  63948. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  63949. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  63950. }
  63951. offset += 3; // Direction
  63952. if (!this._isBillboardBased) {
  63953. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  63954. offset += 3;
  63955. }
  63956. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  63957. if (this._angularSpeedGradientsTexture) {
  63958. offset++;
  63959. }
  63960. else {
  63961. offset += 2;
  63962. }
  63963. if (this._isAnimationSheetEnabled) {
  63964. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  63965. offset += 1;
  63966. if (this.spriteRandomStartCell) {
  63967. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  63968. offset += 1;
  63969. }
  63970. }
  63971. if (this.noiseTexture) {
  63972. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  63973. offset += 3;
  63974. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  63975. offset += 3;
  63976. }
  63977. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  63978. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  63979. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  63980. this._engine.bindArrayBuffer(null);
  63981. return vao;
  63982. };
  63983. GPUParticleSystem.prototype._initialize = function (force) {
  63984. if (force === void 0) { force = false; }
  63985. if (this._buffer0 && !force) {
  63986. return;
  63987. }
  63988. var engine = this._scene.getEngine();
  63989. var data = new Array();
  63990. if (!this.isBillboardBased) {
  63991. this._attributesStrideSize += 3;
  63992. }
  63993. if (this._colorGradientsTexture) {
  63994. this._attributesStrideSize -= 4;
  63995. }
  63996. if (this._angularSpeedGradientsTexture) {
  63997. this._attributesStrideSize -= 1;
  63998. }
  63999. if (this._isAnimationSheetEnabled) {
  64000. this._attributesStrideSize += 1;
  64001. if (this.spriteRandomStartCell) {
  64002. this._attributesStrideSize += 1;
  64003. }
  64004. }
  64005. if (this.noiseTexture) {
  64006. this._attributesStrideSize += 6;
  64007. }
  64008. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  64009. // position
  64010. data.push(0.0);
  64011. data.push(0.0);
  64012. data.push(0.0);
  64013. // Age and life
  64014. data.push(0.0); // create the particle as a dead one to create a new one at start
  64015. data.push(0.0);
  64016. // Seed
  64017. data.push(Math.random());
  64018. data.push(Math.random());
  64019. data.push(Math.random());
  64020. data.push(Math.random());
  64021. // Size
  64022. data.push(0.0);
  64023. data.push(0.0);
  64024. data.push(0.0);
  64025. if (!this._colorGradientsTexture) {
  64026. // color
  64027. data.push(0.0);
  64028. data.push(0.0);
  64029. data.push(0.0);
  64030. data.push(0.0);
  64031. }
  64032. // direction
  64033. data.push(0.0);
  64034. data.push(0.0);
  64035. data.push(0.0);
  64036. if (!this.isBillboardBased) {
  64037. // initialDirection
  64038. data.push(0.0);
  64039. data.push(0.0);
  64040. data.push(0.0);
  64041. }
  64042. // angle
  64043. data.push(0.0);
  64044. if (!this._angularSpeedGradientsTexture) {
  64045. data.push(0.0);
  64046. }
  64047. if (this._isAnimationSheetEnabled) {
  64048. data.push(0.0);
  64049. if (this.spriteRandomStartCell) {
  64050. data.push(0.0);
  64051. }
  64052. }
  64053. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  64054. data.push(Math.random());
  64055. data.push(Math.random());
  64056. data.push(Math.random());
  64057. data.push(Math.random());
  64058. data.push(Math.random());
  64059. data.push(Math.random());
  64060. }
  64061. }
  64062. // Sprite data
  64063. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  64064. -0.5, 0.5, 0, 1,
  64065. -0.5, -0.5, 0, 0,
  64066. 0.5, -0.5, 1, 0]);
  64067. // Buffers
  64068. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64069. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64070. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  64071. // Update VAO
  64072. this._updateVAO = [];
  64073. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  64074. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  64075. // Render VAO
  64076. this._renderVAO = [];
  64077. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  64078. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  64079. // Links
  64080. this._sourceBuffer = this._buffer0;
  64081. this._targetBuffer = this._buffer1;
  64082. };
  64083. /** @hidden */
  64084. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  64085. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  64086. if (this._isBillboardBased) {
  64087. defines += "\n#define BILLBOARD";
  64088. }
  64089. if (this._colorGradientsTexture) {
  64090. defines += "\n#define COLORGRADIENTS";
  64091. }
  64092. if (this._sizeGradientsTexture) {
  64093. defines += "\n#define SIZEGRADIENTS";
  64094. }
  64095. if (this._angularSpeedGradientsTexture) {
  64096. defines += "\n#define ANGULARSPEEDGRADIENTS";
  64097. }
  64098. if (this._velocityGradientsTexture) {
  64099. defines += "\n#define VELOCITYGRADIENTS";
  64100. }
  64101. if (this._limitVelocityGradientsTexture) {
  64102. defines += "\n#define LIMITVELOCITYGRADIENTS";
  64103. }
  64104. if (this._dragGradientsTexture) {
  64105. defines += "\n#define DRAGGRADIENTS";
  64106. }
  64107. if (this.isAnimationSheetEnabled) {
  64108. defines += "\n#define ANIMATESHEET";
  64109. if (this.spriteRandomStartCell) {
  64110. defines += "\n#define ANIMATESHEETRANDOMSTART";
  64111. }
  64112. }
  64113. if (this.noiseTexture) {
  64114. defines += "\n#define NOISE";
  64115. }
  64116. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  64117. return;
  64118. }
  64119. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  64120. if (!this._colorGradientsTexture) {
  64121. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  64122. }
  64123. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  64124. if (!this._isBillboardBased) {
  64125. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  64126. }
  64127. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  64128. if (this.isAnimationSheetEnabled) {
  64129. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  64130. if (this.spriteRandomStartCell) {
  64131. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  64132. }
  64133. }
  64134. if (this.noiseTexture) {
  64135. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  64136. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  64137. }
  64138. this._updateEffectOptions.defines = defines;
  64139. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  64140. };
  64141. /** @hidden */
  64142. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  64143. var defines = "";
  64144. if (this._scene.clipPlane) {
  64145. defines = "\n#define CLIPPLANE";
  64146. }
  64147. if (this._scene.clipPlane2) {
  64148. defines = "\n#define CLIPPLANE2";
  64149. }
  64150. if (this._scene.clipPlane3) {
  64151. defines = "\n#define CLIPPLANE3";
  64152. }
  64153. if (this._scene.clipPlane4) {
  64154. defines = "\n#define CLIPPLANE4";
  64155. }
  64156. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  64157. defines = "\n#define BLENDMULTIPLYMODE";
  64158. }
  64159. if (this._isBillboardBased) {
  64160. defines += "\n#define BILLBOARD";
  64161. switch (this.billboardMode) {
  64162. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  64163. defines += "\n#define BILLBOARDY";
  64164. break;
  64165. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  64166. defines += "\n#define BILLBOARDSTRETCHED";
  64167. break;
  64168. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  64169. default:
  64170. break;
  64171. }
  64172. }
  64173. if (this._colorGradientsTexture) {
  64174. defines += "\n#define COLORGRADIENTS";
  64175. }
  64176. if (this.isAnimationSheetEnabled) {
  64177. defines += "\n#define ANIMATESHEET";
  64178. }
  64179. if (this._imageProcessingConfiguration) {
  64180. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  64181. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  64182. }
  64183. if (this._renderEffect && this._renderEffect.defines === defines) {
  64184. return;
  64185. }
  64186. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  64187. var samplers = ["textureSampler", "colorGradientSampler"];
  64188. if (BABYLON.ImageProcessingConfiguration) {
  64189. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  64190. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  64191. }
  64192. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  64193. };
  64194. /**
  64195. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  64196. * @param preWarm defines if we are in the pre-warmimg phase
  64197. */
  64198. GPUParticleSystem.prototype.animate = function (preWarm) {
  64199. if (preWarm === void 0) { preWarm = false; }
  64200. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  64201. this._actualFrame += this._timeDelta;
  64202. if (!this._stopped) {
  64203. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  64204. this.stop();
  64205. }
  64206. }
  64207. };
  64208. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  64209. var texture = this[textureName];
  64210. if (!factorGradients || !factorGradients.length || texture) {
  64211. return;
  64212. }
  64213. var data = new Float32Array(this._rawTextureWidth);
  64214. for (var x = 0; x < this._rawTextureWidth; x++) {
  64215. var ratio = x / this._rawTextureWidth;
  64216. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  64217. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  64218. });
  64219. }
  64220. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64221. };
  64222. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  64223. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  64224. };
  64225. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  64226. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  64227. };
  64228. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  64229. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  64230. };
  64231. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  64232. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  64233. };
  64234. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  64235. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  64236. };
  64237. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  64238. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  64239. return;
  64240. }
  64241. var data = new Uint8Array(this._rawTextureWidth * 4);
  64242. var tmpColor = BABYLON.Tmp.Color4[0];
  64243. for (var x = 0; x < this._rawTextureWidth; x++) {
  64244. var ratio = x / this._rawTextureWidth;
  64245. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  64246. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  64247. data[x * 4] = tmpColor.r * 255;
  64248. data[x * 4 + 1] = tmpColor.g * 255;
  64249. data[x * 4 + 2] = tmpColor.b * 255;
  64250. data[x * 4 + 3] = tmpColor.a * 255;
  64251. });
  64252. }
  64253. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64254. };
  64255. /**
  64256. * Renders the particle system in its current state
  64257. * @param preWarm defines if the system should only update the particles but not render them
  64258. * @returns the current number of particles
  64259. */
  64260. GPUParticleSystem.prototype.render = function (preWarm) {
  64261. if (preWarm === void 0) { preWarm = false; }
  64262. if (!this._started) {
  64263. return 0;
  64264. }
  64265. this._createColorGradientTexture();
  64266. this._createSizeGradientTexture();
  64267. this._createAngularSpeedGradientTexture();
  64268. this._createVelocityGradientTexture();
  64269. this._createLimitVelocityGradientTexture();
  64270. this._createDragGradientTexture();
  64271. this._recreateUpdateEffect();
  64272. this._recreateRenderEffect();
  64273. if (!this.isReady()) {
  64274. return 0;
  64275. }
  64276. if (!preWarm) {
  64277. if (!this._preWarmDone && this.preWarmCycles) {
  64278. for (var index = 0; index < this.preWarmCycles; index++) {
  64279. this.animate(true);
  64280. this.render(true);
  64281. }
  64282. this._preWarmDone = true;
  64283. }
  64284. if (this._currentRenderId === this._scene.getRenderId()) {
  64285. return 0;
  64286. }
  64287. this._currentRenderId = this._scene.getRenderId();
  64288. }
  64289. // Get everything ready to render
  64290. this._initialize();
  64291. this._accumulatedCount += this.emitRate * this._timeDelta;
  64292. if (this._accumulatedCount > 1) {
  64293. var intPart = this._accumulatedCount | 0;
  64294. this._accumulatedCount -= intPart;
  64295. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  64296. }
  64297. if (!this._currentActiveCount) {
  64298. return 0;
  64299. }
  64300. // Enable update effect
  64301. this._engine.enableEffect(this._updateEffect);
  64302. this._engine.setState(false);
  64303. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  64304. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  64305. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  64306. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  64307. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  64308. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  64309. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  64310. if (!this._colorGradientsTexture) {
  64311. this._updateEffect.setDirectColor4("color1", this.color1);
  64312. this._updateEffect.setDirectColor4("color2", this.color2);
  64313. }
  64314. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  64315. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  64316. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  64317. this._updateEffect.setVector3("gravity", this.gravity);
  64318. if (this._sizeGradientsTexture) {
  64319. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  64320. }
  64321. if (this._angularSpeedGradientsTexture) {
  64322. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  64323. }
  64324. if (this._velocityGradientsTexture) {
  64325. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  64326. }
  64327. if (this._limitVelocityGradientsTexture) {
  64328. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  64329. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  64330. }
  64331. if (this._dragGradientsTexture) {
  64332. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  64333. }
  64334. if (this.particleEmitterType) {
  64335. this.particleEmitterType.applyToShader(this._updateEffect);
  64336. }
  64337. if (this._isAnimationSheetEnabled) {
  64338. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  64339. }
  64340. if (this.noiseTexture) {
  64341. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  64342. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  64343. }
  64344. var emitterWM;
  64345. if (this.emitter.position) {
  64346. var emitterMesh = this.emitter;
  64347. emitterWM = emitterMesh.getWorldMatrix();
  64348. }
  64349. else {
  64350. var emitterPosition = this.emitter;
  64351. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  64352. }
  64353. this._updateEffect.setMatrix("emitterWM", emitterWM);
  64354. // Bind source VAO
  64355. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  64356. // Update
  64357. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  64358. this._engine.setRasterizerState(false);
  64359. this._engine.beginTransformFeedback(true);
  64360. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  64361. this._engine.endTransformFeedback();
  64362. this._engine.setRasterizerState(true);
  64363. this._engine.bindTransformFeedbackBuffer(null);
  64364. if (!preWarm) {
  64365. // Enable render effect
  64366. this._engine.enableEffect(this._renderEffect);
  64367. var viewMatrix = this._scene.getViewMatrix();
  64368. this._renderEffect.setMatrix("view", viewMatrix);
  64369. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  64370. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  64371. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  64372. if (this._colorGradientsTexture) {
  64373. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  64374. }
  64375. else {
  64376. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  64377. }
  64378. if (this._isAnimationSheetEnabled && this.particleTexture) {
  64379. var baseSize = this.particleTexture.getBaseSize();
  64380. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  64381. }
  64382. if (this._isBillboardBased) {
  64383. var camera = this._scene.activeCamera;
  64384. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  64385. }
  64386. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  64387. var invView = viewMatrix.clone();
  64388. invView.invert();
  64389. this._renderEffect.setMatrix("invView", invView);
  64390. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  64391. }
  64392. // image processing
  64393. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  64394. this._imageProcessingConfiguration.bind(this._renderEffect);
  64395. }
  64396. // Draw order
  64397. switch (this.blendMode) {
  64398. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  64399. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  64400. break;
  64401. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  64402. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  64403. break;
  64404. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  64405. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64406. break;
  64407. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  64408. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  64409. break;
  64410. }
  64411. if (this.forceDepthWrite) {
  64412. this._engine.setDepthWrite(true);
  64413. }
  64414. // Bind source VAO
  64415. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  64416. // Render
  64417. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  64418. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64419. }
  64420. // Switch VAOs
  64421. this._targetIndex++;
  64422. if (this._targetIndex === 2) {
  64423. this._targetIndex = 0;
  64424. }
  64425. // Switch buffers
  64426. var tmpBuffer = this._sourceBuffer;
  64427. this._sourceBuffer = this._targetBuffer;
  64428. this._targetBuffer = tmpBuffer;
  64429. return this._currentActiveCount;
  64430. };
  64431. /**
  64432. * Rebuilds the particle system
  64433. */
  64434. GPUParticleSystem.prototype.rebuild = function () {
  64435. this._initialize(true);
  64436. };
  64437. GPUParticleSystem.prototype._releaseBuffers = function () {
  64438. if (this._buffer0) {
  64439. this._buffer0.dispose();
  64440. this._buffer0 = null;
  64441. }
  64442. if (this._buffer1) {
  64443. this._buffer1.dispose();
  64444. this._buffer1 = null;
  64445. }
  64446. if (this._spriteBuffer) {
  64447. this._spriteBuffer.dispose();
  64448. this._spriteBuffer = null;
  64449. }
  64450. };
  64451. GPUParticleSystem.prototype._releaseVAOs = function () {
  64452. if (!this._updateVAO) {
  64453. return;
  64454. }
  64455. for (var index = 0; index < this._updateVAO.length; index++) {
  64456. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  64457. }
  64458. this._updateVAO = [];
  64459. for (var index = 0; index < this._renderVAO.length; index++) {
  64460. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  64461. }
  64462. this._renderVAO = [];
  64463. };
  64464. /**
  64465. * Disposes the particle system and free the associated resources
  64466. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  64467. */
  64468. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  64469. if (disposeTexture === void 0) { disposeTexture = true; }
  64470. var index = this._scene.particleSystems.indexOf(this);
  64471. if (index > -1) {
  64472. this._scene.particleSystems.splice(index, 1);
  64473. }
  64474. this._releaseBuffers();
  64475. this._releaseVAOs();
  64476. if (this._colorGradientsTexture) {
  64477. this._colorGradientsTexture.dispose();
  64478. this._colorGradientsTexture = null;
  64479. }
  64480. if (this._sizeGradientsTexture) {
  64481. this._sizeGradientsTexture.dispose();
  64482. this._sizeGradientsTexture = null;
  64483. }
  64484. if (this._angularSpeedGradientsTexture) {
  64485. this._angularSpeedGradientsTexture.dispose();
  64486. this._angularSpeedGradientsTexture = null;
  64487. }
  64488. if (this._velocityGradientsTexture) {
  64489. this._velocityGradientsTexture.dispose();
  64490. this._velocityGradientsTexture = null;
  64491. }
  64492. if (this._limitVelocityGradientsTexture) {
  64493. this._limitVelocityGradientsTexture.dispose();
  64494. this._limitVelocityGradientsTexture = null;
  64495. }
  64496. if (this._dragGradientsTexture) {
  64497. this._dragGradientsTexture.dispose();
  64498. this._dragGradientsTexture = null;
  64499. }
  64500. if (this._randomTexture) {
  64501. this._randomTexture.dispose();
  64502. this._randomTexture = null;
  64503. }
  64504. if (this._randomTexture2) {
  64505. this._randomTexture2.dispose();
  64506. this._randomTexture2 = null;
  64507. }
  64508. if (disposeTexture && this.particleTexture) {
  64509. this.particleTexture.dispose();
  64510. this.particleTexture = null;
  64511. }
  64512. if (disposeTexture && this.noiseTexture) {
  64513. this.noiseTexture.dispose();
  64514. this.noiseTexture = null;
  64515. }
  64516. // Callback
  64517. this.onDisposeObservable.notifyObservers(this);
  64518. this.onDisposeObservable.clear();
  64519. };
  64520. /**
  64521. * Clones the particle system.
  64522. * @param name The name of the cloned object
  64523. * @param newEmitter The new emitter to use
  64524. * @returns the cloned particle system
  64525. */
  64526. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  64527. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  64528. BABYLON.Tools.DeepCopy(this, result);
  64529. if (newEmitter === undefined) {
  64530. newEmitter = this.emitter;
  64531. }
  64532. result.emitter = newEmitter;
  64533. if (this.particleTexture) {
  64534. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  64535. }
  64536. return result;
  64537. };
  64538. /**
  64539. * Serializes the particle system to a JSON object.
  64540. * @returns the JSON object
  64541. */
  64542. GPUParticleSystem.prototype.serialize = function () {
  64543. var serializationObject = {};
  64544. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  64545. serializationObject.activeParticleCount = this.activeParticleCount;
  64546. return serializationObject;
  64547. };
  64548. /**
  64549. * Parses a JSON object to create a GPU particle system.
  64550. * @param parsedParticleSystem The JSON object to parse
  64551. * @param scene The scene to create the particle system in
  64552. * @param rootUrl The root url to use to load external dependencies like texture
  64553. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  64554. * @returns the parsed GPU particle system
  64555. */
  64556. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  64557. if (doNotStart === void 0) { doNotStart = false; }
  64558. var name = parsedParticleSystem.name;
  64559. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  64560. if (parsedParticleSystem.activeParticleCount) {
  64561. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  64562. }
  64563. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  64564. // Auto start
  64565. if (parsedParticleSystem.preventAutoStart) {
  64566. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  64567. }
  64568. if (!doNotStart && !particleSystem.preventAutoStart) {
  64569. particleSystem.start();
  64570. }
  64571. return particleSystem;
  64572. };
  64573. return GPUParticleSystem;
  64574. }(BABYLON.BaseParticleSystem));
  64575. BABYLON.GPUParticleSystem = GPUParticleSystem;
  64576. })(BABYLON || (BABYLON = {}));
  64577. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  64578. var BABYLON;
  64579. (function (BABYLON) {
  64580. /**
  64581. * Represents one particle of a solid particle system.
  64582. */
  64583. var SolidParticle = /** @class */ (function () {
  64584. /**
  64585. * Creates a Solid Particle object.
  64586. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  64587. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  64588. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  64589. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  64590. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  64591. * @param shapeId (integer) is the model shape identifier in the SPS.
  64592. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  64593. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  64594. */
  64595. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  64596. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  64597. /**
  64598. * particle global index
  64599. */
  64600. this.idx = 0;
  64601. /**
  64602. * The color of the particle
  64603. */
  64604. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64605. /**
  64606. * The world space position of the particle.
  64607. */
  64608. this.position = BABYLON.Vector3.Zero();
  64609. /**
  64610. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  64611. */
  64612. this.rotation = BABYLON.Vector3.Zero();
  64613. /**
  64614. * The scaling of the particle.
  64615. */
  64616. this.scaling = BABYLON.Vector3.One();
  64617. /**
  64618. * The uvs of the particle.
  64619. */
  64620. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  64621. /**
  64622. * The current speed of the particle.
  64623. */
  64624. this.velocity = BABYLON.Vector3.Zero();
  64625. /**
  64626. * The pivot point in the particle local space.
  64627. */
  64628. this.pivot = BABYLON.Vector3.Zero();
  64629. /**
  64630. * Must the particle be translated from its pivot point in its local space ?
  64631. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  64632. * Default : false
  64633. */
  64634. this.translateFromPivot = false;
  64635. /**
  64636. * Is the particle active or not ?
  64637. */
  64638. this.alive = true;
  64639. /**
  64640. * Is the particle visible or not ?
  64641. */
  64642. this.isVisible = true;
  64643. /**
  64644. * Index of this particle in the global "positions" array (Internal use)
  64645. * @hidden
  64646. */
  64647. this._pos = 0;
  64648. /**
  64649. * @hidden Index of this particle in the global "indices" array (Internal use)
  64650. */
  64651. this._ind = 0;
  64652. /**
  64653. * ModelShape id of this particle
  64654. */
  64655. this.shapeId = 0;
  64656. /**
  64657. * Index of the particle in its shape id (Internal use)
  64658. */
  64659. this.idxInShape = 0;
  64660. /**
  64661. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  64662. */
  64663. this._stillInvisible = false;
  64664. /**
  64665. * @hidden Last computed particle rotation matrix
  64666. */
  64667. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  64668. /**
  64669. * Parent particle Id, if any.
  64670. * Default null.
  64671. */
  64672. this.parentId = null;
  64673. /**
  64674. * @hidden Internal global position in the SPS.
  64675. */
  64676. this._globalPosition = BABYLON.Vector3.Zero();
  64677. this.idx = particleIndex;
  64678. this._pos = positionIndex;
  64679. this._ind = indiceIndex;
  64680. this._model = model;
  64681. this.shapeId = shapeId;
  64682. this.idxInShape = idxInShape;
  64683. this._sps = sps;
  64684. if (modelBoundingInfo) {
  64685. this._modelBoundingInfo = modelBoundingInfo;
  64686. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  64687. }
  64688. }
  64689. Object.defineProperty(SolidParticle.prototype, "scale", {
  64690. /**
  64691. * Legacy support, changed scale to scaling
  64692. */
  64693. get: function () {
  64694. return this.scaling;
  64695. },
  64696. /**
  64697. * Legacy support, changed scale to scaling
  64698. */
  64699. set: function (scale) {
  64700. this.scaling = scale;
  64701. },
  64702. enumerable: true,
  64703. configurable: true
  64704. });
  64705. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  64706. /**
  64707. * Legacy support, changed quaternion to rotationQuaternion
  64708. */
  64709. get: function () {
  64710. return this.rotationQuaternion;
  64711. },
  64712. /**
  64713. * Legacy support, changed quaternion to rotationQuaternion
  64714. */
  64715. set: function (q) {
  64716. this.rotationQuaternion = q;
  64717. },
  64718. enumerable: true,
  64719. configurable: true
  64720. });
  64721. /**
  64722. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  64723. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  64724. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  64725. * @returns true if it intersects
  64726. */
  64727. SolidParticle.prototype.intersectsMesh = function (target) {
  64728. if (!this._boundingInfo || !target._boundingInfo) {
  64729. return false;
  64730. }
  64731. if (this._sps._bSphereOnly) {
  64732. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  64733. }
  64734. return this._boundingInfo.intersects(target._boundingInfo, false);
  64735. };
  64736. return SolidParticle;
  64737. }());
  64738. BABYLON.SolidParticle = SolidParticle;
  64739. /**
  64740. * Represents the shape of the model used by one particle of a solid particle system.
  64741. * SPS internal tool, don't use it manually.
  64742. */
  64743. var ModelShape = /** @class */ (function () {
  64744. /**
  64745. * 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.
  64746. * SPS internal tool, don't use it manually.
  64747. * @hidden
  64748. */
  64749. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  64750. /**
  64751. * length of the shape in the model indices array (internal use)
  64752. * @hidden
  64753. */
  64754. this._indicesLength = 0;
  64755. this.shapeID = id;
  64756. this._shape = shape;
  64757. this._indicesLength = indicesLength;
  64758. this._shapeUV = shapeUV;
  64759. this._positionFunction = posFunction;
  64760. this._vertexFunction = vtxFunction;
  64761. }
  64762. return ModelShape;
  64763. }());
  64764. BABYLON.ModelShape = ModelShape;
  64765. /**
  64766. * Represents a Depth Sorted Particle in the solid particle system.
  64767. */
  64768. var DepthSortedParticle = /** @class */ (function () {
  64769. function DepthSortedParticle() {
  64770. /**
  64771. * Index of the particle in the "indices" array
  64772. */
  64773. this.ind = 0;
  64774. /**
  64775. * Length of the particle shape in the "indices" array
  64776. */
  64777. this.indicesLength = 0;
  64778. /**
  64779. * Squared distance from the particle to the camera
  64780. */
  64781. this.sqDistance = 0.0;
  64782. }
  64783. return DepthSortedParticle;
  64784. }());
  64785. BABYLON.DepthSortedParticle = DepthSortedParticle;
  64786. })(BABYLON || (BABYLON = {}));
  64787. //# sourceMappingURL=babylon.solidParticle.js.map
  64788. var BABYLON;
  64789. (function (BABYLON) {
  64790. /**
  64791. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  64792. *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.
  64793. * The SPS is also a particle system. It provides some methods to manage the particles.
  64794. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  64795. *
  64796. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  64797. */
  64798. var SolidParticleSystem = /** @class */ (function () {
  64799. /**
  64800. * Creates a SPS (Solid Particle System) object.
  64801. * @param name (String) is the SPS name, this will be the underlying mesh name.
  64802. * @param scene (Scene) is the scene in which the SPS is added.
  64803. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  64804. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  64805. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  64806. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  64807. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  64808. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  64809. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  64810. */
  64811. function SolidParticleSystem(name, scene, options) {
  64812. /**
  64813. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  64814. * Example : var p = SPS.particles[i];
  64815. */
  64816. this.particles = new Array();
  64817. /**
  64818. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  64819. */
  64820. this.nbParticles = 0;
  64821. /**
  64822. * If the particles must ever face the camera (default false). Useful for planar particles.
  64823. */
  64824. this.billboard = false;
  64825. /**
  64826. * Recompute normals when adding a shape
  64827. */
  64828. this.recomputeNormals = true;
  64829. /**
  64830. * This a counter ofr your own usage. It's not set by any SPS functions.
  64831. */
  64832. this.counter = 0;
  64833. /**
  64834. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  64835. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  64836. */
  64837. this.vars = {};
  64838. /**
  64839. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  64840. * @hidden
  64841. */
  64842. this._bSphereOnly = false;
  64843. /**
  64844. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  64845. * @hidden
  64846. */
  64847. this._bSphereRadiusFactor = 1.0;
  64848. this._positions = new Array();
  64849. this._indices = new Array();
  64850. this._normals = new Array();
  64851. this._colors = new Array();
  64852. this._uvs = new Array();
  64853. this._index = 0; // indices index
  64854. this._updatable = true;
  64855. this._pickable = false;
  64856. this._isVisibilityBoxLocked = false;
  64857. this._alwaysVisible = false;
  64858. this._depthSort = false;
  64859. this._shapeCounter = 0;
  64860. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  64861. this._color = new BABYLON.Color4(0, 0, 0, 0);
  64862. this._computeParticleColor = true;
  64863. this._computeParticleTexture = true;
  64864. this._computeParticleRotation = true;
  64865. this._computeParticleVertex = false;
  64866. this._computeBoundingBox = false;
  64867. this._depthSortParticles = true;
  64868. this._cam_axisZ = BABYLON.Vector3.Zero();
  64869. this._cam_axisY = BABYLON.Vector3.Zero();
  64870. this._cam_axisX = BABYLON.Vector3.Zero();
  64871. this._axisZ = BABYLON.Axis.Z;
  64872. this._camDir = BABYLON.Vector3.Zero();
  64873. this._camInvertedPosition = BABYLON.Vector3.Zero();
  64874. this._rotMatrix = new BABYLON.Matrix();
  64875. this._invertMatrix = new BABYLON.Matrix();
  64876. this._rotated = BABYLON.Vector3.Zero();
  64877. this._quaternion = new BABYLON.Quaternion();
  64878. this._vertex = BABYLON.Vector3.Zero();
  64879. this._normal = BABYLON.Vector3.Zero();
  64880. this._yaw = 0.0;
  64881. this._pitch = 0.0;
  64882. this._roll = 0.0;
  64883. this._halfroll = 0.0;
  64884. this._halfpitch = 0.0;
  64885. this._halfyaw = 0.0;
  64886. this._sinRoll = 0.0;
  64887. this._cosRoll = 0.0;
  64888. this._sinPitch = 0.0;
  64889. this._cosPitch = 0.0;
  64890. this._sinYaw = 0.0;
  64891. this._cosYaw = 0.0;
  64892. this._mustUnrotateFixedNormals = false;
  64893. this._minimum = BABYLON.Vector3.Zero();
  64894. this._maximum = BABYLON.Vector3.Zero();
  64895. this._minBbox = BABYLON.Vector3.Zero();
  64896. this._maxBbox = BABYLON.Vector3.Zero();
  64897. this._particlesIntersect = false;
  64898. this._depthSortFunction = function (p1, p2) {
  64899. return (p2.sqDistance - p1.sqDistance);
  64900. };
  64901. this._needs32Bits = false;
  64902. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  64903. this._scaledPivot = BABYLON.Vector3.Zero();
  64904. this._particleHasParent = false;
  64905. this.name = name;
  64906. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64907. this._camera = scene.activeCamera;
  64908. this._pickable = options ? options.isPickable : false;
  64909. this._depthSort = options ? options.enableDepthSort : false;
  64910. this._particlesIntersect = options ? options.particleIntersection : false;
  64911. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  64912. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  64913. if (options && options.updatable !== undefined) {
  64914. this._updatable = options.updatable;
  64915. }
  64916. else {
  64917. this._updatable = true;
  64918. }
  64919. if (this._pickable) {
  64920. this.pickedParticles = [];
  64921. }
  64922. if (this._depthSort) {
  64923. this.depthSortedParticles = [];
  64924. }
  64925. }
  64926. /**
  64927. * Builds the SPS underlying mesh. Returns a standard Mesh.
  64928. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  64929. * @returns the created mesh
  64930. */
  64931. SolidParticleSystem.prototype.buildMesh = function () {
  64932. if (this.nbParticles === 0) {
  64933. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  64934. this.addShape(triangle, 1);
  64935. triangle.dispose();
  64936. }
  64937. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  64938. this._positions32 = new Float32Array(this._positions);
  64939. this._uvs32 = new Float32Array(this._uvs);
  64940. this._colors32 = new Float32Array(this._colors);
  64941. if (this.recomputeNormals) {
  64942. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  64943. }
  64944. this._normals32 = new Float32Array(this._normals);
  64945. this._fixedNormal32 = new Float32Array(this._normals);
  64946. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  64947. this._unrotateFixedNormals();
  64948. }
  64949. var vertexData = new BABYLON.VertexData();
  64950. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  64951. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  64952. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  64953. if (this._uvs32.length > 0) {
  64954. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  64955. }
  64956. if (this._colors32.length > 0) {
  64957. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  64958. }
  64959. var mesh = new BABYLON.Mesh(this.name, this._scene);
  64960. vertexData.applyToMesh(mesh, this._updatable);
  64961. this.mesh = mesh;
  64962. this.mesh.isPickable = this._pickable;
  64963. // free memory
  64964. if (!this._depthSort) {
  64965. this._indices = null;
  64966. }
  64967. this._positions = null;
  64968. this._normals = null;
  64969. this._uvs = null;
  64970. this._colors = null;
  64971. if (!this._updatable) {
  64972. this.particles.length = 0;
  64973. }
  64974. return mesh;
  64975. };
  64976. /**
  64977. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  64978. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  64979. * Thus the particles generated from `digest()` have their property `position` set yet.
  64980. * @param mesh ( Mesh ) is the mesh to be digested
  64981. * @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
  64982. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  64983. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  64984. * @returns the current SPS
  64985. */
  64986. SolidParticleSystem.prototype.digest = function (mesh, options) {
  64987. var size = (options && options.facetNb) || 1;
  64988. var number = (options && options.number) || 0;
  64989. var delta = (options && options.delta) || 0;
  64990. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64991. var meshInd = mesh.getIndices();
  64992. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64993. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64994. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64995. var f = 0; // facet counter
  64996. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  64997. // compute size from number
  64998. if (number) {
  64999. number = (number > totalFacets) ? totalFacets : number;
  65000. size = Math.round(totalFacets / number);
  65001. delta = 0;
  65002. }
  65003. else {
  65004. size = (size > totalFacets) ? totalFacets : size;
  65005. }
  65006. var facetPos = []; // submesh positions
  65007. var facetInd = []; // submesh indices
  65008. var facetUV = []; // submesh UV
  65009. var facetCol = []; // submesh colors
  65010. var barycenter = BABYLON.Vector3.Zero();
  65011. var sizeO = size;
  65012. while (f < totalFacets) {
  65013. size = sizeO + Math.floor((1 + delta) * Math.random());
  65014. if (f > totalFacets - size) {
  65015. size = totalFacets - f;
  65016. }
  65017. // reset temp arrays
  65018. facetPos.length = 0;
  65019. facetInd.length = 0;
  65020. facetUV.length = 0;
  65021. facetCol.length = 0;
  65022. // iterate over "size" facets
  65023. var fi = 0;
  65024. for (var j = f * 3; j < (f + size) * 3; j++) {
  65025. facetInd.push(fi);
  65026. var i = meshInd[j];
  65027. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  65028. if (meshUV) {
  65029. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  65030. }
  65031. if (meshCol) {
  65032. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  65033. }
  65034. fi++;
  65035. }
  65036. // create a model shape for each single particle
  65037. var idx = this.nbParticles;
  65038. var shape = this._posToShape(facetPos);
  65039. var shapeUV = this._uvsToShapeUV(facetUV);
  65040. // compute the barycenter of the shape
  65041. var v;
  65042. for (v = 0; v < shape.length; v++) {
  65043. barycenter.addInPlace(shape[v]);
  65044. }
  65045. barycenter.scaleInPlace(1 / shape.length);
  65046. // shift the shape from its barycenter to the origin
  65047. for (v = 0; v < shape.length; v++) {
  65048. shape[v].subtractInPlace(barycenter);
  65049. }
  65050. var bInfo;
  65051. if (this._particlesIntersect) {
  65052. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  65053. }
  65054. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  65055. // add the particle in the SPS
  65056. var currentPos = this._positions.length;
  65057. var currentInd = this._indices.length;
  65058. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  65059. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  65060. // initialize the particle position
  65061. this.particles[this.nbParticles].position.addInPlace(barycenter);
  65062. this._index += shape.length;
  65063. idx++;
  65064. this.nbParticles++;
  65065. this._shapeCounter++;
  65066. f += size;
  65067. }
  65068. return this;
  65069. };
  65070. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  65071. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  65072. var index = 0;
  65073. var idx = 0;
  65074. for (var p = 0; p < this.particles.length; p++) {
  65075. this._particle = this.particles[p];
  65076. this._shape = this._particle._model._shape;
  65077. if (this._particle.rotationQuaternion) {
  65078. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65079. }
  65080. else {
  65081. this._yaw = this._particle.rotation.y;
  65082. this._pitch = this._particle.rotation.x;
  65083. this._roll = this._particle.rotation.z;
  65084. this._quaternionRotationYPR();
  65085. }
  65086. this._quaternionToRotationMatrix();
  65087. this._rotMatrix.invertToRef(this._invertMatrix);
  65088. for (var pt = 0; pt < this._shape.length; pt++) {
  65089. idx = index + pt * 3;
  65090. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  65091. this._fixedNormal32[idx] = this._normal.x;
  65092. this._fixedNormal32[idx + 1] = this._normal.y;
  65093. this._fixedNormal32[idx + 2] = this._normal.z;
  65094. }
  65095. index = idx + 3;
  65096. }
  65097. };
  65098. //reset copy
  65099. SolidParticleSystem.prototype._resetCopy = function () {
  65100. this._copy.position.x = 0;
  65101. this._copy.position.y = 0;
  65102. this._copy.position.z = 0;
  65103. this._copy.rotation.x = 0;
  65104. this._copy.rotation.y = 0;
  65105. this._copy.rotation.z = 0;
  65106. this._copy.rotationQuaternion = null;
  65107. this._copy.scaling.x = 1.0;
  65108. this._copy.scaling.y = 1.0;
  65109. this._copy.scaling.z = 1.0;
  65110. this._copy.uvs.x = 0;
  65111. this._copy.uvs.y = 0;
  65112. this._copy.uvs.z = 1.0;
  65113. this._copy.uvs.w = 1.0;
  65114. this._copy.color = null;
  65115. this._copy.translateFromPivot = false;
  65116. };
  65117. // _meshBuilder : inserts the shape model in the global SPS mesh
  65118. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  65119. var i;
  65120. var u = 0;
  65121. var c = 0;
  65122. var n = 0;
  65123. this._resetCopy();
  65124. if (options && options.positionFunction) { // call to custom positionFunction
  65125. options.positionFunction(this._copy, idx, idxInShape);
  65126. this._mustUnrotateFixedNormals = true;
  65127. }
  65128. if (this._copy.rotationQuaternion) {
  65129. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65130. }
  65131. else {
  65132. this._yaw = this._copy.rotation.y;
  65133. this._pitch = this._copy.rotation.x;
  65134. this._roll = this._copy.rotation.z;
  65135. this._quaternionRotationYPR();
  65136. }
  65137. this._quaternionToRotationMatrix();
  65138. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  65139. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  65140. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  65141. if (this._copy.translateFromPivot) {
  65142. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65143. }
  65144. else {
  65145. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65146. }
  65147. for (i = 0; i < shape.length; i++) {
  65148. this._vertex.x = shape[i].x;
  65149. this._vertex.y = shape[i].y;
  65150. this._vertex.z = shape[i].z;
  65151. if (options && options.vertexFunction) {
  65152. options.vertexFunction(this._copy, this._vertex, i);
  65153. }
  65154. this._vertex.x *= this._copy.scaling.x;
  65155. this._vertex.y *= this._copy.scaling.y;
  65156. this._vertex.z *= this._copy.scaling.z;
  65157. this._vertex.x -= this._scaledPivot.x;
  65158. this._vertex.y -= this._scaledPivot.y;
  65159. this._vertex.z -= this._scaledPivot.z;
  65160. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65161. this._rotated.addInPlace(this._pivotBackTranslation);
  65162. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  65163. if (meshUV) {
  65164. 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);
  65165. u += 2;
  65166. }
  65167. if (this._copy.color) {
  65168. this._color = this._copy.color;
  65169. }
  65170. else if (meshCol && meshCol[c] !== undefined) {
  65171. this._color.r = meshCol[c];
  65172. this._color.g = meshCol[c + 1];
  65173. this._color.b = meshCol[c + 2];
  65174. this._color.a = meshCol[c + 3];
  65175. }
  65176. else {
  65177. this._color.r = 1.0;
  65178. this._color.g = 1.0;
  65179. this._color.b = 1.0;
  65180. this._color.a = 1.0;
  65181. }
  65182. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  65183. c += 4;
  65184. if (!this.recomputeNormals && meshNor) {
  65185. this._normal.x = meshNor[n];
  65186. this._normal.y = meshNor[n + 1];
  65187. this._normal.z = meshNor[n + 2];
  65188. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  65189. normals.push(this._normal.x, this._normal.y, this._normal.z);
  65190. n += 3;
  65191. }
  65192. }
  65193. for (i = 0; i < meshInd.length; i++) {
  65194. var current_ind = p + meshInd[i];
  65195. indices.push(current_ind);
  65196. if (current_ind > 65535) {
  65197. this._needs32Bits = true;
  65198. }
  65199. }
  65200. if (this._pickable) {
  65201. var nbfaces = meshInd.length / 3;
  65202. for (i = 0; i < nbfaces; i++) {
  65203. this.pickedParticles.push({ idx: idx, faceId: i });
  65204. }
  65205. }
  65206. if (this._depthSort) {
  65207. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  65208. }
  65209. return this._copy;
  65210. };
  65211. // returns a shape array from positions array
  65212. SolidParticleSystem.prototype._posToShape = function (positions) {
  65213. var shape = [];
  65214. for (var i = 0; i < positions.length; i += 3) {
  65215. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  65216. }
  65217. return shape;
  65218. };
  65219. // returns a shapeUV array from a Vector4 uvs
  65220. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  65221. var shapeUV = [];
  65222. if (uvs) {
  65223. for (var i = 0; i < uvs.length; i++)
  65224. shapeUV.push(uvs[i]);
  65225. }
  65226. return shapeUV;
  65227. };
  65228. // adds a new particle object in the particles array
  65229. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  65230. if (bInfo === void 0) { bInfo = null; }
  65231. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  65232. this.particles.push(sp);
  65233. return sp;
  65234. };
  65235. /**
  65236. * Adds some particles to the SPS from the model shape. Returns the shape id.
  65237. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  65238. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  65239. * @param nb (positive integer) the number of particles to be created from this model
  65240. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  65241. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  65242. * @returns the number of shapes in the system
  65243. */
  65244. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  65245. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65246. var meshInd = mesh.getIndices();
  65247. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65248. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65249. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65250. var bbInfo;
  65251. if (this._particlesIntersect) {
  65252. bbInfo = mesh.getBoundingInfo();
  65253. }
  65254. var shape = this._posToShape(meshPos);
  65255. var shapeUV = this._uvsToShapeUV(meshUV);
  65256. var posfunc = options ? options.positionFunction : null;
  65257. var vtxfunc = options ? options.vertexFunction : null;
  65258. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  65259. // particles
  65260. var sp;
  65261. var currentCopy;
  65262. var idx = this.nbParticles;
  65263. for (var i = 0; i < nb; i++) {
  65264. var currentPos = this._positions.length;
  65265. var currentInd = this._indices.length;
  65266. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  65267. if (this._updatable) {
  65268. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  65269. sp.position.copyFrom(currentCopy.position);
  65270. sp.rotation.copyFrom(currentCopy.rotation);
  65271. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  65272. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  65273. }
  65274. if (currentCopy.color && sp.color) {
  65275. sp.color.copyFrom(currentCopy.color);
  65276. }
  65277. sp.scaling.copyFrom(currentCopy.scaling);
  65278. sp.uvs.copyFrom(currentCopy.uvs);
  65279. }
  65280. this._index += shape.length;
  65281. idx++;
  65282. }
  65283. this.nbParticles += nb;
  65284. this._shapeCounter++;
  65285. return this._shapeCounter - 1;
  65286. };
  65287. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  65288. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  65289. this._resetCopy();
  65290. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  65291. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  65292. }
  65293. if (this._copy.rotationQuaternion) {
  65294. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65295. }
  65296. else {
  65297. this._yaw = this._copy.rotation.y;
  65298. this._pitch = this._copy.rotation.x;
  65299. this._roll = this._copy.rotation.z;
  65300. this._quaternionRotationYPR();
  65301. }
  65302. this._quaternionToRotationMatrix();
  65303. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65304. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65305. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65306. if (this._copy.translateFromPivot) {
  65307. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65308. }
  65309. else {
  65310. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65311. }
  65312. this._shape = particle._model._shape;
  65313. for (var pt = 0; pt < this._shape.length; pt++) {
  65314. this._vertex.x = this._shape[pt].x;
  65315. this._vertex.y = this._shape[pt].y;
  65316. this._vertex.z = this._shape[pt].z;
  65317. if (particle._model._vertexFunction) {
  65318. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  65319. }
  65320. this._vertex.x *= this._copy.scaling.x;
  65321. this._vertex.y *= this._copy.scaling.y;
  65322. this._vertex.z *= this._copy.scaling.z;
  65323. this._vertex.x -= this._scaledPivot.x;
  65324. this._vertex.y -= this._scaledPivot.y;
  65325. this._vertex.z -= this._scaledPivot.z;
  65326. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65327. this._rotated.addInPlace(this._pivotBackTranslation);
  65328. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  65329. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  65330. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  65331. }
  65332. particle.position.x = 0.0;
  65333. particle.position.y = 0.0;
  65334. particle.position.z = 0.0;
  65335. particle.rotation.x = 0.0;
  65336. particle.rotation.y = 0.0;
  65337. particle.rotation.z = 0.0;
  65338. particle.rotationQuaternion = null;
  65339. particle.scaling.x = 1.0;
  65340. particle.scaling.y = 1.0;
  65341. particle.scaling.z = 1.0;
  65342. particle.uvs.x = 0.0;
  65343. particle.uvs.y = 0.0;
  65344. particle.uvs.z = 1.0;
  65345. particle.uvs.w = 1.0;
  65346. particle.pivot.x = 0.0;
  65347. particle.pivot.y = 0.0;
  65348. particle.pivot.z = 0.0;
  65349. particle.translateFromPivot = false;
  65350. particle.parentId = null;
  65351. };
  65352. /**
  65353. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  65354. * @returns the SPS.
  65355. */
  65356. SolidParticleSystem.prototype.rebuildMesh = function () {
  65357. for (var p = 0; p < this.particles.length; p++) {
  65358. this._rebuildParticle(this.particles[p]);
  65359. }
  65360. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65361. return this;
  65362. };
  65363. /**
  65364. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  65365. * This method calls `updateParticle()` for each particle of the SPS.
  65366. * For an animated SPS, it is usually called within the render loop.
  65367. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  65368. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  65369. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  65370. * @returns the SPS.
  65371. */
  65372. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  65373. if (start === void 0) { start = 0; }
  65374. if (end === void 0) { end = this.nbParticles - 1; }
  65375. if (update === void 0) { update = true; }
  65376. if (!this._updatable) {
  65377. return this;
  65378. }
  65379. // custom beforeUpdate
  65380. this.beforeUpdateParticles(start, end, update);
  65381. this._cam_axisX.x = 1.0;
  65382. this._cam_axisX.y = 0.0;
  65383. this._cam_axisX.z = 0.0;
  65384. this._cam_axisY.x = 0.0;
  65385. this._cam_axisY.y = 1.0;
  65386. this._cam_axisY.z = 0.0;
  65387. this._cam_axisZ.x = 0.0;
  65388. this._cam_axisZ.y = 0.0;
  65389. this._cam_axisZ.z = 1.0;
  65390. // cases when the World Matrix is to be computed first
  65391. if (this.billboard || this._depthSort) {
  65392. this.mesh.computeWorldMatrix(true);
  65393. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  65394. }
  65395. // if the particles will always face the camera
  65396. if (this.billboard) {
  65397. // compute the camera position and un-rotate it by the current mesh rotation
  65398. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  65399. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  65400. this._cam_axisZ.normalize();
  65401. // same for camera up vector extracted from the cam view matrix
  65402. var view = this._camera.getViewMatrix(true);
  65403. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  65404. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  65405. this._cam_axisY.normalize();
  65406. this._cam_axisX.normalize();
  65407. }
  65408. // if depthSort, compute the camera global position in the mesh local system
  65409. if (this._depthSort) {
  65410. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  65411. }
  65412. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  65413. var idx = 0; // current position index in the global array positions32
  65414. var index = 0; // position start index in the global array positions32 of the current particle
  65415. var colidx = 0; // current color index in the global array colors32
  65416. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  65417. var uvidx = 0; // current uv index in the global array uvs32
  65418. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  65419. var pt = 0; // current index in the particle model shape
  65420. if (this.mesh.isFacetDataEnabled) {
  65421. this._computeBoundingBox = true;
  65422. }
  65423. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  65424. if (this._computeBoundingBox) {
  65425. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  65426. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  65427. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  65428. }
  65429. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  65430. if (this.mesh._boundingInfo) {
  65431. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  65432. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  65433. }
  65434. }
  65435. }
  65436. // particle loop
  65437. index = this.particles[start]._pos;
  65438. var vpos = (index / 3) | 0;
  65439. colorIndex = vpos * 4;
  65440. uvIndex = vpos * 2;
  65441. for (var p = start; p <= end; p++) {
  65442. this._particle = this.particles[p];
  65443. this._shape = this._particle._model._shape;
  65444. this._shapeUV = this._particle._model._shapeUV;
  65445. // call to custom user function to update the particle properties
  65446. this.updateParticle(this._particle);
  65447. // camera-particle distance for depth sorting
  65448. if (this._depthSort && this._depthSortParticles) {
  65449. var dsp = this.depthSortedParticles[p];
  65450. dsp.ind = this._particle._ind;
  65451. dsp.indicesLength = this._particle._model._indicesLength;
  65452. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  65453. }
  65454. // skip the computations for inactive or already invisible particles
  65455. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  65456. // increment indexes for the next particle
  65457. pt = this._shape.length;
  65458. index += pt * 3;
  65459. colorIndex += pt * 4;
  65460. uvIndex += pt * 2;
  65461. continue;
  65462. }
  65463. if (this._particle.isVisible) {
  65464. this._particle._stillInvisible = false; // un-mark permanent invisibility
  65465. this._particleHasParent = (this._particle.parentId !== null);
  65466. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65467. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65468. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65469. // particle rotation matrix
  65470. if (this.billboard) {
  65471. this._particle.rotation.x = 0.0;
  65472. this._particle.rotation.y = 0.0;
  65473. }
  65474. if (this._computeParticleRotation || this.billboard) {
  65475. if (this._particle.rotationQuaternion) {
  65476. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65477. }
  65478. else {
  65479. this._yaw = this._particle.rotation.y;
  65480. this._pitch = this._particle.rotation.x;
  65481. this._roll = this._particle.rotation.z;
  65482. this._quaternionRotationYPR();
  65483. }
  65484. this._quaternionToRotationMatrix();
  65485. }
  65486. if (this._particleHasParent) {
  65487. this._parent = this.particles[this._particle.parentId];
  65488. 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];
  65489. 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];
  65490. 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];
  65491. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  65492. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  65493. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  65494. if (this._computeParticleRotation || this.billboard) {
  65495. 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];
  65496. 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];
  65497. 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];
  65498. 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];
  65499. 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];
  65500. 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];
  65501. 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];
  65502. 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];
  65503. 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];
  65504. }
  65505. }
  65506. else {
  65507. this._particle._globalPosition.x = this._particle.position.x;
  65508. this._particle._globalPosition.y = this._particle.position.y;
  65509. this._particle._globalPosition.z = this._particle.position.z;
  65510. if (this._computeParticleRotation || this.billboard) {
  65511. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  65512. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  65513. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  65514. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  65515. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  65516. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  65517. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  65518. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  65519. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  65520. }
  65521. }
  65522. if (this._particle.translateFromPivot) {
  65523. this._pivotBackTranslation.x = 0.0;
  65524. this._pivotBackTranslation.y = 0.0;
  65525. this._pivotBackTranslation.z = 0.0;
  65526. }
  65527. else {
  65528. this._pivotBackTranslation.x = this._scaledPivot.x;
  65529. this._pivotBackTranslation.y = this._scaledPivot.y;
  65530. this._pivotBackTranslation.z = this._scaledPivot.z;
  65531. }
  65532. // particle vertex loop
  65533. for (pt = 0; pt < this._shape.length; pt++) {
  65534. idx = index + pt * 3;
  65535. colidx = colorIndex + pt * 4;
  65536. uvidx = uvIndex + pt * 2;
  65537. this._vertex.x = this._shape[pt].x;
  65538. this._vertex.y = this._shape[pt].y;
  65539. this._vertex.z = this._shape[pt].z;
  65540. if (this._computeParticleVertex) {
  65541. this.updateParticleVertex(this._particle, this._vertex, pt);
  65542. }
  65543. // positions
  65544. this._vertex.x *= this._particle.scaling.x;
  65545. this._vertex.y *= this._particle.scaling.y;
  65546. this._vertex.z *= this._particle.scaling.z;
  65547. this._vertex.x -= this._scaledPivot.x;
  65548. this._vertex.y -= this._scaledPivot.y;
  65549. this._vertex.z -= this._scaledPivot.z;
  65550. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65551. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65552. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65553. this._rotated.x += this._pivotBackTranslation.x;
  65554. this._rotated.y += this._pivotBackTranslation.y;
  65555. this._rotated.z += this._pivotBackTranslation.z;
  65556. 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;
  65557. 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;
  65558. 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;
  65559. if (this._computeBoundingBox) {
  65560. if (this._positions32[idx] < this._minimum.x) {
  65561. this._minimum.x = this._positions32[idx];
  65562. }
  65563. if (this._positions32[idx] > this._maximum.x) {
  65564. this._maximum.x = this._positions32[idx];
  65565. }
  65566. if (this._positions32[idx + 1] < this._minimum.y) {
  65567. this._minimum.y = this._positions32[idx + 1];
  65568. }
  65569. if (this._positions32[idx + 1] > this._maximum.y) {
  65570. this._maximum.y = this._positions32[idx + 1];
  65571. }
  65572. if (this._positions32[idx + 2] < this._minimum.z) {
  65573. this._minimum.z = this._positions32[idx + 2];
  65574. }
  65575. if (this._positions32[idx + 2] > this._maximum.z) {
  65576. this._maximum.z = this._positions32[idx + 2];
  65577. }
  65578. }
  65579. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  65580. if (!this._computeParticleVertex) {
  65581. this._normal.x = this._fixedNormal32[idx];
  65582. this._normal.y = this._fixedNormal32[idx + 1];
  65583. this._normal.z = this._fixedNormal32[idx + 2];
  65584. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  65585. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  65586. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  65587. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  65588. 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;
  65589. 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;
  65590. }
  65591. if (this._computeParticleColor && this._particle.color) {
  65592. this._colors32[colidx] = this._particle.color.r;
  65593. this._colors32[colidx + 1] = this._particle.color.g;
  65594. this._colors32[colidx + 2] = this._particle.color.b;
  65595. this._colors32[colidx + 3] = this._particle.color.a;
  65596. }
  65597. if (this._computeParticleTexture) {
  65598. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65599. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65600. }
  65601. }
  65602. }
  65603. // particle just set invisible : scaled to zero and positioned at the origin
  65604. else {
  65605. this._particle._stillInvisible = true; // mark the particle as invisible
  65606. for (pt = 0; pt < this._shape.length; pt++) {
  65607. idx = index + pt * 3;
  65608. colidx = colorIndex + pt * 4;
  65609. uvidx = uvIndex + pt * 2;
  65610. this._positions32[idx] = 0.0;
  65611. this._positions32[idx + 1] = 0.0;
  65612. this._positions32[idx + 2] = 0.0;
  65613. this._normals32[idx] = 0.0;
  65614. this._normals32[idx + 1] = 0.0;
  65615. this._normals32[idx + 2] = 0.0;
  65616. if (this._computeParticleColor && this._particle.color) {
  65617. this._colors32[colidx] = this._particle.color.r;
  65618. this._colors32[colidx + 1] = this._particle.color.g;
  65619. this._colors32[colidx + 2] = this._particle.color.b;
  65620. this._colors32[colidx + 3] = this._particle.color.a;
  65621. }
  65622. if (this._computeParticleTexture) {
  65623. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65624. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65625. }
  65626. }
  65627. }
  65628. // if the particle intersections must be computed : update the bbInfo
  65629. if (this._particlesIntersect) {
  65630. var bInfo = this._particle._boundingInfo;
  65631. var bBox = bInfo.boundingBox;
  65632. var bSphere = bInfo.boundingSphere;
  65633. if (!this._bSphereOnly) {
  65634. // place, scale and rotate the particle bbox within the SPS local system, then update it
  65635. for (var b = 0; b < bBox.vectors.length; b++) {
  65636. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  65637. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  65638. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  65639. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65640. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65641. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65642. 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;
  65643. 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;
  65644. 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;
  65645. }
  65646. bBox._update(this.mesh._worldMatrix);
  65647. }
  65648. // place and scale the particle bouding sphere in the SPS local system, then update it
  65649. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  65650. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  65651. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  65652. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  65653. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  65654. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  65655. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  65656. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  65657. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  65658. 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));
  65659. bSphere._update(this.mesh._worldMatrix);
  65660. }
  65661. // increment indexes for the next particle
  65662. index = idx + 3;
  65663. colorIndex = colidx + 4;
  65664. uvIndex = uvidx + 2;
  65665. }
  65666. // if the VBO must be updated
  65667. if (update) {
  65668. if (this._computeParticleColor) {
  65669. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  65670. }
  65671. if (this._computeParticleTexture) {
  65672. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  65673. }
  65674. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65675. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  65676. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  65677. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  65678. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  65679. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  65680. for (var i = 0; i < this._normals32.length; i++) {
  65681. this._fixedNormal32[i] = this._normals32[i];
  65682. }
  65683. }
  65684. if (!this.mesh.areNormalsFrozen) {
  65685. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  65686. }
  65687. }
  65688. if (this._depthSort && this._depthSortParticles) {
  65689. this.depthSortedParticles.sort(this._depthSortFunction);
  65690. var dspl = this.depthSortedParticles.length;
  65691. var sorted = 0;
  65692. var lind = 0;
  65693. var sind = 0;
  65694. var sid = 0;
  65695. for (sorted = 0; sorted < dspl; sorted++) {
  65696. lind = this.depthSortedParticles[sorted].indicesLength;
  65697. sind = this.depthSortedParticles[sorted].ind;
  65698. for (var i = 0; i < lind; i++) {
  65699. this._indices32[sid] = this._indices[sind + i];
  65700. sid++;
  65701. }
  65702. }
  65703. this.mesh.updateIndices(this._indices32);
  65704. }
  65705. }
  65706. if (this._computeBoundingBox) {
  65707. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  65708. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  65709. }
  65710. this.afterUpdateParticles(start, end, update);
  65711. return this;
  65712. };
  65713. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  65714. this._halfroll = this._roll * 0.5;
  65715. this._halfpitch = this._pitch * 0.5;
  65716. this._halfyaw = this._yaw * 0.5;
  65717. this._sinRoll = Math.sin(this._halfroll);
  65718. this._cosRoll = Math.cos(this._halfroll);
  65719. this._sinPitch = Math.sin(this._halfpitch);
  65720. this._cosPitch = Math.cos(this._halfpitch);
  65721. this._sinYaw = Math.sin(this._halfyaw);
  65722. this._cosYaw = Math.cos(this._halfyaw);
  65723. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  65724. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  65725. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  65726. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  65727. };
  65728. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  65729. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  65730. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  65731. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  65732. this._rotMatrix.m[3] = 0;
  65733. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  65734. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  65735. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  65736. this._rotMatrix.m[7] = 0;
  65737. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  65738. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  65739. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  65740. this._rotMatrix.m[11] = 0;
  65741. this._rotMatrix.m[12] = 0;
  65742. this._rotMatrix.m[13] = 0;
  65743. this._rotMatrix.m[14] = 0;
  65744. this._rotMatrix.m[15] = 1.0;
  65745. };
  65746. /**
  65747. * Disposes the SPS.
  65748. */
  65749. SolidParticleSystem.prototype.dispose = function () {
  65750. this.mesh.dispose();
  65751. this.vars = null;
  65752. // drop references to internal big arrays for the GC
  65753. this._positions = null;
  65754. this._indices = null;
  65755. this._normals = null;
  65756. this._uvs = null;
  65757. this._colors = null;
  65758. this._indices32 = null;
  65759. this._positions32 = null;
  65760. this._normals32 = null;
  65761. this._fixedNormal32 = null;
  65762. this._uvs32 = null;
  65763. this._colors32 = null;
  65764. this.pickedParticles = null;
  65765. };
  65766. /**
  65767. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  65768. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65769. * @returns the SPS.
  65770. */
  65771. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  65772. if (!this._isVisibilityBoxLocked) {
  65773. this.mesh.refreshBoundingInfo();
  65774. }
  65775. return this;
  65776. };
  65777. /**
  65778. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  65779. * @param size the size (float) of the visibility box
  65780. * note : this doesn't lock the SPS mesh bounding box.
  65781. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65782. */
  65783. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  65784. var vis = size / 2;
  65785. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  65786. };
  65787. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  65788. /**
  65789. * Gets whether the SPS as always visible or not
  65790. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65791. */
  65792. get: function () {
  65793. return this._alwaysVisible;
  65794. },
  65795. /**
  65796. * Sets the SPS as always visible or not
  65797. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65798. */
  65799. set: function (val) {
  65800. this._alwaysVisible = val;
  65801. this.mesh.alwaysSelectAsActiveMesh = val;
  65802. },
  65803. enumerable: true,
  65804. configurable: true
  65805. });
  65806. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  65807. /**
  65808. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65809. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65810. */
  65811. get: function () {
  65812. return this._isVisibilityBoxLocked;
  65813. },
  65814. /**
  65815. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65816. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65817. */
  65818. set: function (val) {
  65819. this._isVisibilityBoxLocked = val;
  65820. var boundingInfo = this.mesh.getBoundingInfo();
  65821. boundingInfo.isLocked = val;
  65822. },
  65823. enumerable: true,
  65824. configurable: true
  65825. });
  65826. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  65827. /**
  65828. * Gets if `setParticles()` computes the particle rotations or not.
  65829. * Default value : true. The SPS is faster when it's set to false.
  65830. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65831. */
  65832. get: function () {
  65833. return this._computeParticleRotation;
  65834. },
  65835. /**
  65836. * Tells to `setParticles()` to compute the particle rotations or not.
  65837. * Default value : true. The SPS is faster when it's set to false.
  65838. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65839. */
  65840. set: function (val) {
  65841. this._computeParticleRotation = val;
  65842. },
  65843. enumerable: true,
  65844. configurable: true
  65845. });
  65846. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  65847. /**
  65848. * Gets if `setParticles()` computes the particle colors or not.
  65849. * Default value : true. The SPS is faster when it's set to false.
  65850. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65851. */
  65852. get: function () {
  65853. return this._computeParticleColor;
  65854. },
  65855. /**
  65856. * Tells to `setParticles()` to compute the particle colors or not.
  65857. * Default value : true. The SPS is faster when it's set to false.
  65858. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65859. */
  65860. set: function (val) {
  65861. this._computeParticleColor = val;
  65862. },
  65863. enumerable: true,
  65864. configurable: true
  65865. });
  65866. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  65867. /**
  65868. * Gets if `setParticles()` computes the particle textures or not.
  65869. * Default value : true. The SPS is faster when it's set to false.
  65870. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  65871. */
  65872. get: function () {
  65873. return this._computeParticleTexture;
  65874. },
  65875. set: function (val) {
  65876. this._computeParticleTexture = val;
  65877. },
  65878. enumerable: true,
  65879. configurable: true
  65880. });
  65881. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  65882. /**
  65883. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  65884. * Default value : false. The SPS is faster when it's set to false.
  65885. * Note : the particle custom vertex positions aren't stored values.
  65886. */
  65887. get: function () {
  65888. return this._computeParticleVertex;
  65889. },
  65890. /**
  65891. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  65892. * Default value : false. The SPS is faster when it's set to false.
  65893. * Note : the particle custom vertex positions aren't stored values.
  65894. */
  65895. set: function (val) {
  65896. this._computeParticleVertex = val;
  65897. },
  65898. enumerable: true,
  65899. configurable: true
  65900. });
  65901. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  65902. /**
  65903. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  65904. */
  65905. get: function () {
  65906. return this._computeBoundingBox;
  65907. },
  65908. /**
  65909. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  65910. */
  65911. set: function (val) {
  65912. this._computeBoundingBox = val;
  65913. },
  65914. enumerable: true,
  65915. configurable: true
  65916. });
  65917. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  65918. /**
  65919. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  65920. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65921. * Default : `true`
  65922. */
  65923. get: function () {
  65924. return this._depthSortParticles;
  65925. },
  65926. /**
  65927. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  65928. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65929. * Default : `true`
  65930. */
  65931. set: function (val) {
  65932. this._depthSortParticles = val;
  65933. },
  65934. enumerable: true,
  65935. configurable: true
  65936. });
  65937. // =======================================================================
  65938. // Particle behavior logic
  65939. // these following methods may be overwritten by the user to fit his needs
  65940. /**
  65941. * This function does nothing. It may be overwritten to set all the particle first values.
  65942. * The SPS doesn't call this function, you may have to call it by your own.
  65943. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65944. */
  65945. SolidParticleSystem.prototype.initParticles = function () {
  65946. };
  65947. /**
  65948. * This function does nothing. It may be overwritten to recycle a particle.
  65949. * The SPS doesn't call this function, you may have to call it by your own.
  65950. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65951. * @param particle The particle to recycle
  65952. * @returns the recycled particle
  65953. */
  65954. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  65955. return particle;
  65956. };
  65957. /**
  65958. * Updates a particle : this function should be overwritten by the user.
  65959. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  65960. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65961. * @example : just set a particle position or velocity and recycle conditions
  65962. * @param particle The particle to update
  65963. * @returns the updated particle
  65964. */
  65965. SolidParticleSystem.prototype.updateParticle = function (particle) {
  65966. return particle;
  65967. };
  65968. /**
  65969. * Updates a vertex of a particle : it can be overwritten by the user.
  65970. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  65971. * @param particle the current particle
  65972. * @param vertex the current index of the current particle
  65973. * @param pt the index of the current vertex in the particle shape
  65974. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  65975. * @example : just set a vertex particle position
  65976. * @returns the updated vertex
  65977. */
  65978. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  65979. return vertex;
  65980. };
  65981. /**
  65982. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  65983. * This does nothing and may be overwritten by the user.
  65984. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65985. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65986. * @param update the boolean update value actually passed to setParticles()
  65987. */
  65988. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  65989. };
  65990. /**
  65991. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  65992. * This will be passed three parameters.
  65993. * This does nothing and may be overwritten by the user.
  65994. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65995. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65996. * @param update the boolean update value actually passed to setParticles()
  65997. */
  65998. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  65999. };
  66000. return SolidParticleSystem;
  66001. }());
  66002. BABYLON.SolidParticleSystem = SolidParticleSystem;
  66003. })(BABYLON || (BABYLON = {}));
  66004. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  66005. var BABYLON;
  66006. (function (BABYLON) {
  66007. /**
  66008. * Class containing static functions to help procedurally build meshes
  66009. */
  66010. var MeshBuilder = /** @class */ (function () {
  66011. function MeshBuilder() {
  66012. }
  66013. MeshBuilder.updateSideOrientation = function (orientation) {
  66014. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  66015. return BABYLON.Mesh.DOUBLESIDE;
  66016. }
  66017. if (orientation === undefined || orientation === null) {
  66018. return BABYLON.Mesh.FRONTSIDE;
  66019. }
  66020. return orientation;
  66021. };
  66022. /**
  66023. * Creates a box mesh
  66024. * * The parameter `size` sets the size (float) of each box side (default 1)
  66025. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  66026. * * 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)
  66027. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66028. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66029. * * 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
  66030. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66031. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  66032. * @param name defines the name of the mesh
  66033. * @param options defines the options used to create the mesh
  66034. * @param scene defines the hosting scene
  66035. * @returns the box mesh
  66036. */
  66037. MeshBuilder.CreateBox = function (name, options, scene) {
  66038. if (scene === void 0) { scene = null; }
  66039. var box = new BABYLON.Mesh(name, scene);
  66040. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66041. box._originalBuilderSideOrientation = options.sideOrientation;
  66042. var vertexData = BABYLON.VertexData.CreateBox(options);
  66043. vertexData.applyToMesh(box, options.updatable);
  66044. return box;
  66045. };
  66046. /**
  66047. * Creates a sphere mesh
  66048. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  66049. * * 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`)
  66050. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  66051. * * 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
  66052. * * 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)
  66053. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66054. * * 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
  66055. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66056. * @param name defines the name of the mesh
  66057. * @param options defines the options used to create the mesh
  66058. * @param scene defines the hosting scene
  66059. * @returns the sphere mesh
  66060. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  66061. */
  66062. MeshBuilder.CreateSphere = function (name, options, scene) {
  66063. var sphere = new BABYLON.Mesh(name, scene);
  66064. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66065. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66066. var vertexData = BABYLON.VertexData.CreateSphere(options);
  66067. vertexData.applyToMesh(sphere, options.updatable);
  66068. return sphere;
  66069. };
  66070. /**
  66071. * Creates a plane polygonal mesh. By default, this is a disc
  66072. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  66073. * * 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
  66074. * * 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
  66075. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66076. * * 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
  66077. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66078. * @param name defines the name of the mesh
  66079. * @param options defines the options used to create the mesh
  66080. * @param scene defines the hosting scene
  66081. * @returns the plane polygonal mesh
  66082. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  66083. */
  66084. MeshBuilder.CreateDisc = function (name, options, scene) {
  66085. if (scene === void 0) { scene = null; }
  66086. var disc = new BABYLON.Mesh(name, scene);
  66087. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66088. disc._originalBuilderSideOrientation = options.sideOrientation;
  66089. var vertexData = BABYLON.VertexData.CreateDisc(options);
  66090. vertexData.applyToMesh(disc, options.updatable);
  66091. return disc;
  66092. };
  66093. /**
  66094. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  66095. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  66096. * * 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`)
  66097. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  66098. * * 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
  66099. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66100. * * 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
  66101. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66102. * @param name defines the name of the mesh
  66103. * @param options defines the options used to create the mesh
  66104. * @param scene defines the hosting scene
  66105. * @returns the icosahedron mesh
  66106. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  66107. */
  66108. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  66109. var sphere = new BABYLON.Mesh(name, scene);
  66110. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66111. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66112. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  66113. vertexData.applyToMesh(sphere, options.updatable);
  66114. return sphere;
  66115. };
  66116. ;
  66117. /**
  66118. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66119. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  66120. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  66121. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  66122. * * 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
  66123. * * 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
  66124. * * 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
  66125. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66126. * * 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
  66127. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66128. * * 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
  66129. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  66130. * * 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
  66131. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  66132. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66133. * @param name defines the name of the mesh
  66134. * @param options defines the options used to create the mesh
  66135. * @param scene defines the hosting scene
  66136. * @returns the ribbon mesh
  66137. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  66138. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66139. */
  66140. MeshBuilder.CreateRibbon = function (name, options, scene) {
  66141. if (scene === void 0) { scene = null; }
  66142. var pathArray = options.pathArray;
  66143. var closeArray = options.closeArray;
  66144. var closePath = options.closePath;
  66145. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66146. var instance = options.instance;
  66147. var updatable = options.updatable;
  66148. if (instance) { // existing ribbon instance update
  66149. // positionFunction : ribbon case
  66150. // only pathArray and sideOrientation parameters are taken into account for positions update
  66151. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  66152. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  66153. var positionFunction = function (positions) {
  66154. var minlg = pathArray[0].length;
  66155. var i = 0;
  66156. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  66157. for (var si = 1; si <= ns; si++) {
  66158. for (var p = 0; p < pathArray.length; p++) {
  66159. var path = pathArray[p];
  66160. var l = path.length;
  66161. minlg = (minlg < l) ? minlg : l;
  66162. var j = 0;
  66163. while (j < minlg) {
  66164. positions[i] = path[j].x;
  66165. positions[i + 1] = path[j].y;
  66166. positions[i + 2] = path[j].z;
  66167. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  66168. BABYLON.Tmp.Vector3[0].x = path[j].x;
  66169. }
  66170. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  66171. BABYLON.Tmp.Vector3[1].x = path[j].x;
  66172. }
  66173. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  66174. BABYLON.Tmp.Vector3[0].y = path[j].y;
  66175. }
  66176. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  66177. BABYLON.Tmp.Vector3[1].y = path[j].y;
  66178. }
  66179. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  66180. BABYLON.Tmp.Vector3[0].z = path[j].z;
  66181. }
  66182. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  66183. BABYLON.Tmp.Vector3[1].z = path[j].z;
  66184. }
  66185. j++;
  66186. i += 3;
  66187. }
  66188. if (instance._closePath) {
  66189. positions[i] = path[0].x;
  66190. positions[i + 1] = path[0].y;
  66191. positions[i + 2] = path[0].z;
  66192. i += 3;
  66193. }
  66194. }
  66195. }
  66196. };
  66197. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66198. positionFunction(positions);
  66199. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  66200. instance._boundingInfo.update(instance._worldMatrix);
  66201. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  66202. if (options.colors) {
  66203. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66204. for (var c = 0; c < options.colors.length; c++) {
  66205. colors[c * 4] = options.colors[c].r;
  66206. colors[c * 4 + 1] = options.colors[c].g;
  66207. colors[c * 4 + 2] = options.colors[c].b;
  66208. colors[c * 4 + 3] = options.colors[c].a;
  66209. }
  66210. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  66211. }
  66212. if (options.uvs) {
  66213. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66214. for (var i = 0; i < options.uvs.length; i++) {
  66215. uvs[i * 2] = options.uvs[i].x;
  66216. uvs[i * 2 + 1] = options.uvs[i].y;
  66217. }
  66218. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  66219. }
  66220. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  66221. var indices = instance.getIndices();
  66222. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66223. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  66224. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  66225. if (instance._closePath) {
  66226. var indexFirst = 0;
  66227. var indexLast = 0;
  66228. for (var p = 0; p < pathArray.length; p++) {
  66229. indexFirst = instance._idx[p] * 3;
  66230. if (p + 1 < pathArray.length) {
  66231. indexLast = (instance._idx[p + 1] - 1) * 3;
  66232. }
  66233. else {
  66234. indexLast = normals.length - 3;
  66235. }
  66236. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  66237. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  66238. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  66239. normals[indexLast] = normals[indexFirst];
  66240. normals[indexLast + 1] = normals[indexFirst + 1];
  66241. normals[indexLast + 2] = normals[indexFirst + 2];
  66242. }
  66243. }
  66244. if (!(instance.areNormalsFrozen)) {
  66245. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  66246. }
  66247. }
  66248. return instance;
  66249. }
  66250. else { // new ribbon creation
  66251. var ribbon = new BABYLON.Mesh(name, scene);
  66252. ribbon._originalBuilderSideOrientation = sideOrientation;
  66253. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  66254. if (closePath) {
  66255. ribbon._idx = vertexData._idx;
  66256. }
  66257. ribbon._closePath = closePath;
  66258. ribbon._closeArray = closeArray;
  66259. vertexData.applyToMesh(ribbon, updatable);
  66260. return ribbon;
  66261. }
  66262. };
  66263. /**
  66264. * Creates a cylinder or a cone mesh
  66265. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  66266. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  66267. * * 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.
  66268. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  66269. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  66270. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  66271. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  66272. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  66273. * * 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).
  66274. * * 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
  66275. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  66276. * * 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
  66277. * * 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.
  66278. * * If `enclose` is false, a ring surface is one element.
  66279. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  66280. * * 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
  66281. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66282. * * 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
  66283. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66284. * @param name defines the name of the mesh
  66285. * @param options defines the options used to create the mesh
  66286. * @param scene defines the hosting scene
  66287. * @returns the cylinder mesh
  66288. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  66289. */
  66290. MeshBuilder.CreateCylinder = function (name, options, scene) {
  66291. var cylinder = new BABYLON.Mesh(name, scene);
  66292. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66293. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  66294. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  66295. vertexData.applyToMesh(cylinder, options.updatable);
  66296. return cylinder;
  66297. };
  66298. /**
  66299. * Creates a torus mesh
  66300. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  66301. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  66302. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  66303. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66304. * * 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
  66305. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66306. * @param name defines the name of the mesh
  66307. * @param options defines the options used to create the mesh
  66308. * @param scene defines the hosting scene
  66309. * @returns the torus mesh
  66310. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  66311. */
  66312. MeshBuilder.CreateTorus = function (name, options, scene) {
  66313. var torus = new BABYLON.Mesh(name, scene);
  66314. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66315. torus._originalBuilderSideOrientation = options.sideOrientation;
  66316. var vertexData = BABYLON.VertexData.CreateTorus(options);
  66317. vertexData.applyToMesh(torus, options.updatable);
  66318. return torus;
  66319. };
  66320. /**
  66321. * Creates a torus knot mesh
  66322. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  66323. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  66324. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  66325. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  66326. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66327. * * 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
  66328. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66329. * @param name defines the name of the mesh
  66330. * @param options defines the options used to create the mesh
  66331. * @param scene defines the hosting scene
  66332. * @returns the torus knot mesh
  66333. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  66334. */
  66335. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  66336. var torusKnot = new BABYLON.Mesh(name, scene);
  66337. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66338. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  66339. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  66340. vertexData.applyToMesh(torusKnot, options.updatable);
  66341. return torusKnot;
  66342. };
  66343. /**
  66344. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  66345. * * 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
  66346. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  66347. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  66348. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  66349. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  66350. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  66351. * * 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
  66352. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  66353. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66354. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  66355. * @param name defines the name of the new line system
  66356. * @param options defines the options used to create the line system
  66357. * @param scene defines the hosting scene
  66358. * @returns a new line system mesh
  66359. */
  66360. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  66361. var instance = options.instance;
  66362. var lines = options.lines;
  66363. var colors = options.colors;
  66364. if (instance) { // lines update
  66365. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66366. var vertexColor;
  66367. var lineColors;
  66368. if (colors) {
  66369. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66370. }
  66371. var i = 0;
  66372. var c = 0;
  66373. for (var l = 0; l < lines.length; l++) {
  66374. var points = lines[l];
  66375. for (var p = 0; p < points.length; p++) {
  66376. positions[i] = points[p].x;
  66377. positions[i + 1] = points[p].y;
  66378. positions[i + 2] = points[p].z;
  66379. if (colors && vertexColor) {
  66380. lineColors = colors[l];
  66381. vertexColor[c] = lineColors[p].r;
  66382. vertexColor[c + 1] = lineColors[p].g;
  66383. vertexColor[c + 2] = lineColors[p].b;
  66384. vertexColor[c + 3] = lineColors[p].a;
  66385. c += 4;
  66386. }
  66387. i += 3;
  66388. }
  66389. }
  66390. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  66391. if (colors && vertexColor) {
  66392. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  66393. }
  66394. return instance;
  66395. }
  66396. // line system creation
  66397. var useVertexColor = (colors) ? true : false;
  66398. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  66399. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  66400. vertexData.applyToMesh(lineSystem, options.updatable);
  66401. return lineSystem;
  66402. };
  66403. /**
  66404. * Creates a line mesh
  66405. * 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
  66406. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66407. * * The parameter `points` is an array successive Vector3
  66408. * * 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
  66409. * * The optional parameter `colors` is an array of successive Color4, one per line point
  66410. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  66411. * * When updating an instance, remember that only point positions can change, not the number of points
  66412. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66413. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  66414. * @param name defines the name of the new line system
  66415. * @param options defines the options used to create the line system
  66416. * @param scene defines the hosting scene
  66417. * @returns a new line mesh
  66418. */
  66419. MeshBuilder.CreateLines = function (name, options, scene) {
  66420. if (scene === void 0) { scene = null; }
  66421. var colors = (options.colors) ? [options.colors] : null;
  66422. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  66423. return lines;
  66424. };
  66425. /**
  66426. * Creates a dashed line mesh
  66427. * * 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
  66428. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66429. * * The parameter `points` is an array successive Vector3
  66430. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  66431. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  66432. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  66433. * * 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
  66434. * * When updating an instance, remember that only point positions can change, not the number of points
  66435. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66436. * @param name defines the name of the mesh
  66437. * @param options defines the options used to create the mesh
  66438. * @param scene defines the hosting scene
  66439. * @returns the dashed line mesh
  66440. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  66441. */
  66442. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  66443. if (scene === void 0) { scene = null; }
  66444. var points = options.points;
  66445. var instance = options.instance;
  66446. var gapSize = options.gapSize || 1;
  66447. var dashSize = options.dashSize || 3;
  66448. if (instance) { // dashed lines update
  66449. var positionFunction = function (positions) {
  66450. var curvect = BABYLON.Vector3.Zero();
  66451. var nbSeg = positions.length / 6;
  66452. var lg = 0;
  66453. var nb = 0;
  66454. var shft = 0;
  66455. var dashshft = 0;
  66456. var curshft = 0;
  66457. var p = 0;
  66458. var i = 0;
  66459. var j = 0;
  66460. for (i = 0; i < points.length - 1; i++) {
  66461. points[i + 1].subtractToRef(points[i], curvect);
  66462. lg += curvect.length();
  66463. }
  66464. shft = lg / nbSeg;
  66465. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  66466. for (i = 0; i < points.length - 1; i++) {
  66467. points[i + 1].subtractToRef(points[i], curvect);
  66468. nb = Math.floor(curvect.length() / shft);
  66469. curvect.normalize();
  66470. j = 0;
  66471. while (j < nb && p < positions.length) {
  66472. curshft = shft * j;
  66473. positions[p] = points[i].x + curshft * curvect.x;
  66474. positions[p + 1] = points[i].y + curshft * curvect.y;
  66475. positions[p + 2] = points[i].z + curshft * curvect.z;
  66476. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  66477. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  66478. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  66479. p += 6;
  66480. j++;
  66481. }
  66482. }
  66483. while (p < positions.length) {
  66484. positions[p] = points[i].x;
  66485. positions[p + 1] = points[i].y;
  66486. positions[p + 2] = points[i].z;
  66487. p += 3;
  66488. }
  66489. };
  66490. instance.updateMeshPositions(positionFunction, false);
  66491. return instance;
  66492. }
  66493. // dashed lines creation
  66494. var dashedLines = new BABYLON.LinesMesh(name, scene);
  66495. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  66496. vertexData.applyToMesh(dashedLines, options.updatable);
  66497. dashedLines.dashSize = dashSize;
  66498. dashedLines.gapSize = gapSize;
  66499. return dashedLines;
  66500. };
  66501. /**
  66502. * 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.
  66503. * * 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.
  66504. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66505. * * 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.
  66506. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  66507. * * 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
  66508. * * 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
  66509. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  66510. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66511. * * 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
  66512. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  66513. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66514. * @param name defines the name of the mesh
  66515. * @param options defines the options used to create the mesh
  66516. * @param scene defines the hosting scene
  66517. * @returns the extruded shape mesh
  66518. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66519. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66520. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66521. */
  66522. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  66523. if (scene === void 0) { scene = null; }
  66524. var path = options.path;
  66525. var shape = options.shape;
  66526. var scale = options.scale || 1;
  66527. var rotation = options.rotation || 0;
  66528. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66529. var updatable = options.updatable;
  66530. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66531. var instance = options.instance || null;
  66532. var invertUV = options.invertUV || false;
  66533. 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);
  66534. };
  66535. /**
  66536. * Creates an custom extruded shape mesh.
  66537. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  66538. * * 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.
  66539. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66540. * * 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
  66541. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  66542. * * 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
  66543. * * It must returns a float value that will be the scale value applied to the shape on each path point
  66544. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  66545. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  66546. * * 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
  66547. * * 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
  66548. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  66549. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66550. * * 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
  66551. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66552. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66553. * @param name defines the name of the mesh
  66554. * @param options defines the options used to create the mesh
  66555. * @param scene defines the hosting scene
  66556. * @returns the custom extruded shape mesh
  66557. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  66558. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66559. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66560. */
  66561. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  66562. var path = options.path;
  66563. var shape = options.shape;
  66564. var scaleFunction = options.scaleFunction || (function () { return 1; });
  66565. var rotationFunction = options.rotationFunction || (function () { return 0; });
  66566. var ribbonCloseArray = options.ribbonCloseArray || false;
  66567. var ribbonClosePath = options.ribbonClosePath || false;
  66568. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66569. var updatable = options.updatable;
  66570. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66571. var instance = options.instance;
  66572. var invertUV = options.invertUV || false;
  66573. 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);
  66574. };
  66575. /**
  66576. * Creates lathe mesh.
  66577. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  66578. * * 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
  66579. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  66580. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  66581. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  66582. * * 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
  66583. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  66584. * * 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
  66585. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66586. * * 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
  66587. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66588. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66589. * @param name defines the name of the mesh
  66590. * @param options defines the options used to create the mesh
  66591. * @param scene defines the hosting scene
  66592. * @returns the lathe mesh
  66593. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  66594. */
  66595. MeshBuilder.CreateLathe = function (name, options, scene) {
  66596. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  66597. var closed = (options.closed === undefined) ? true : options.closed;
  66598. var shape = options.shape;
  66599. var radius = options.radius || 1;
  66600. var tessellation = options.tessellation || 64;
  66601. var clip = options.clip || 0;
  66602. var updatable = options.updatable;
  66603. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66604. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66605. var pi2 = Math.PI * 2;
  66606. var paths = new Array();
  66607. var invertUV = options.invertUV || false;
  66608. var i = 0;
  66609. var p = 0;
  66610. var step = pi2 / tessellation * arc;
  66611. var rotated;
  66612. var path = new Array();
  66613. for (i = 0; i <= tessellation - clip; i++) {
  66614. var path = [];
  66615. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  66616. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  66617. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  66618. }
  66619. for (p = 0; p < shape.length; p++) {
  66620. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  66621. path.push(rotated);
  66622. }
  66623. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  66624. 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));
  66625. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  66626. }
  66627. paths.push(path);
  66628. }
  66629. // lathe ribbon
  66630. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66631. return lathe;
  66632. };
  66633. /**
  66634. * Creates a plane mesh
  66635. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  66636. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  66637. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  66638. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66639. * * 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
  66640. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66641. * @param name defines the name of the mesh
  66642. * @param options defines the options used to create the mesh
  66643. * @param scene defines the hosting scene
  66644. * @returns the plane mesh
  66645. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66646. */
  66647. MeshBuilder.CreatePlane = function (name, options, scene) {
  66648. var plane = new BABYLON.Mesh(name, scene);
  66649. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66650. plane._originalBuilderSideOrientation = options.sideOrientation;
  66651. var vertexData = BABYLON.VertexData.CreatePlane(options);
  66652. vertexData.applyToMesh(plane, options.updatable);
  66653. if (options.sourcePlane) {
  66654. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  66655. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  66656. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  66657. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  66658. plane.rotate(vectorProduct, product);
  66659. }
  66660. }
  66661. return plane;
  66662. };
  66663. /**
  66664. * Creates a ground mesh
  66665. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  66666. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  66667. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66668. * @param name defines the name of the mesh
  66669. * @param options defines the options used to create the mesh
  66670. * @param scene defines the hosting scene
  66671. * @returns the ground mesh
  66672. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66673. */
  66674. MeshBuilder.CreateGround = function (name, options, scene) {
  66675. var ground = new BABYLON.GroundMesh(name, scene);
  66676. ground._setReady(false);
  66677. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  66678. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  66679. ground._width = options.width || 1;
  66680. ground._height = options.height || 1;
  66681. ground._maxX = ground._width / 2;
  66682. ground._maxZ = ground._height / 2;
  66683. ground._minX = -ground._maxX;
  66684. ground._minZ = -ground._maxZ;
  66685. var vertexData = BABYLON.VertexData.CreateGround(options);
  66686. vertexData.applyToMesh(ground, options.updatable);
  66687. ground._setReady(true);
  66688. return ground;
  66689. };
  66690. /**
  66691. * Creates a tiled ground mesh
  66692. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  66693. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  66694. * * 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
  66695. * * 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
  66696. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66697. * @param name defines the name of the mesh
  66698. * @param options defines the options used to create the mesh
  66699. * @param scene defines the hosting scene
  66700. * @returns the tiled ground mesh
  66701. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  66702. */
  66703. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  66704. var tiledGround = new BABYLON.Mesh(name, scene);
  66705. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  66706. vertexData.applyToMesh(tiledGround, options.updatable);
  66707. return tiledGround;
  66708. };
  66709. /**
  66710. * Creates a ground mesh from a height map
  66711. * * The parameter `url` sets the URL of the height map image resource.
  66712. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  66713. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  66714. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  66715. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  66716. * * 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.
  66717. * * 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).
  66718. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  66719. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66720. * @param name defines the name of the mesh
  66721. * @param url defines the url to the height map
  66722. * @param options defines the options used to create the mesh
  66723. * @param scene defines the hosting scene
  66724. * @returns the ground mesh
  66725. * @see http://doc.babylonjs.com/babylon101/height_map
  66726. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  66727. */
  66728. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  66729. var width = options.width || 10.0;
  66730. var height = options.height || 10.0;
  66731. var subdivisions = options.subdivisions || 1 | 0;
  66732. var minHeight = options.minHeight || 0.0;
  66733. var maxHeight = options.maxHeight || 1.0;
  66734. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  66735. var alphaFilter = options.alphaFilter || 0.0;
  66736. var updatable = options.updatable;
  66737. var onReady = options.onReady;
  66738. var ground = new BABYLON.GroundMesh(name, scene);
  66739. ground._subdivisionsX = subdivisions;
  66740. ground._subdivisionsY = subdivisions;
  66741. ground._width = width;
  66742. ground._height = height;
  66743. ground._maxX = ground._width / 2.0;
  66744. ground._maxZ = ground._height / 2.0;
  66745. ground._minX = -ground._maxX;
  66746. ground._minZ = -ground._maxZ;
  66747. ground._setReady(false);
  66748. var onload = function (img) {
  66749. // Getting height map data
  66750. var canvas = document.createElement("canvas");
  66751. var context = canvas.getContext("2d");
  66752. if (!context) {
  66753. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  66754. }
  66755. if (scene.isDisposed) {
  66756. return;
  66757. }
  66758. var bufferWidth = img.width;
  66759. var bufferHeight = img.height;
  66760. canvas.width = bufferWidth;
  66761. canvas.height = bufferHeight;
  66762. context.drawImage(img, 0, 0);
  66763. // Create VertexData from map data
  66764. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  66765. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  66766. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  66767. width: width, height: height,
  66768. subdivisions: subdivisions,
  66769. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  66770. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  66771. alphaFilter: alphaFilter
  66772. });
  66773. vertexData.applyToMesh(ground, updatable);
  66774. //execute ready callback, if set
  66775. if (onReady) {
  66776. onReady(ground);
  66777. }
  66778. ground._setReady(true);
  66779. };
  66780. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  66781. return ground;
  66782. };
  66783. /**
  66784. * Creates a polygon mesh
  66785. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  66786. * * 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
  66787. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66788. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66789. * * 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)
  66790. * * Remember you can only change the shape positions, not their number when updating a polygon
  66791. * @param name defines the name of the mesh
  66792. * @param options defines the options used to create the mesh
  66793. * @param scene defines the hosting scene
  66794. * @returns the polygon mesh
  66795. */
  66796. MeshBuilder.CreatePolygon = function (name, options, scene) {
  66797. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66798. var shape = options.shape;
  66799. var holes = options.holes || [];
  66800. var depth = options.depth || 0;
  66801. var contours = [];
  66802. var hole = [];
  66803. for (var i = 0; i < shape.length; i++) {
  66804. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  66805. }
  66806. var epsilon = 0.00000001;
  66807. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  66808. contours.pop();
  66809. }
  66810. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  66811. for (var hNb = 0; hNb < holes.length; hNb++) {
  66812. hole = [];
  66813. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  66814. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  66815. }
  66816. polygonTriangulation.addHole(hole);
  66817. }
  66818. var polygon = polygonTriangulation.build(options.updatable, depth);
  66819. polygon._originalBuilderSideOrientation = options.sideOrientation;
  66820. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  66821. vertexData.applyToMesh(polygon, options.updatable);
  66822. return polygon;
  66823. };
  66824. ;
  66825. /**
  66826. * Creates an extruded polygon mesh, with depth in the Y direction.
  66827. * * 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)
  66828. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66829. * @param name defines the name of the mesh
  66830. * @param options defines the options used to create the mesh
  66831. * @param scene defines the hosting scene
  66832. * @returns the polygon mesh
  66833. */
  66834. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  66835. return MeshBuilder.CreatePolygon(name, options, scene);
  66836. };
  66837. ;
  66838. /**
  66839. * Creates a tube mesh.
  66840. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66841. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  66842. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  66843. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  66844. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  66845. * * 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)
  66846. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  66847. * * 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
  66848. * * 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
  66849. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66850. * * 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
  66851. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66852. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66853. * @param name defines the name of the mesh
  66854. * @param options defines the options used to create the mesh
  66855. * @param scene defines the hosting scene
  66856. * @returns the tube mesh
  66857. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66858. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  66859. */
  66860. MeshBuilder.CreateTube = function (name, options, scene) {
  66861. var path = options.path;
  66862. var instance = options.instance;
  66863. var radius = 1.0;
  66864. if (instance) {
  66865. radius = instance.radius;
  66866. }
  66867. if (options.radius !== undefined) {
  66868. radius = options.radius;
  66869. }
  66870. ;
  66871. var tessellation = options.tessellation || 64 | 0;
  66872. var radiusFunction = options.radiusFunction || null;
  66873. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66874. var invertUV = options.invertUV || false;
  66875. var updatable = options.updatable;
  66876. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66877. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  66878. // tube geometry
  66879. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  66880. var tangents = path3D.getTangents();
  66881. var normals = path3D.getNormals();
  66882. var distances = path3D.getDistances();
  66883. var pi2 = Math.PI * 2;
  66884. var step = pi2 / tessellation * arc;
  66885. var returnRadius = function () { return radius; };
  66886. var radiusFunctionFinal = radiusFunction || returnRadius;
  66887. var circlePath;
  66888. var rad;
  66889. var normal;
  66890. var rotated;
  66891. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66892. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66893. for (var i = 0; i < path.length; i++) {
  66894. rad = radiusFunctionFinal(i, distances[i]); // current radius
  66895. circlePath = Array(); // current circle array
  66896. normal = normals[i]; // current normal
  66897. for (var t = 0; t < tessellation; t++) {
  66898. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  66899. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  66900. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  66901. rotated.scaleInPlace(rad).addInPlace(path[i]);
  66902. circlePath[t] = rotated;
  66903. }
  66904. circlePaths[index] = circlePath;
  66905. index++;
  66906. }
  66907. // cap
  66908. var capPath = function (nbPoints, pathIndex) {
  66909. var pointCap = Array();
  66910. for (var i = 0; i < nbPoints; i++) {
  66911. pointCap.push(path[pathIndex]);
  66912. }
  66913. return pointCap;
  66914. };
  66915. switch (cap) {
  66916. case BABYLON.Mesh.NO_CAP:
  66917. break;
  66918. case BABYLON.Mesh.CAP_START:
  66919. circlePaths[0] = capPath(tessellation, 0);
  66920. circlePaths[1] = circlePaths[2].slice(0);
  66921. break;
  66922. case BABYLON.Mesh.CAP_END:
  66923. circlePaths[index] = circlePaths[index - 1].slice(0);
  66924. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66925. break;
  66926. case BABYLON.Mesh.CAP_ALL:
  66927. circlePaths[0] = capPath(tessellation, 0);
  66928. circlePaths[1] = circlePaths[2].slice(0);
  66929. circlePaths[index] = circlePaths[index - 1].slice(0);
  66930. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66931. break;
  66932. default:
  66933. break;
  66934. }
  66935. return circlePaths;
  66936. };
  66937. var path3D;
  66938. var pathArray;
  66939. if (instance) { // tube update
  66940. var arc = options.arc || instance.arc;
  66941. path3D = (instance.path3D).update(path);
  66942. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  66943. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  66944. instance.path3D = path3D;
  66945. instance.pathArray = pathArray;
  66946. instance.arc = arc;
  66947. instance.radius = radius;
  66948. return instance;
  66949. }
  66950. // tube creation
  66951. path3D = new BABYLON.Path3D(path);
  66952. var newPathArray = new Array();
  66953. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66954. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  66955. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66956. tube.pathArray = pathArray;
  66957. tube.path3D = path3D;
  66958. tube.tessellation = tessellation;
  66959. tube.cap = cap;
  66960. tube.arc = options.arc;
  66961. tube.radius = radius;
  66962. return tube;
  66963. };
  66964. /**
  66965. * Creates a polyhedron mesh
  66966. * * 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
  66967. * * The parameter `size` (positive float, default 1) sets the polygon size
  66968. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  66969. * * 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`
  66970. * * 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
  66971. * * 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)`)
  66972. * * 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
  66973. * * 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
  66974. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66975. * * 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
  66976. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66977. * @param name defines the name of the mesh
  66978. * @param options defines the options used to create the mesh
  66979. * @param scene defines the hosting scene
  66980. * @returns the polyhedron mesh
  66981. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  66982. */
  66983. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  66984. var polyhedron = new BABYLON.Mesh(name, scene);
  66985. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66986. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  66987. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  66988. vertexData.applyToMesh(polyhedron, options.updatable);
  66989. return polyhedron;
  66990. };
  66991. /**
  66992. * Creates a decal mesh.
  66993. * 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
  66994. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  66995. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  66996. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  66997. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  66998. * @param name defines the name of the mesh
  66999. * @param sourceMesh defines the mesh where the decal must be applied
  67000. * @param options defines the options used to create the mesh
  67001. * @param scene defines the hosting scene
  67002. * @returns the decal mesh
  67003. * @see http://doc.babylonjs.com/how_to/decals
  67004. */
  67005. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  67006. var indices = sourceMesh.getIndices();
  67007. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67008. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67009. var position = options.position || BABYLON.Vector3.Zero();
  67010. var normal = options.normal || BABYLON.Vector3.Up();
  67011. var size = options.size || BABYLON.Vector3.One();
  67012. var angle = options.angle || 0;
  67013. // Getting correct rotation
  67014. if (!normal) {
  67015. var target = new BABYLON.Vector3(0, 0, 1);
  67016. var camera = sourceMesh.getScene().activeCamera;
  67017. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  67018. normal = camera.globalPosition.subtract(cameraWorldTarget);
  67019. }
  67020. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  67021. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  67022. var pitch = Math.atan2(normal.y, len);
  67023. // Matrix
  67024. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  67025. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  67026. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  67027. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  67028. var vertexData = new BABYLON.VertexData();
  67029. vertexData.indices = [];
  67030. vertexData.positions = [];
  67031. vertexData.normals = [];
  67032. vertexData.uvs = [];
  67033. var currentVertexDataIndex = 0;
  67034. var extractDecalVector3 = function (indexId) {
  67035. var result = new BABYLON.PositionNormalVertex();
  67036. if (!indices || !positions || !normals) {
  67037. return result;
  67038. }
  67039. var vertexId = indices[indexId];
  67040. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  67041. // Send vector to decal local world
  67042. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  67043. // Get normal
  67044. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  67045. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  67046. return result;
  67047. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  67048. var clip = function (vertices, axis) {
  67049. if (vertices.length === 0) {
  67050. return vertices;
  67051. }
  67052. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  67053. var clipVertices = function (v0, v1) {
  67054. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  67055. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  67056. };
  67057. var result = new Array();
  67058. for (var index = 0; index < vertices.length; index += 3) {
  67059. var v1Out;
  67060. var v2Out;
  67061. var v3Out;
  67062. var total = 0;
  67063. var nV1 = null;
  67064. var nV2 = null;
  67065. var nV3 = null;
  67066. var nV4 = null;
  67067. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  67068. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  67069. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  67070. v1Out = d1 > 0;
  67071. v2Out = d2 > 0;
  67072. v3Out = d3 > 0;
  67073. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  67074. switch (total) {
  67075. case 0:
  67076. result.push(vertices[index]);
  67077. result.push(vertices[index + 1]);
  67078. result.push(vertices[index + 2]);
  67079. break;
  67080. case 1:
  67081. if (v1Out) {
  67082. nV1 = vertices[index + 1];
  67083. nV2 = vertices[index + 2];
  67084. nV3 = clipVertices(vertices[index], nV1);
  67085. nV4 = clipVertices(vertices[index], nV2);
  67086. }
  67087. if (v2Out) {
  67088. nV1 = vertices[index];
  67089. nV2 = vertices[index + 2];
  67090. nV3 = clipVertices(vertices[index + 1], nV1);
  67091. nV4 = clipVertices(vertices[index + 1], nV2);
  67092. result.push(nV3);
  67093. result.push(nV2.clone());
  67094. result.push(nV1.clone());
  67095. result.push(nV2.clone());
  67096. result.push(nV3.clone());
  67097. result.push(nV4);
  67098. break;
  67099. }
  67100. if (v3Out) {
  67101. nV1 = vertices[index];
  67102. nV2 = vertices[index + 1];
  67103. nV3 = clipVertices(vertices[index + 2], nV1);
  67104. nV4 = clipVertices(vertices[index + 2], nV2);
  67105. }
  67106. if (nV1 && nV2 && nV3 && nV4) {
  67107. result.push(nV1.clone());
  67108. result.push(nV2.clone());
  67109. result.push(nV3);
  67110. result.push(nV4);
  67111. result.push(nV3.clone());
  67112. result.push(nV2.clone());
  67113. }
  67114. break;
  67115. case 2:
  67116. if (!v1Out) {
  67117. nV1 = vertices[index].clone();
  67118. nV2 = clipVertices(nV1, vertices[index + 1]);
  67119. nV3 = clipVertices(nV1, vertices[index + 2]);
  67120. result.push(nV1);
  67121. result.push(nV2);
  67122. result.push(nV3);
  67123. }
  67124. if (!v2Out) {
  67125. nV1 = vertices[index + 1].clone();
  67126. nV2 = clipVertices(nV1, vertices[index + 2]);
  67127. nV3 = clipVertices(nV1, vertices[index]);
  67128. result.push(nV1);
  67129. result.push(nV2);
  67130. result.push(nV3);
  67131. }
  67132. if (!v3Out) {
  67133. nV1 = vertices[index + 2].clone();
  67134. nV2 = clipVertices(nV1, vertices[index]);
  67135. nV3 = clipVertices(nV1, vertices[index + 1]);
  67136. result.push(nV1);
  67137. result.push(nV2);
  67138. result.push(nV3);
  67139. }
  67140. break;
  67141. case 3:
  67142. break;
  67143. }
  67144. }
  67145. return result;
  67146. };
  67147. for (var index = 0; index < indices.length; index += 3) {
  67148. var faceVertices = new Array();
  67149. faceVertices.push(extractDecalVector3(index));
  67150. faceVertices.push(extractDecalVector3(index + 1));
  67151. faceVertices.push(extractDecalVector3(index + 2));
  67152. // Clip
  67153. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  67154. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  67155. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  67156. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  67157. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  67158. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  67159. if (faceVertices.length === 0) {
  67160. continue;
  67161. }
  67162. // Add UVs and get back to world
  67163. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  67164. var vertex = faceVertices[vIndex];
  67165. //TODO check for Int32Array | Uint32Array | Uint16Array
  67166. vertexData.indices.push(currentVertexDataIndex);
  67167. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  67168. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  67169. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  67170. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  67171. currentVertexDataIndex++;
  67172. }
  67173. }
  67174. // Return mesh
  67175. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  67176. vertexData.applyToMesh(decal);
  67177. decal.position = position.clone();
  67178. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  67179. return decal;
  67180. };
  67181. // Privates
  67182. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  67183. // extrusion geometry
  67184. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  67185. var tangents = path3D.getTangents();
  67186. var normals = path3D.getNormals();
  67187. var binormals = path3D.getBinormals();
  67188. var distances = path3D.getDistances();
  67189. var angle = 0;
  67190. var returnScale = function () { return scale !== null ? scale : 1; };
  67191. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  67192. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  67193. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  67194. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  67195. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  67196. for (var i = 0; i < curve.length; i++) {
  67197. var shapePath = new Array();
  67198. var angleStep = rotate(i, distances[i]);
  67199. var scaleRatio = scl(i, distances[i]);
  67200. for (var p = 0; p < shape.length; p++) {
  67201. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  67202. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  67203. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  67204. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  67205. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  67206. shapePath[p] = rotated;
  67207. }
  67208. shapePaths[index] = shapePath;
  67209. angle += angleStep;
  67210. index++;
  67211. }
  67212. // cap
  67213. var capPath = function (shapePath) {
  67214. var pointCap = Array();
  67215. var barycenter = BABYLON.Vector3.Zero();
  67216. var i;
  67217. for (i = 0; i < shapePath.length; i++) {
  67218. barycenter.addInPlace(shapePath[i]);
  67219. }
  67220. barycenter.scaleInPlace(1.0 / shapePath.length);
  67221. for (i = 0; i < shapePath.length; i++) {
  67222. pointCap.push(barycenter);
  67223. }
  67224. return pointCap;
  67225. };
  67226. switch (cap) {
  67227. case BABYLON.Mesh.NO_CAP:
  67228. break;
  67229. case BABYLON.Mesh.CAP_START:
  67230. shapePaths[0] = capPath(shapePaths[2]);
  67231. shapePaths[1] = shapePaths[2];
  67232. break;
  67233. case BABYLON.Mesh.CAP_END:
  67234. shapePaths[index] = shapePaths[index - 1];
  67235. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  67236. break;
  67237. case BABYLON.Mesh.CAP_ALL:
  67238. shapePaths[0] = capPath(shapePaths[2]);
  67239. shapePaths[1] = shapePaths[2];
  67240. shapePaths[index] = shapePaths[index - 1];
  67241. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  67242. break;
  67243. default:
  67244. break;
  67245. }
  67246. return shapePaths;
  67247. };
  67248. var path3D;
  67249. var pathArray;
  67250. if (instance) { // instance update
  67251. path3D = (instance.path3D).update(curve);
  67252. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  67253. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  67254. return instance;
  67255. }
  67256. // extruded shape creation
  67257. path3D = new BABYLON.Path3D(curve);
  67258. var newShapePaths = new Array();
  67259. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67260. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  67261. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  67262. extrudedGeneric.pathArray = pathArray;
  67263. extrudedGeneric.path3D = path3D;
  67264. extrudedGeneric.cap = cap;
  67265. return extrudedGeneric;
  67266. };
  67267. return MeshBuilder;
  67268. }());
  67269. BABYLON.MeshBuilder = MeshBuilder;
  67270. })(BABYLON || (BABYLON = {}));
  67271. //# sourceMappingURL=babylon.meshBuilder.js.map
  67272. var BABYLON;
  67273. (function (BABYLON) {
  67274. /**
  67275. * Draco compression (https://google.github.io/draco/)
  67276. *
  67277. * This class wraps the Draco module.
  67278. *
  67279. * **Encoder**
  67280. *
  67281. * The encoder is not currently implemented.
  67282. *
  67283. * **Decoder**
  67284. *
  67285. * 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.
  67286. *
  67287. * To update the configuration, use the following code:
  67288. * ```javascript
  67289. * BABYLON.DracoCompression.Configuration = {
  67290. * decoder: {
  67291. * wasmUrl: "<url to the WebAssembly library>",
  67292. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  67293. * fallbackUrl: "<url to the fallback JavaScript library>",
  67294. * }
  67295. * };
  67296. * ```
  67297. *
  67298. * 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.
  67299. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  67300. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  67301. *
  67302. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  67303. * ```javascript
  67304. * var dracoCompression = new BABYLON.DracoCompression();
  67305. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  67306. * [BABYLON.VertexBuffer.PositionKind]: 0
  67307. * });
  67308. * ```
  67309. *
  67310. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  67311. */
  67312. var DracoCompression = /** @class */ (function () {
  67313. /**
  67314. * Constructor
  67315. */
  67316. function DracoCompression() {
  67317. }
  67318. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  67319. /**
  67320. * Returns true if the decoder is available.
  67321. */
  67322. get: function () {
  67323. if (typeof DracoDecoderModule !== "undefined") {
  67324. return true;
  67325. }
  67326. var decoder = DracoCompression.Configuration.decoder;
  67327. if (decoder) {
  67328. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67329. return true;
  67330. }
  67331. if (decoder.fallbackUrl) {
  67332. return true;
  67333. }
  67334. }
  67335. return false;
  67336. },
  67337. enumerable: true,
  67338. configurable: true
  67339. });
  67340. /**
  67341. * Stop all async operations and release resources.
  67342. */
  67343. DracoCompression.prototype.dispose = function () {
  67344. };
  67345. /**
  67346. * Decode Draco compressed mesh data to vertex data.
  67347. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  67348. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  67349. * @returns A promise that resolves with the decoded vertex data
  67350. */
  67351. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  67352. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  67353. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  67354. var module = wrappedModule.module;
  67355. var vertexData = new BABYLON.VertexData();
  67356. var buffer = new module.DecoderBuffer();
  67357. buffer.Init(dataView, dataView.byteLength);
  67358. var decoder = new module.Decoder();
  67359. var geometry;
  67360. var status;
  67361. try {
  67362. var type = decoder.GetEncodedGeometryType(buffer);
  67363. switch (type) {
  67364. case module.TRIANGULAR_MESH:
  67365. geometry = new module.Mesh();
  67366. status = decoder.DecodeBufferToMesh(buffer, geometry);
  67367. break;
  67368. case module.POINT_CLOUD:
  67369. geometry = new module.PointCloud();
  67370. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  67371. break;
  67372. default:
  67373. throw new Error("Invalid geometry type " + type);
  67374. }
  67375. if (!status.ok() || !geometry.ptr) {
  67376. throw new Error(status.error_msg());
  67377. }
  67378. var numPoints = geometry.num_points();
  67379. if (type === module.TRIANGULAR_MESH) {
  67380. var numFaces = geometry.num_faces();
  67381. var faceIndices = new module.DracoInt32Array();
  67382. try {
  67383. var indices = new Uint32Array(numFaces * 3);
  67384. for (var i = 0; i < numFaces; i++) {
  67385. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  67386. var offset = i * 3;
  67387. indices[offset + 0] = faceIndices.GetValue(0);
  67388. indices[offset + 1] = faceIndices.GetValue(1);
  67389. indices[offset + 2] = faceIndices.GetValue(2);
  67390. }
  67391. vertexData.indices = indices;
  67392. }
  67393. finally {
  67394. module.destroy(faceIndices);
  67395. }
  67396. }
  67397. for (var kind in attributes) {
  67398. var uniqueId = attributes[kind];
  67399. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  67400. var dracoData = new module.DracoFloat32Array();
  67401. try {
  67402. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  67403. var babylonData = new Float32Array(numPoints * attribute.num_components());
  67404. for (var i = 0; i < babylonData.length; i++) {
  67405. babylonData[i] = dracoData.GetValue(i);
  67406. }
  67407. vertexData.set(babylonData, kind);
  67408. }
  67409. finally {
  67410. module.destroy(dracoData);
  67411. }
  67412. }
  67413. }
  67414. finally {
  67415. if (geometry) {
  67416. module.destroy(geometry);
  67417. }
  67418. module.destroy(decoder);
  67419. module.destroy(buffer);
  67420. }
  67421. return vertexData;
  67422. });
  67423. };
  67424. DracoCompression._GetDecoderModule = function () {
  67425. if (!DracoCompression._DecoderModulePromise) {
  67426. var promise = null;
  67427. var config_1 = {};
  67428. if (typeof DracoDecoderModule !== "undefined") {
  67429. promise = Promise.resolve();
  67430. }
  67431. else {
  67432. var decoder = DracoCompression.Configuration.decoder;
  67433. if (decoder) {
  67434. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67435. promise = Promise.all([
  67436. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  67437. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  67438. config_1.wasmBinary = data;
  67439. })
  67440. ]);
  67441. }
  67442. else if (decoder.fallbackUrl) {
  67443. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  67444. }
  67445. }
  67446. }
  67447. if (!promise) {
  67448. throw new Error("Draco decoder module is not available");
  67449. }
  67450. DracoCompression._DecoderModulePromise = promise.then(function () {
  67451. return new Promise(function (resolve) {
  67452. config_1.onModuleLoaded = function (decoderModule) {
  67453. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  67454. resolve({ module: decoderModule });
  67455. };
  67456. DracoDecoderModule(config_1);
  67457. });
  67458. });
  67459. }
  67460. return DracoCompression._DecoderModulePromise;
  67461. };
  67462. DracoCompression._LoadScriptAsync = function (url) {
  67463. return new Promise(function (resolve, reject) {
  67464. BABYLON.Tools.LoadScript(url, function () {
  67465. resolve();
  67466. }, function (message) {
  67467. reject(new Error(message));
  67468. });
  67469. });
  67470. };
  67471. DracoCompression._LoadFileAsync = function (url) {
  67472. return new Promise(function (resolve, reject) {
  67473. BABYLON.Tools.LoadFile(url, function (data) {
  67474. resolve(data);
  67475. }, undefined, undefined, true, function (request, exception) {
  67476. reject(exception);
  67477. });
  67478. });
  67479. };
  67480. /**
  67481. * The configuration. Defaults to the following urls:
  67482. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  67483. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  67484. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67485. */
  67486. DracoCompression.Configuration = {
  67487. decoder: {
  67488. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  67489. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  67490. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67491. }
  67492. };
  67493. return DracoCompression;
  67494. }());
  67495. BABYLON.DracoCompression = DracoCompression;
  67496. })(BABYLON || (BABYLON = {}));
  67497. //# sourceMappingURL=babylon.dracoCompression.js.map
  67498. var BABYLON;
  67499. (function (BABYLON) {
  67500. // Sets the default audio engine to Babylon JS.
  67501. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  67502. /**
  67503. * This represents the default audio engine used in babylon.
  67504. * It is responsible to play, synchronize and analyse sounds throughout the application.
  67505. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67506. */
  67507. var AudioEngine = /** @class */ (function () {
  67508. /**
  67509. * Instantiates a new audio engine.
  67510. *
  67511. * There should be only one per page as some browsers restrict the number
  67512. * of audio contexts you can create.
  67513. * @param engine defines the hosting engine
  67514. */
  67515. function AudioEngine(engine) {
  67516. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  67517. var _this = this;
  67518. this._audioContext = null;
  67519. this._audioContextInitialized = false;
  67520. this._muteButton = null;
  67521. /**
  67522. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  67523. */
  67524. this.canUseWebAudio = false;
  67525. /**
  67526. * Defines if Babylon should emit a warning if WebAudio is not supported.
  67527. * @ignoreNaming
  67528. */
  67529. this.WarnedWebAudioUnsupported = false;
  67530. /**
  67531. * Gets whether or not mp3 are supported by your browser.
  67532. */
  67533. this.isMP3supported = false;
  67534. /**
  67535. * Gets whether or not ogg are supported by your browser.
  67536. */
  67537. this.isOGGsupported = false;
  67538. /**
  67539. * Gets whether audio has been unlocked on the device.
  67540. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  67541. * a user interaction has happened.
  67542. */
  67543. this.unlocked = true;
  67544. /**
  67545. * Defines if the audio engine relies on a custom unlocked button.
  67546. * In this case, the embedded button will not be displayed.
  67547. */
  67548. this.useCustomUnlockedButton = false;
  67549. /**
  67550. * Event raised when audio has been unlocked on the browser.
  67551. */
  67552. this.onAudioUnlockedObservable = new BABYLON.Observable();
  67553. /**
  67554. * Event raised when audio has been locked on the browser.
  67555. */
  67556. this.onAudioLockedObservable = new BABYLON.Observable();
  67557. this._tryToRun = false;
  67558. this._onResize = function () {
  67559. _this._moveButtonToTopLeft();
  67560. };
  67561. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  67562. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  67563. this.canUseWebAudio = true;
  67564. }
  67565. var audioElem = document.createElement('audio');
  67566. this._engine = engine;
  67567. try {
  67568. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  67569. this.isMP3supported = true;
  67570. }
  67571. }
  67572. catch (e) {
  67573. // protect error during capability check.
  67574. }
  67575. try {
  67576. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  67577. this.isOGGsupported = true;
  67578. }
  67579. }
  67580. catch (e) {
  67581. // protect error during capability check.
  67582. }
  67583. }
  67584. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  67585. /**
  67586. * Gets the current AudioContext if available.
  67587. */
  67588. get: function () {
  67589. if (!this._audioContextInitialized) {
  67590. this._initializeAudioContext();
  67591. }
  67592. else {
  67593. if (!this.unlocked && !this._muteButton) {
  67594. this._displayMuteButton();
  67595. }
  67596. }
  67597. return this._audioContext;
  67598. },
  67599. enumerable: true,
  67600. configurable: true
  67601. });
  67602. /**
  67603. * Flags the audio engine in Locked state.
  67604. * This happens due to new browser policies preventing audio to autoplay.
  67605. */
  67606. AudioEngine.prototype.lock = function () {
  67607. this._triggerSuspendedState();
  67608. };
  67609. /**
  67610. * Unlocks the audio engine once a user action has been done on the dom.
  67611. * This is helpful to resume play once browser policies have been satisfied.
  67612. */
  67613. AudioEngine.prototype.unlock = function () {
  67614. this._triggerRunningState();
  67615. };
  67616. AudioEngine.prototype._resumeAudioContext = function () {
  67617. var result;
  67618. if (this._audioContext.resume) {
  67619. result = this._audioContext.resume();
  67620. }
  67621. return result || Promise.resolve();
  67622. };
  67623. AudioEngine.prototype._initializeAudioContext = function () {
  67624. var _this = this;
  67625. try {
  67626. if (this.canUseWebAudio) {
  67627. this._audioContext = new AudioContext();
  67628. // create a global volume gain node
  67629. this.masterGain = this._audioContext.createGain();
  67630. this.masterGain.gain.value = 1;
  67631. this.masterGain.connect(this._audioContext.destination);
  67632. this._audioContextInitialized = true;
  67633. if (this._audioContext.state === "running") {
  67634. // Do not wait for the promise to unlock.
  67635. this._triggerRunningState();
  67636. }
  67637. else {
  67638. if (this._audioContext && this._audioContext.resume) {
  67639. this._resumeAudioContext().then(function () {
  67640. _this._triggerRunningState();
  67641. }).catch(function () {
  67642. // Can not resume automatically
  67643. // Needs user action
  67644. _this.lock();
  67645. });
  67646. }
  67647. }
  67648. }
  67649. }
  67650. catch (e) {
  67651. this.canUseWebAudio = false;
  67652. BABYLON.Tools.Error("Web Audio: " + e.message);
  67653. }
  67654. };
  67655. AudioEngine.prototype._triggerRunningState = function () {
  67656. var _this = this;
  67657. if (this._tryToRun) {
  67658. return;
  67659. }
  67660. this._tryToRun = true;
  67661. this._resumeAudioContext()
  67662. .then(function () {
  67663. _this._tryToRun = false;
  67664. _this.unlocked = true;
  67665. if (_this._muteButton) {
  67666. _this._hideMuteButton();
  67667. }
  67668. // Notify users that the audio stack is unlocked/unmuted
  67669. _this.onAudioUnlockedObservable.notifyObservers(_this);
  67670. }).catch(function () {
  67671. _this._tryToRun = false;
  67672. _this.unlocked = false;
  67673. });
  67674. };
  67675. AudioEngine.prototype._triggerSuspendedState = function () {
  67676. this.unlocked = false;
  67677. this.onAudioLockedObservable.notifyObservers(this);
  67678. this._displayMuteButton();
  67679. };
  67680. AudioEngine.prototype._displayMuteButton = function () {
  67681. var _this = this;
  67682. if (this.useCustomUnlockedButton) {
  67683. return;
  67684. }
  67685. this._canvas = this._engine.getRenderingCanvas();
  67686. this._muteButton = document.createElement("BUTTON");
  67687. this._muteButton.className = "babylonUnmuteIcon";
  67688. this._muteButton.id = "babylonUnmuteIconBtn";
  67689. this._muteButton.title = "Unmute";
  67690. 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) }";
  67691. var style = document.createElement('style');
  67692. style.appendChild(document.createTextNode(css));
  67693. document.getElementsByTagName('head')[0].appendChild(style);
  67694. document.body.appendChild(this._muteButton);
  67695. this._moveButtonToTopLeft();
  67696. this._muteButton.addEventListener('mousedown', function () {
  67697. _this._triggerRunningState();
  67698. }, true);
  67699. this._muteButton.addEventListener('touchend', function () {
  67700. _this._triggerRunningState();
  67701. }, true);
  67702. this._muteButton.addEventListener('click', function () {
  67703. _this._triggerRunningState();
  67704. }, true);
  67705. window.addEventListener("resize", this._onResize);
  67706. };
  67707. AudioEngine.prototype._moveButtonToTopLeft = function () {
  67708. if (this._canvas && this._muteButton) {
  67709. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  67710. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  67711. }
  67712. };
  67713. AudioEngine.prototype._hideMuteButton = function () {
  67714. if (this._muteButton) {
  67715. document.body.removeChild(this._muteButton);
  67716. this._muteButton = null;
  67717. }
  67718. };
  67719. /**
  67720. * Destroy and release the resources associated with the audio ccontext.
  67721. */
  67722. AudioEngine.prototype.dispose = function () {
  67723. if (this.canUseWebAudio && this._audioContextInitialized) {
  67724. if (this._connectedAnalyser && this._audioContext) {
  67725. this._connectedAnalyser.stopDebugCanvas();
  67726. this._connectedAnalyser.dispose();
  67727. this.masterGain.disconnect();
  67728. this.masterGain.connect(this._audioContext.destination);
  67729. this._connectedAnalyser = null;
  67730. }
  67731. this.masterGain.gain.value = 1;
  67732. }
  67733. this.WarnedWebAudioUnsupported = false;
  67734. this._hideMuteButton();
  67735. window.removeEventListener("resize", this._onResize);
  67736. this.onAudioUnlockedObservable.clear();
  67737. this.onAudioLockedObservable.clear();
  67738. };
  67739. /**
  67740. * Gets the global volume sets on the master gain.
  67741. * @returns the global volume if set or -1 otherwise
  67742. */
  67743. AudioEngine.prototype.getGlobalVolume = function () {
  67744. if (this.canUseWebAudio && this._audioContextInitialized) {
  67745. return this.masterGain.gain.value;
  67746. }
  67747. else {
  67748. return -1;
  67749. }
  67750. };
  67751. /**
  67752. * Sets the global volume of your experience (sets on the master gain).
  67753. * @param newVolume Defines the new global volume of the application
  67754. */
  67755. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  67756. if (this.canUseWebAudio && this._audioContextInitialized) {
  67757. this.masterGain.gain.value = newVolume;
  67758. }
  67759. };
  67760. /**
  67761. * Connect the audio engine to an audio analyser allowing some amazing
  67762. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  67763. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  67764. * @param analyser The analyser to connect to the engine
  67765. */
  67766. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  67767. if (this._connectedAnalyser) {
  67768. this._connectedAnalyser.stopDebugCanvas();
  67769. }
  67770. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  67771. this._connectedAnalyser = analyser;
  67772. this.masterGain.disconnect();
  67773. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  67774. }
  67775. };
  67776. return AudioEngine;
  67777. }());
  67778. BABYLON.AudioEngine = AudioEngine;
  67779. })(BABYLON || (BABYLON = {}));
  67780. //# sourceMappingURL=babylon.audioEngine.js.map
  67781. var BABYLON;
  67782. (function (BABYLON) {
  67783. /**
  67784. * Defines a sound that can be played in the application.
  67785. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  67786. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67787. */
  67788. var Sound = /** @class */ (function () {
  67789. /**
  67790. * Create a sound and attach it to a scene
  67791. * @param name Name of your sound
  67792. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  67793. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  67794. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  67795. */
  67796. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  67797. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  67798. var _this = this;
  67799. /**
  67800. * Does the sound autoplay once loaded.
  67801. */
  67802. this.autoplay = false;
  67803. /**
  67804. * Does the sound loop after it finishes playing once.
  67805. */
  67806. this.loop = false;
  67807. /**
  67808. * Does the sound use a custom attenuation curve to simulate the falloff
  67809. * happening when the source gets further away from the camera.
  67810. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67811. */
  67812. this.useCustomAttenuation = false;
  67813. /**
  67814. * Is this sound currently played.
  67815. */
  67816. this.isPlaying = false;
  67817. /**
  67818. * Is this sound currently paused.
  67819. */
  67820. this.isPaused = false;
  67821. /**
  67822. * Does this sound enables spatial sound.
  67823. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67824. */
  67825. this.spatialSound = false;
  67826. /**
  67827. * Define the reference distance the sound should be heard perfectly.
  67828. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67829. */
  67830. this.refDistance = 1;
  67831. /**
  67832. * Define the roll off factor of spatial sounds.
  67833. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67834. */
  67835. this.rolloffFactor = 1;
  67836. /**
  67837. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  67838. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67839. */
  67840. this.maxDistance = 100;
  67841. /**
  67842. * Define the distance attenuation model the sound will follow.
  67843. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67844. */
  67845. this.distanceModel = "linear";
  67846. /**
  67847. * Observable event when the current playing sound finishes.
  67848. */
  67849. this.onEndedObservable = new BABYLON.Observable();
  67850. this._panningModel = "equalpower";
  67851. this._playbackRate = 1;
  67852. this._streaming = false;
  67853. this._startTime = 0;
  67854. this._startOffset = 0;
  67855. this._position = BABYLON.Vector3.Zero();
  67856. /** @hidden */
  67857. this._positionInEmitterSpace = false;
  67858. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  67859. this._volume = 1;
  67860. this._isReadyToPlay = false;
  67861. this._isDirectional = false;
  67862. // Used if you'd like to create a directional sound.
  67863. // If not set, the sound will be omnidirectional
  67864. this._coneInnerAngle = 360;
  67865. this._coneOuterAngle = 360;
  67866. this._coneOuterGain = 0;
  67867. this._isOutputConnected = false;
  67868. this._urlType = "Unknown";
  67869. this.name = name;
  67870. this._scene = scene;
  67871. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67872. if (!compo) {
  67873. compo = new BABYLON.AudioSceneComponent(scene);
  67874. scene._addComponent(compo);
  67875. }
  67876. this._readyToPlayCallback = readyToPlayCallback;
  67877. // Default custom attenuation function is a linear attenuation
  67878. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  67879. if (currentDistance < maxDistance) {
  67880. return currentVolume * (1 - currentDistance / maxDistance);
  67881. }
  67882. else {
  67883. return 0;
  67884. }
  67885. };
  67886. if (options) {
  67887. this.autoplay = options.autoplay || false;
  67888. this.loop = options.loop || false;
  67889. // if volume === 0, we need another way to check this option
  67890. if (options.volume !== undefined) {
  67891. this._volume = options.volume;
  67892. }
  67893. this.spatialSound = options.spatialSound || false;
  67894. this.maxDistance = options.maxDistance || 100;
  67895. this.useCustomAttenuation = options.useCustomAttenuation || false;
  67896. this.rolloffFactor = options.rolloffFactor || 1;
  67897. this.refDistance = options.refDistance || 1;
  67898. this.distanceModel = options.distanceModel || "linear";
  67899. this._playbackRate = options.playbackRate || 1;
  67900. this._streaming = options.streaming || false;
  67901. }
  67902. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67903. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67904. this._soundGain.gain.value = this._volume;
  67905. this._inputAudioNode = this._soundGain;
  67906. this._outputAudioNode = this._soundGain;
  67907. if (this.spatialSound) {
  67908. this._createSpatialParameters();
  67909. }
  67910. this._scene.mainSoundTrack.AddSound(this);
  67911. var validParameter = true;
  67912. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  67913. if (urlOrArrayBuffer) {
  67914. try {
  67915. if (typeof (urlOrArrayBuffer) === "string") {
  67916. this._urlType = "String";
  67917. }
  67918. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  67919. this._urlType = "ArrayBuffer";
  67920. }
  67921. else if (urlOrArrayBuffer instanceof MediaStream) {
  67922. this._urlType = "MediaStream";
  67923. }
  67924. else if (Array.isArray(urlOrArrayBuffer)) {
  67925. this._urlType = "Array";
  67926. }
  67927. var urls = [];
  67928. var codecSupportedFound = false;
  67929. switch (this._urlType) {
  67930. case "MediaStream":
  67931. this._streaming = true;
  67932. this._isReadyToPlay = true;
  67933. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  67934. if (this.autoplay) {
  67935. this.play();
  67936. }
  67937. if (this._readyToPlayCallback) {
  67938. this._readyToPlayCallback();
  67939. }
  67940. break;
  67941. case "ArrayBuffer":
  67942. if (urlOrArrayBuffer.byteLength > 0) {
  67943. codecSupportedFound = true;
  67944. this._soundLoaded(urlOrArrayBuffer);
  67945. }
  67946. break;
  67947. case "String":
  67948. urls.push(urlOrArrayBuffer);
  67949. case "Array":
  67950. if (urls.length === 0)
  67951. urls = urlOrArrayBuffer;
  67952. // If we found a supported format, we load it immediately and stop the loop
  67953. for (var i = 0; i < urls.length; i++) {
  67954. var url = urls[i];
  67955. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  67956. codecSupportedFound = true;
  67957. }
  67958. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  67959. codecSupportedFound = true;
  67960. }
  67961. if (url.indexOf(".wav", url.length - 4) !== -1) {
  67962. codecSupportedFound = true;
  67963. }
  67964. if (url.indexOf("blob:") !== -1) {
  67965. codecSupportedFound = true;
  67966. }
  67967. if (codecSupportedFound) {
  67968. // Loading sound using XHR2
  67969. if (!this._streaming) {
  67970. this._scene._loadFile(url, function (data) {
  67971. _this._soundLoaded(data);
  67972. }, undefined, true, true, function (exception) {
  67973. if (exception) {
  67974. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  67975. }
  67976. BABYLON.Tools.Error("Sound creation aborted.");
  67977. _this._scene.mainSoundTrack.RemoveSound(_this);
  67978. });
  67979. }
  67980. // Streaming sound using HTML5 Audio tag
  67981. else {
  67982. this._htmlAudioElement = new Audio(url);
  67983. this._htmlAudioElement.controls = false;
  67984. this._htmlAudioElement.loop = this.loop;
  67985. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  67986. this._htmlAudioElement.preload = "auto";
  67987. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  67988. _this._isReadyToPlay = true;
  67989. if (_this.autoplay) {
  67990. _this.play();
  67991. }
  67992. if (_this._readyToPlayCallback) {
  67993. _this._readyToPlayCallback();
  67994. }
  67995. });
  67996. document.body.appendChild(this._htmlAudioElement);
  67997. this._htmlAudioElement.load();
  67998. }
  67999. break;
  68000. }
  68001. }
  68002. break;
  68003. default:
  68004. validParameter = false;
  68005. break;
  68006. }
  68007. if (!validParameter) {
  68008. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  68009. }
  68010. else {
  68011. if (!codecSupportedFound) {
  68012. this._isReadyToPlay = true;
  68013. // Simulating a ready to play event to avoid breaking code path
  68014. if (this._readyToPlayCallback) {
  68015. window.setTimeout(function () {
  68016. if (_this._readyToPlayCallback) {
  68017. _this._readyToPlayCallback();
  68018. }
  68019. }, 1000);
  68020. }
  68021. }
  68022. }
  68023. }
  68024. catch (ex) {
  68025. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  68026. this._scene.mainSoundTrack.RemoveSound(this);
  68027. }
  68028. }
  68029. }
  68030. else {
  68031. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  68032. this._scene.mainSoundTrack.AddSound(this);
  68033. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  68034. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  68035. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  68036. }
  68037. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  68038. if (this._readyToPlayCallback) {
  68039. window.setTimeout(function () {
  68040. if (_this._readyToPlayCallback) {
  68041. _this._readyToPlayCallback();
  68042. }
  68043. }, 1000);
  68044. }
  68045. }
  68046. }
  68047. /**
  68048. * Release the sound and its associated resources
  68049. */
  68050. Sound.prototype.dispose = function () {
  68051. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68052. if (this.isPlaying) {
  68053. this.stop();
  68054. }
  68055. this._isReadyToPlay = false;
  68056. if (this.soundTrackId === -1) {
  68057. this._scene.mainSoundTrack.RemoveSound(this);
  68058. }
  68059. else if (this._scene.soundTracks) {
  68060. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  68061. }
  68062. if (this._soundGain) {
  68063. this._soundGain.disconnect();
  68064. this._soundGain = null;
  68065. }
  68066. if (this._soundPanner) {
  68067. this._soundPanner.disconnect();
  68068. this._soundPanner = null;
  68069. }
  68070. if (this._soundSource) {
  68071. this._soundSource.disconnect();
  68072. this._soundSource = null;
  68073. }
  68074. this._audioBuffer = null;
  68075. if (this._htmlAudioElement) {
  68076. this._htmlAudioElement.pause();
  68077. this._htmlAudioElement.src = "";
  68078. document.body.removeChild(this._htmlAudioElement);
  68079. }
  68080. if (this._streamingSource) {
  68081. this._streamingSource.disconnect();
  68082. }
  68083. if (this._connectedMesh && this._registerFunc) {
  68084. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68085. this._connectedMesh = null;
  68086. }
  68087. }
  68088. };
  68089. /**
  68090. * Gets if the sounds is ready to be played or not.
  68091. * @returns true if ready, otherwise false
  68092. */
  68093. Sound.prototype.isReady = function () {
  68094. return this._isReadyToPlay;
  68095. };
  68096. Sound.prototype._soundLoaded = function (audioData) {
  68097. var _this = this;
  68098. if (!BABYLON.Engine.audioEngine.audioContext) {
  68099. return;
  68100. }
  68101. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  68102. _this._audioBuffer = buffer;
  68103. _this._isReadyToPlay = true;
  68104. if (_this.autoplay) {
  68105. _this.play();
  68106. }
  68107. if (_this._readyToPlayCallback) {
  68108. _this._readyToPlayCallback();
  68109. }
  68110. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  68111. };
  68112. /**
  68113. * Sets the data of the sound from an audiobuffer
  68114. * @param audioBuffer The audioBuffer containing the data
  68115. */
  68116. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  68117. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68118. this._audioBuffer = audioBuffer;
  68119. this._isReadyToPlay = true;
  68120. }
  68121. };
  68122. /**
  68123. * Updates the current sounds options such as maxdistance, loop...
  68124. * @param options A JSON object containing values named as the object properties
  68125. */
  68126. Sound.prototype.updateOptions = function (options) {
  68127. if (options) {
  68128. this.loop = options.loop || this.loop;
  68129. this.maxDistance = options.maxDistance || this.maxDistance;
  68130. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  68131. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  68132. this.refDistance = options.refDistance || this.refDistance;
  68133. this.distanceModel = options.distanceModel || this.distanceModel;
  68134. this._playbackRate = options.playbackRate || this._playbackRate;
  68135. this._updateSpatialParameters();
  68136. if (this.isPlaying) {
  68137. if (this._streaming && this._htmlAudioElement) {
  68138. this._htmlAudioElement.playbackRate = this._playbackRate;
  68139. }
  68140. else {
  68141. if (this._soundSource) {
  68142. this._soundSource.playbackRate.value = this._playbackRate;
  68143. }
  68144. }
  68145. }
  68146. }
  68147. };
  68148. Sound.prototype._createSpatialParameters = function () {
  68149. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68150. if (this._scene.headphone) {
  68151. this._panningModel = "HRTF";
  68152. }
  68153. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  68154. this._updateSpatialParameters();
  68155. this._soundPanner.connect(this._outputAudioNode);
  68156. this._inputAudioNode = this._soundPanner;
  68157. }
  68158. };
  68159. Sound.prototype._updateSpatialParameters = function () {
  68160. if (this.spatialSound && this._soundPanner) {
  68161. if (this.useCustomAttenuation) {
  68162. // Tricks to disable in a way embedded Web Audio attenuation
  68163. this._soundPanner.distanceModel = "linear";
  68164. this._soundPanner.maxDistance = Number.MAX_VALUE;
  68165. this._soundPanner.refDistance = 1;
  68166. this._soundPanner.rolloffFactor = 1;
  68167. this._soundPanner.panningModel = this._panningModel;
  68168. }
  68169. else {
  68170. this._soundPanner.distanceModel = this.distanceModel;
  68171. this._soundPanner.maxDistance = this.maxDistance;
  68172. this._soundPanner.refDistance = this.refDistance;
  68173. this._soundPanner.rolloffFactor = this.rolloffFactor;
  68174. this._soundPanner.panningModel = this._panningModel;
  68175. }
  68176. }
  68177. };
  68178. /**
  68179. * Switch the panning model to HRTF:
  68180. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68181. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68182. */
  68183. Sound.prototype.switchPanningModelToHRTF = function () {
  68184. this._panningModel = "HRTF";
  68185. this._switchPanningModel();
  68186. };
  68187. /**
  68188. * Switch the panning model to Equal Power:
  68189. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68190. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68191. */
  68192. Sound.prototype.switchPanningModelToEqualPower = function () {
  68193. this._panningModel = "equalpower";
  68194. this._switchPanningModel();
  68195. };
  68196. Sound.prototype._switchPanningModel = function () {
  68197. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68198. this._soundPanner.panningModel = this._panningModel;
  68199. }
  68200. };
  68201. /**
  68202. * Connect this sound to a sound track audio node like gain...
  68203. * @param soundTrackAudioNode the sound track audio node to connect to
  68204. */
  68205. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  68206. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68207. if (this._isOutputConnected) {
  68208. this._outputAudioNode.disconnect();
  68209. }
  68210. this._outputAudioNode.connect(soundTrackAudioNode);
  68211. this._isOutputConnected = true;
  68212. }
  68213. };
  68214. /**
  68215. * Transform this sound into a directional source
  68216. * @param coneInnerAngle Size of the inner cone in degree
  68217. * @param coneOuterAngle Size of the outer cone in degree
  68218. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  68219. */
  68220. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  68221. if (coneOuterAngle < coneInnerAngle) {
  68222. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  68223. return;
  68224. }
  68225. this._coneInnerAngle = coneInnerAngle;
  68226. this._coneOuterAngle = coneOuterAngle;
  68227. this._coneOuterGain = coneOuterGain;
  68228. this._isDirectional = true;
  68229. if (this.isPlaying && this.loop) {
  68230. this.stop();
  68231. this.play();
  68232. }
  68233. };
  68234. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  68235. /**
  68236. * Gets or sets the inner angle for the directional cone.
  68237. */
  68238. get: function () {
  68239. return this._coneInnerAngle;
  68240. },
  68241. /**
  68242. * Gets or sets the inner angle for the directional cone.
  68243. */
  68244. set: function (value) {
  68245. if (value != this._coneInnerAngle) {
  68246. if (this._coneOuterAngle < value) {
  68247. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68248. return;
  68249. }
  68250. this._coneInnerAngle = value;
  68251. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68252. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68253. }
  68254. }
  68255. },
  68256. enumerable: true,
  68257. configurable: true
  68258. });
  68259. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  68260. /**
  68261. * Gets or sets the outer angle for the directional cone.
  68262. */
  68263. get: function () {
  68264. return this._coneOuterAngle;
  68265. },
  68266. /**
  68267. * Gets or sets the outer angle for the directional cone.
  68268. */
  68269. set: function (value) {
  68270. if (value != this._coneOuterAngle) {
  68271. if (value < this._coneInnerAngle) {
  68272. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68273. return;
  68274. }
  68275. this._coneOuterAngle = value;
  68276. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68277. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68278. }
  68279. }
  68280. },
  68281. enumerable: true,
  68282. configurable: true
  68283. });
  68284. /**
  68285. * Sets the position of the emitter if spatial sound is enabled
  68286. * @param newPosition Defines the new posisiton
  68287. */
  68288. Sound.prototype.setPosition = function (newPosition) {
  68289. this._position = newPosition;
  68290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68291. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68292. }
  68293. };
  68294. /**
  68295. * Sets the local direction of the emitter if spatial sound is enabled
  68296. * @param newLocalDirection Defines the new local direction
  68297. */
  68298. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  68299. this._localDirection = newLocalDirection;
  68300. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  68301. this._updateDirection();
  68302. }
  68303. };
  68304. Sound.prototype._updateDirection = function () {
  68305. if (!this._connectedMesh || !this._soundPanner) {
  68306. return;
  68307. }
  68308. var mat = this._connectedMesh.getWorldMatrix();
  68309. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  68310. direction.normalize();
  68311. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  68312. };
  68313. /** @hidden */
  68314. Sound.prototype.updateDistanceFromListener = function () {
  68315. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  68316. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  68317. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  68318. }
  68319. };
  68320. /**
  68321. * Sets a new custom attenuation function for the sound.
  68322. * @param callback Defines the function used for the attenuation
  68323. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68324. */
  68325. Sound.prototype.setAttenuationFunction = function (callback) {
  68326. this._customAttenuationFunction = callback;
  68327. };
  68328. /**
  68329. * Play the sound
  68330. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  68331. * @param offset (optional) Start the sound setting it at a specific time
  68332. */
  68333. Sound.prototype.play = function (time, offset) {
  68334. var _this = this;
  68335. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  68336. try {
  68337. if (this._startOffset < 0) {
  68338. time = -this._startOffset;
  68339. this._startOffset = 0;
  68340. }
  68341. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68342. if (!this._soundSource || !this._streamingSource) {
  68343. if (this.spatialSound && this._soundPanner) {
  68344. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68345. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68346. }
  68347. if (this._isDirectional) {
  68348. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68349. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68350. this._soundPanner.coneOuterGain = this._coneOuterGain;
  68351. if (this._connectedMesh) {
  68352. this._updateDirection();
  68353. }
  68354. else {
  68355. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  68356. }
  68357. }
  68358. }
  68359. }
  68360. if (this._streaming) {
  68361. if (!this._streamingSource) {
  68362. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  68363. this._htmlAudioElement.onended = function () { _this._onended(); };
  68364. this._htmlAudioElement.playbackRate = this._playbackRate;
  68365. }
  68366. this._streamingSource.disconnect();
  68367. this._streamingSource.connect(this._inputAudioNode);
  68368. if (this._htmlAudioElement) {
  68369. // required to manage properly the new suspended default state of Chrome
  68370. // When the option 'streaming: true' is used, we need first to wait for
  68371. // the audio engine to be unlocked by a user gesture before trying to play
  68372. // an HTML Audio elememt
  68373. var tryToPlay = function () {
  68374. if (BABYLON.Engine.audioEngine.unlocked) {
  68375. var playPromise = _this._htmlAudioElement.play();
  68376. // In browsers that don’t yet support this functionality,
  68377. // playPromise won’t be defined.
  68378. if (playPromise !== undefined) {
  68379. playPromise.catch(function (error) {
  68380. // Automatic playback failed.
  68381. // Waiting for the audio engine to be unlocked by user click on unmute
  68382. BABYLON.Engine.audioEngine.lock();
  68383. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68384. });
  68385. }
  68386. }
  68387. else {
  68388. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68389. }
  68390. };
  68391. tryToPlay();
  68392. }
  68393. }
  68394. else {
  68395. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  68396. this._soundSource.buffer = this._audioBuffer;
  68397. this._soundSource.connect(this._inputAudioNode);
  68398. this._soundSource.loop = this.loop;
  68399. this._soundSource.playbackRate.value = this._playbackRate;
  68400. this._soundSource.onended = function () { _this._onended(); };
  68401. if (this._soundSource.buffer) {
  68402. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  68403. }
  68404. }
  68405. this._startTime = startTime;
  68406. this.isPlaying = true;
  68407. this.isPaused = false;
  68408. }
  68409. catch (ex) {
  68410. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  68411. }
  68412. }
  68413. };
  68414. Sound.prototype._onended = function () {
  68415. this.isPlaying = false;
  68416. if (this.onended) {
  68417. this.onended();
  68418. }
  68419. this.onEndedObservable.notifyObservers(this);
  68420. };
  68421. /**
  68422. * Stop the sound
  68423. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  68424. */
  68425. Sound.prototype.stop = function (time) {
  68426. if (this.isPlaying) {
  68427. if (this._streaming) {
  68428. if (this._htmlAudioElement) {
  68429. this._htmlAudioElement.pause();
  68430. // Test needed for Firefox or it will generate an Invalid State Error
  68431. if (this._htmlAudioElement.currentTime > 0) {
  68432. this._htmlAudioElement.currentTime = 0;
  68433. }
  68434. }
  68435. else {
  68436. this._streamingSource.disconnect();
  68437. }
  68438. }
  68439. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  68440. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68441. this._soundSource.stop(stopTime);
  68442. this._soundSource.onended = function () { };
  68443. if (!this.isPaused) {
  68444. this._startOffset = 0;
  68445. }
  68446. }
  68447. this.isPlaying = false;
  68448. }
  68449. };
  68450. /**
  68451. * Put the sound in pause
  68452. */
  68453. Sound.prototype.pause = function () {
  68454. if (this.isPlaying) {
  68455. this.isPaused = true;
  68456. if (this._streaming) {
  68457. if (this._htmlAudioElement) {
  68458. this._htmlAudioElement.pause();
  68459. }
  68460. else {
  68461. this._streamingSource.disconnect();
  68462. }
  68463. }
  68464. else if (BABYLON.Engine.audioEngine.audioContext) {
  68465. this.stop(0);
  68466. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  68467. }
  68468. }
  68469. };
  68470. /**
  68471. * Sets a dedicated volume for this sounds
  68472. * @param newVolume Define the new volume of the sound
  68473. * @param time Define in how long the sound should be at this value
  68474. */
  68475. Sound.prototype.setVolume = function (newVolume, time) {
  68476. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  68477. if (time && BABYLON.Engine.audioEngine.audioContext) {
  68478. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  68479. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  68480. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  68481. }
  68482. else {
  68483. this._soundGain.gain.value = newVolume;
  68484. }
  68485. }
  68486. this._volume = newVolume;
  68487. };
  68488. /**
  68489. * Set the sound play back rate
  68490. * @param newPlaybackRate Define the playback rate the sound should be played at
  68491. */
  68492. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  68493. this._playbackRate = newPlaybackRate;
  68494. if (this.isPlaying) {
  68495. if (this._streaming && this._htmlAudioElement) {
  68496. this._htmlAudioElement.playbackRate = this._playbackRate;
  68497. }
  68498. else if (this._soundSource) {
  68499. this._soundSource.playbackRate.value = this._playbackRate;
  68500. }
  68501. }
  68502. };
  68503. /**
  68504. * Gets the volume of the sound.
  68505. * @returns the volume of the sound
  68506. */
  68507. Sound.prototype.getVolume = function () {
  68508. return this._volume;
  68509. };
  68510. /**
  68511. * Attach the sound to a dedicated mesh
  68512. * @param meshToConnectTo The mesh to connect the sound with
  68513. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68514. */
  68515. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  68516. var _this = this;
  68517. if (this._connectedMesh && this._registerFunc) {
  68518. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68519. this._registerFunc = null;
  68520. }
  68521. this._connectedMesh = meshToConnectTo;
  68522. if (!this.spatialSound) {
  68523. this.spatialSound = true;
  68524. this._createSpatialParameters();
  68525. if (this.isPlaying && this.loop) {
  68526. this.stop();
  68527. this.play();
  68528. }
  68529. }
  68530. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  68531. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  68532. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  68533. };
  68534. /**
  68535. * Detach the sound from the previously attached mesh
  68536. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68537. */
  68538. Sound.prototype.detachFromMesh = function () {
  68539. if (this._connectedMesh && this._registerFunc) {
  68540. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68541. this._registerFunc = null;
  68542. this._connectedMesh = null;
  68543. }
  68544. };
  68545. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  68546. if (!node.getBoundingInfo) {
  68547. return;
  68548. }
  68549. var mesh = node;
  68550. if (this._positionInEmitterSpace) {
  68551. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  68552. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  68553. }
  68554. else {
  68555. var boundingInfo = mesh.getBoundingInfo();
  68556. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  68557. }
  68558. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  68559. this._updateDirection();
  68560. }
  68561. };
  68562. /**
  68563. * Clone the current sound in the scene.
  68564. * @returns the new sound clone
  68565. */
  68566. Sound.prototype.clone = function () {
  68567. var _this = this;
  68568. if (!this._streaming) {
  68569. var setBufferAndRun = function () {
  68570. if (_this._isReadyToPlay) {
  68571. clonedSound._audioBuffer = _this.getAudioBuffer();
  68572. clonedSound._isReadyToPlay = true;
  68573. if (clonedSound.autoplay) {
  68574. clonedSound.play();
  68575. }
  68576. }
  68577. else {
  68578. window.setTimeout(setBufferAndRun, 300);
  68579. }
  68580. };
  68581. var currentOptions = {
  68582. autoplay: this.autoplay, loop: this.loop,
  68583. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  68584. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  68585. refDistance: this.refDistance, distanceModel: this.distanceModel
  68586. };
  68587. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  68588. if (this.useCustomAttenuation) {
  68589. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  68590. }
  68591. clonedSound.setPosition(this._position);
  68592. clonedSound.setPlaybackRate(this._playbackRate);
  68593. setBufferAndRun();
  68594. return clonedSound;
  68595. }
  68596. // Can't clone a streaming sound
  68597. else {
  68598. return null;
  68599. }
  68600. };
  68601. /**
  68602. * Gets the current underlying audio buffer containing the data
  68603. * @returns the audio buffer
  68604. */
  68605. Sound.prototype.getAudioBuffer = function () {
  68606. return this._audioBuffer;
  68607. };
  68608. /**
  68609. * Serializes the Sound in a JSON representation
  68610. * @returns the JSON representation of the sound
  68611. */
  68612. Sound.prototype.serialize = function () {
  68613. var serializationObject = {
  68614. name: this.name,
  68615. url: this.name,
  68616. autoplay: this.autoplay,
  68617. loop: this.loop,
  68618. volume: this._volume,
  68619. spatialSound: this.spatialSound,
  68620. maxDistance: this.maxDistance,
  68621. rolloffFactor: this.rolloffFactor,
  68622. refDistance: this.refDistance,
  68623. distanceModel: this.distanceModel,
  68624. playbackRate: this._playbackRate,
  68625. panningModel: this._panningModel,
  68626. soundTrackId: this.soundTrackId
  68627. };
  68628. if (this.spatialSound) {
  68629. if (this._connectedMesh)
  68630. serializationObject.connectedMeshId = this._connectedMesh.id;
  68631. serializationObject.position = this._position.asArray();
  68632. serializationObject.refDistance = this.refDistance;
  68633. serializationObject.distanceModel = this.distanceModel;
  68634. serializationObject.isDirectional = this._isDirectional;
  68635. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  68636. serializationObject.coneInnerAngle = this._coneInnerAngle;
  68637. serializationObject.coneOuterAngle = this._coneOuterAngle;
  68638. serializationObject.coneOuterGain = this._coneOuterGain;
  68639. }
  68640. return serializationObject;
  68641. };
  68642. /**
  68643. * Parse a JSON representation of a sound to innstantiate in a given scene
  68644. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  68645. * @param scene Define the scene the new parsed sound should be created in
  68646. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  68647. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  68648. * @returns the newly parsed sound
  68649. */
  68650. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  68651. var soundName = parsedSound.name;
  68652. var soundUrl;
  68653. if (parsedSound.url) {
  68654. soundUrl = rootUrl + parsedSound.url;
  68655. }
  68656. else {
  68657. soundUrl = rootUrl + soundName;
  68658. }
  68659. var options = {
  68660. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  68661. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  68662. rolloffFactor: parsedSound.rolloffFactor,
  68663. refDistance: parsedSound.refDistance,
  68664. distanceModel: parsedSound.distanceModel,
  68665. playbackRate: parsedSound.playbackRate
  68666. };
  68667. var newSound;
  68668. if (!sourceSound) {
  68669. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  68670. scene._addPendingData(newSound);
  68671. }
  68672. else {
  68673. var setBufferAndRun = function () {
  68674. if (sourceSound._isReadyToPlay) {
  68675. newSound._audioBuffer = sourceSound.getAudioBuffer();
  68676. newSound._isReadyToPlay = true;
  68677. if (newSound.autoplay) {
  68678. newSound.play();
  68679. }
  68680. }
  68681. else {
  68682. window.setTimeout(setBufferAndRun, 300);
  68683. }
  68684. };
  68685. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  68686. setBufferAndRun();
  68687. }
  68688. if (parsedSound.position) {
  68689. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  68690. newSound.setPosition(soundPosition);
  68691. }
  68692. if (parsedSound.isDirectional) {
  68693. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  68694. if (parsedSound.localDirectionToMesh) {
  68695. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  68696. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  68697. }
  68698. }
  68699. if (parsedSound.connectedMeshId) {
  68700. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  68701. if (connectedMesh) {
  68702. newSound.attachToMesh(connectedMesh);
  68703. }
  68704. }
  68705. return newSound;
  68706. };
  68707. return Sound;
  68708. }());
  68709. BABYLON.Sound = Sound;
  68710. })(BABYLON || (BABYLON = {}));
  68711. //# sourceMappingURL=babylon.sound.js.map
  68712. var BABYLON;
  68713. (function (BABYLON) {
  68714. /**
  68715. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  68716. * It will be also used in a future release to apply effects on a specific track.
  68717. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68718. */
  68719. var SoundTrack = /** @class */ (function () {
  68720. /**
  68721. * Creates a new sound track.
  68722. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68723. * @param scene Define the scene the sound track belongs to
  68724. * @param options
  68725. */
  68726. function SoundTrack(scene, options) {
  68727. if (options === void 0) { options = {}; }
  68728. /**
  68729. * The unique identifier of the sound track in the scene.
  68730. */
  68731. this.id = -1;
  68732. this._isMainTrack = false;
  68733. this._isInitialized = false;
  68734. this._scene = scene;
  68735. this.soundCollection = new Array();
  68736. this._options = options;
  68737. if (!this._isMainTrack && this._scene.soundTracks) {
  68738. this._scene.soundTracks.push(this);
  68739. this.id = this._scene.soundTracks.length - 1;
  68740. }
  68741. }
  68742. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  68743. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68744. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  68745. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  68746. if (this._options) {
  68747. if (this._options.volume) {
  68748. this._outputAudioNode.gain.value = this._options.volume;
  68749. }
  68750. if (this._options.mainTrack) {
  68751. this._isMainTrack = this._options.mainTrack;
  68752. }
  68753. }
  68754. this._isInitialized = true;
  68755. }
  68756. };
  68757. /**
  68758. * Release the sound track and its associated resources
  68759. */
  68760. SoundTrack.prototype.dispose = function () {
  68761. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  68762. if (this._connectedAnalyser) {
  68763. this._connectedAnalyser.stopDebugCanvas();
  68764. }
  68765. while (this.soundCollection.length) {
  68766. this.soundCollection[0].dispose();
  68767. }
  68768. if (this._outputAudioNode) {
  68769. this._outputAudioNode.disconnect();
  68770. }
  68771. this._outputAudioNode = null;
  68772. }
  68773. };
  68774. /**
  68775. * Adds a sound to this sound track
  68776. * @param sound define the cound to add
  68777. * @ignoreNaming
  68778. */
  68779. SoundTrack.prototype.AddSound = function (sound) {
  68780. if (!this._isInitialized) {
  68781. this._initializeSoundTrackAudioGraph();
  68782. }
  68783. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68784. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  68785. }
  68786. if (sound.soundTrackId) {
  68787. if (sound.soundTrackId === -1) {
  68788. this._scene.mainSoundTrack.RemoveSound(sound);
  68789. }
  68790. else if (this._scene.soundTracks) {
  68791. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  68792. }
  68793. }
  68794. this.soundCollection.push(sound);
  68795. sound.soundTrackId = this.id;
  68796. };
  68797. /**
  68798. * Removes a sound to this sound track
  68799. * @param sound define the cound to remove
  68800. * @ignoreNaming
  68801. */
  68802. SoundTrack.prototype.RemoveSound = function (sound) {
  68803. var index = this.soundCollection.indexOf(sound);
  68804. if (index !== -1) {
  68805. this.soundCollection.splice(index, 1);
  68806. }
  68807. };
  68808. /**
  68809. * Set a global volume for the full sound track.
  68810. * @param newVolume Define the new volume of the sound track
  68811. */
  68812. SoundTrack.prototype.setVolume = function (newVolume) {
  68813. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68814. this._outputAudioNode.gain.value = newVolume;
  68815. }
  68816. };
  68817. /**
  68818. * Switch the panning model to HRTF:
  68819. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68820. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68821. */
  68822. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  68823. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68824. for (var i = 0; i < this.soundCollection.length; i++) {
  68825. this.soundCollection[i].switchPanningModelToHRTF();
  68826. }
  68827. }
  68828. };
  68829. /**
  68830. * Switch the panning model to Equal Power:
  68831. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68832. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68833. */
  68834. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  68835. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68836. for (var i = 0; i < this.soundCollection.length; i++) {
  68837. this.soundCollection[i].switchPanningModelToEqualPower();
  68838. }
  68839. }
  68840. };
  68841. /**
  68842. * Connect the sound track to an audio analyser allowing some amazing
  68843. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68844. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68845. * @param analyser The analyser to connect to the engine
  68846. */
  68847. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  68848. if (this._connectedAnalyser) {
  68849. this._connectedAnalyser.stopDebugCanvas();
  68850. }
  68851. this._connectedAnalyser = analyser;
  68852. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68853. this._outputAudioNode.disconnect();
  68854. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  68855. }
  68856. };
  68857. return SoundTrack;
  68858. }());
  68859. BABYLON.SoundTrack = SoundTrack;
  68860. })(BABYLON || (BABYLON = {}));
  68861. //# sourceMappingURL=babylon.soundtrack.js.map
  68862. var BABYLON;
  68863. (function (BABYLON) {
  68864. /**
  68865. * Class used to work with sound analyzer using fast fourier transform (FFT)
  68866. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68867. */
  68868. var Analyser = /** @class */ (function () {
  68869. /**
  68870. * Creates a new analyser
  68871. * @param scene defines hosting scene
  68872. */
  68873. function Analyser(scene) {
  68874. /**
  68875. * Gets or sets the smoothing
  68876. * @ignorenaming
  68877. */
  68878. this.SMOOTHING = 0.75;
  68879. /**
  68880. * Gets or sets the FFT table size
  68881. * @ignorenaming
  68882. */
  68883. this.FFT_SIZE = 512;
  68884. /**
  68885. * Gets or sets the bar graph amplitude
  68886. * @ignorenaming
  68887. */
  68888. this.BARGRAPHAMPLITUDE = 256;
  68889. /**
  68890. * Gets or sets the position of the debug canvas
  68891. * @ignorenaming
  68892. */
  68893. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  68894. /**
  68895. * Gets or sets the debug canvas size
  68896. * @ignorenaming
  68897. */
  68898. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  68899. this._scene = scene;
  68900. this._audioEngine = BABYLON.Engine.audioEngine;
  68901. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  68902. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  68903. this._webAudioAnalyser.minDecibels = -140;
  68904. this._webAudioAnalyser.maxDecibels = 0;
  68905. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68906. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68907. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  68908. }
  68909. }
  68910. /**
  68911. * Get the number of data values you will have to play with for the visualization
  68912. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  68913. * @returns a number
  68914. */
  68915. Analyser.prototype.getFrequencyBinCount = function () {
  68916. if (this._audioEngine.canUseWebAudio) {
  68917. return this._webAudioAnalyser.frequencyBinCount;
  68918. }
  68919. else {
  68920. return 0;
  68921. }
  68922. };
  68923. /**
  68924. * Gets the current frequency data as a byte array
  68925. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68926. * @returns a Uint8Array
  68927. */
  68928. Analyser.prototype.getByteFrequencyData = function () {
  68929. if (this._audioEngine.canUseWebAudio) {
  68930. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68931. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68932. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  68933. }
  68934. return this._byteFreqs;
  68935. };
  68936. /**
  68937. * Gets the current waveform as a byte array
  68938. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  68939. * @returns a Uint8Array
  68940. */
  68941. Analyser.prototype.getByteTimeDomainData = function () {
  68942. if (this._audioEngine.canUseWebAudio) {
  68943. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68944. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68945. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  68946. }
  68947. return this._byteTime;
  68948. };
  68949. /**
  68950. * Gets the current frequency data as a float array
  68951. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68952. * @returns a Float32Array
  68953. */
  68954. Analyser.prototype.getFloatFrequencyData = function () {
  68955. if (this._audioEngine.canUseWebAudio) {
  68956. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68957. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68958. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  68959. }
  68960. return this._floatFreqs;
  68961. };
  68962. /**
  68963. * Renders the debug canvas
  68964. */
  68965. Analyser.prototype.drawDebugCanvas = function () {
  68966. var _this = this;
  68967. if (this._audioEngine.canUseWebAudio) {
  68968. if (!this._debugCanvas) {
  68969. this._debugCanvas = document.createElement("canvas");
  68970. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  68971. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  68972. this._debugCanvas.style.position = "absolute";
  68973. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  68974. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  68975. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  68976. document.body.appendChild(this._debugCanvas);
  68977. this._registerFunc = function () {
  68978. _this.drawDebugCanvas();
  68979. };
  68980. this._scene.registerBeforeRender(this._registerFunc);
  68981. }
  68982. if (this._registerFunc && this._debugCanvasContext) {
  68983. var workingArray = this.getByteFrequencyData();
  68984. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  68985. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  68986. // Draw the frequency domain chart.
  68987. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  68988. var value = workingArray[i];
  68989. var percent = value / this.BARGRAPHAMPLITUDE;
  68990. var height = this.DEBUGCANVASSIZE.height * percent;
  68991. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  68992. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  68993. var hue = i / this.getFrequencyBinCount() * 360;
  68994. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  68995. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  68996. }
  68997. }
  68998. }
  68999. };
  69000. /**
  69001. * Stops rendering the debug canvas and removes it
  69002. */
  69003. Analyser.prototype.stopDebugCanvas = function () {
  69004. if (this._debugCanvas) {
  69005. if (this._registerFunc) {
  69006. this._scene.unregisterBeforeRender(this._registerFunc);
  69007. this._registerFunc = null;
  69008. }
  69009. document.body.removeChild(this._debugCanvas);
  69010. this._debugCanvas = null;
  69011. this._debugCanvasContext = null;
  69012. }
  69013. };
  69014. /**
  69015. * Connects two audio nodes
  69016. * @param inputAudioNode defines first node to connect
  69017. * @param outputAudioNode defines second node to connect
  69018. */
  69019. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  69020. if (this._audioEngine.canUseWebAudio) {
  69021. inputAudioNode.connect(this._webAudioAnalyser);
  69022. this._webAudioAnalyser.connect(outputAudioNode);
  69023. }
  69024. };
  69025. /**
  69026. * Releases all associated resources
  69027. */
  69028. Analyser.prototype.dispose = function () {
  69029. if (this._audioEngine.canUseWebAudio) {
  69030. this._webAudioAnalyser.disconnect();
  69031. }
  69032. };
  69033. return Analyser;
  69034. }());
  69035. BABYLON.Analyser = Analyser;
  69036. })(BABYLON || (BABYLON = {}));
  69037. //# sourceMappingURL=babylon.analyser.js.map
  69038. var BABYLON;
  69039. (function (BABYLON) {
  69040. /**
  69041. * Wraps one or more Sound objects and selects one with random weight for playback.
  69042. */
  69043. var WeightedSound = /** @class */ (function () {
  69044. /**
  69045. * Creates a new WeightedSound from the list of sounds given.
  69046. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  69047. * @param sounds Array of Sounds that will be selected from.
  69048. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  69049. */
  69050. function WeightedSound(loop, sounds, weights) {
  69051. var _this = this;
  69052. /** When true a Sound will be selected and played when the current playing Sound completes. */
  69053. this.loop = false;
  69054. this._coneInnerAngle = 360;
  69055. this._coneOuterAngle = 360;
  69056. this._volume = 1;
  69057. /** A Sound is currently playing. */
  69058. this.isPlaying = false;
  69059. /** A Sound is currently paused. */
  69060. this.isPaused = false;
  69061. this._sounds = [];
  69062. this._weights = [];
  69063. if (sounds.length !== weights.length) {
  69064. throw new Error('Sounds length does not equal weights length');
  69065. }
  69066. this.loop = loop;
  69067. this._weights = weights;
  69068. // Normalize the weights
  69069. var weightSum = 0;
  69070. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  69071. var weight = weights_1[_i];
  69072. weightSum += weight;
  69073. }
  69074. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  69075. for (var i = 0; i < this._weights.length; i++) {
  69076. this._weights[i] *= invWeightSum;
  69077. }
  69078. this._sounds = sounds;
  69079. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  69080. var sound = _b[_a];
  69081. sound.onEndedObservable.add(function () { _this._onended(); });
  69082. }
  69083. }
  69084. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  69085. /**
  69086. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  69087. */
  69088. get: function () {
  69089. return this._coneInnerAngle;
  69090. },
  69091. /**
  69092. * The size of cone in degress for a directional sound in which there will be no attenuation.
  69093. */
  69094. set: function (value) {
  69095. if (value !== this._coneInnerAngle) {
  69096. if (this._coneOuterAngle < value) {
  69097. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69098. return;
  69099. }
  69100. this._coneInnerAngle = value;
  69101. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69102. var sound = _a[_i];
  69103. sound.directionalConeInnerAngle = value;
  69104. }
  69105. }
  69106. },
  69107. enumerable: true,
  69108. configurable: true
  69109. });
  69110. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  69111. /**
  69112. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69113. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69114. */
  69115. get: function () {
  69116. return this._coneOuterAngle;
  69117. },
  69118. /**
  69119. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69120. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69121. */
  69122. set: function (value) {
  69123. if (value !== this._coneOuterAngle) {
  69124. if (value < this._coneInnerAngle) {
  69125. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69126. return;
  69127. }
  69128. this._coneOuterAngle = value;
  69129. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69130. var sound = _a[_i];
  69131. sound.directionalConeOuterAngle = value;
  69132. }
  69133. }
  69134. },
  69135. enumerable: true,
  69136. configurable: true
  69137. });
  69138. Object.defineProperty(WeightedSound.prototype, "volume", {
  69139. /**
  69140. * Playback volume.
  69141. */
  69142. get: function () {
  69143. return this._volume;
  69144. },
  69145. /**
  69146. * Playback volume.
  69147. */
  69148. set: function (value) {
  69149. if (value !== this._volume) {
  69150. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69151. var sound = _a[_i];
  69152. sound.setVolume(value);
  69153. }
  69154. }
  69155. },
  69156. enumerable: true,
  69157. configurable: true
  69158. });
  69159. WeightedSound.prototype._onended = function () {
  69160. if (this._currentIndex !== undefined) {
  69161. this._sounds[this._currentIndex].autoplay = false;
  69162. }
  69163. if (this.loop && this.isPlaying) {
  69164. this.play();
  69165. }
  69166. else {
  69167. this.isPlaying = false;
  69168. }
  69169. };
  69170. /**
  69171. * Suspend playback
  69172. */
  69173. WeightedSound.prototype.pause = function () {
  69174. this.isPaused = true;
  69175. if (this._currentIndex !== undefined) {
  69176. this._sounds[this._currentIndex].pause();
  69177. }
  69178. };
  69179. /**
  69180. * Stop playback
  69181. */
  69182. WeightedSound.prototype.stop = function () {
  69183. this.isPlaying = false;
  69184. if (this._currentIndex !== undefined) {
  69185. this._sounds[this._currentIndex].stop();
  69186. }
  69187. };
  69188. /**
  69189. * Start playback.
  69190. * @param startOffset Position the clip head at a specific time in seconds.
  69191. */
  69192. WeightedSound.prototype.play = function (startOffset) {
  69193. if (!this.isPaused) {
  69194. this.stop();
  69195. var randomValue = Math.random();
  69196. var total = 0;
  69197. for (var i = 0; i < this._weights.length; i++) {
  69198. total += this._weights[i];
  69199. if (randomValue <= total) {
  69200. this._currentIndex = i;
  69201. break;
  69202. }
  69203. }
  69204. }
  69205. var sound = this._sounds[this._currentIndex];
  69206. if (sound.isReady()) {
  69207. sound.play(0, this.isPaused ? undefined : startOffset);
  69208. }
  69209. else {
  69210. sound.autoplay = true;
  69211. }
  69212. this.isPlaying = true;
  69213. this.isPaused = false;
  69214. };
  69215. return WeightedSound;
  69216. }());
  69217. BABYLON.WeightedSound = WeightedSound;
  69218. })(BABYLON || (BABYLON = {}));
  69219. //# sourceMappingURL=babylon.weightedsound.js.map
  69220. var BABYLON;
  69221. (function (BABYLON) {
  69222. // Adds the parser to the scene parsers.
  69223. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  69224. // TODO: add sound
  69225. var loadedSounds = [];
  69226. var loadedSound;
  69227. container.sounds = container.sounds || [];
  69228. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69229. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69230. var parsedSound = parsedData.sounds[index];
  69231. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69232. if (!parsedSound.url)
  69233. parsedSound.url = parsedSound.name;
  69234. if (!loadedSounds[parsedSound.url]) {
  69235. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69236. loadedSounds[parsedSound.url] = loadedSound;
  69237. container.sounds.push(loadedSound);
  69238. }
  69239. else {
  69240. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69241. }
  69242. }
  69243. else {
  69244. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69245. }
  69246. }
  69247. }
  69248. loadedSounds = [];
  69249. });
  69250. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  69251. get: function () {
  69252. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69253. if (!compo) {
  69254. compo = new AudioSceneComponent(this);
  69255. this._addComponent(compo);
  69256. }
  69257. if (!this._mainSoundTrack) {
  69258. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  69259. }
  69260. return this._mainSoundTrack;
  69261. },
  69262. enumerable: true,
  69263. configurable: true
  69264. });
  69265. BABYLON.Scene.prototype.getSoundByName = function (name) {
  69266. var index;
  69267. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  69268. if (this.mainSoundTrack.soundCollection[index].name === name) {
  69269. return this.mainSoundTrack.soundCollection[index];
  69270. }
  69271. }
  69272. if (this.soundTracks) {
  69273. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  69274. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  69275. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  69276. return this.soundTracks[sdIndex].soundCollection[index];
  69277. }
  69278. }
  69279. }
  69280. }
  69281. return null;
  69282. };
  69283. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  69284. get: function () {
  69285. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69286. if (!compo) {
  69287. compo = new AudioSceneComponent(this);
  69288. this._addComponent(compo);
  69289. }
  69290. return compo.audioEnabled;
  69291. },
  69292. set: function (value) {
  69293. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69294. if (!compo) {
  69295. compo = new AudioSceneComponent(this);
  69296. this._addComponent(compo);
  69297. }
  69298. if (value) {
  69299. compo.enableAudio();
  69300. }
  69301. else {
  69302. compo.disableAudio();
  69303. }
  69304. },
  69305. enumerable: true,
  69306. configurable: true
  69307. });
  69308. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  69309. get: function () {
  69310. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69311. if (!compo) {
  69312. compo = new AudioSceneComponent(this);
  69313. this._addComponent(compo);
  69314. }
  69315. return compo.headphone;
  69316. },
  69317. set: function (value) {
  69318. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69319. if (!compo) {
  69320. compo = new AudioSceneComponent(this);
  69321. this._addComponent(compo);
  69322. }
  69323. if (value) {
  69324. compo.switchAudioModeForHeadphones();
  69325. }
  69326. else {
  69327. compo.switchAudioModeForNormalSpeakers();
  69328. }
  69329. },
  69330. enumerable: true,
  69331. configurable: true
  69332. });
  69333. /**
  69334. * Defines the sound scene component responsible to manage any sounds
  69335. * in a given scene.
  69336. */
  69337. var AudioSceneComponent = /** @class */ (function () {
  69338. /**
  69339. * Creates a new instance of the component for the given scene
  69340. * @param scene Defines the scene to register the component in
  69341. */
  69342. function AudioSceneComponent(scene) {
  69343. /**
  69344. * The component name helpfull to identify the component in the list of scene components.
  69345. */
  69346. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  69347. this._audioEnabled = true;
  69348. this._headphone = false;
  69349. this.scene = scene;
  69350. scene.soundTracks = new Array();
  69351. scene.sounds = new Array();
  69352. }
  69353. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  69354. /**
  69355. * Gets whether audio is enabled or not.
  69356. * Please use related enable/disable method to switch state.
  69357. */
  69358. get: function () {
  69359. return this._audioEnabled;
  69360. },
  69361. enumerable: true,
  69362. configurable: true
  69363. });
  69364. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  69365. /**
  69366. * Gets whether audio is outputing to headphone or not.
  69367. * Please use the according Switch methods to change output.
  69368. */
  69369. get: function () {
  69370. return this._headphone;
  69371. },
  69372. enumerable: true,
  69373. configurable: true
  69374. });
  69375. /**
  69376. * Registers the component in a given scene
  69377. */
  69378. AudioSceneComponent.prototype.register = function () {
  69379. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  69380. };
  69381. /**
  69382. * Rebuilds the elements related to this component in case of
  69383. * context lost for instance.
  69384. */
  69385. AudioSceneComponent.prototype.rebuild = function () {
  69386. // Nothing to do here. (Not rendering related)
  69387. };
  69388. /**
  69389. * Serializes the component data to the specified json object
  69390. * @param serializationObject The object to serialize to
  69391. */
  69392. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  69393. serializationObject.sounds = [];
  69394. if (this.scene.soundTracks) {
  69395. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  69396. var soundtrack = this.scene.soundTracks[index];
  69397. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  69398. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  69399. }
  69400. }
  69401. }
  69402. };
  69403. /**
  69404. * Adds all the element from the container to the scene
  69405. * @param container the container holding the elements
  69406. */
  69407. AudioSceneComponent.prototype.addFromContainer = function (container) {
  69408. var _this = this;
  69409. if (!container.sounds) {
  69410. return;
  69411. }
  69412. container.sounds.forEach(function (sound) {
  69413. sound.play();
  69414. sound.autoplay = true;
  69415. _this.scene.mainSoundTrack.AddSound(sound);
  69416. });
  69417. };
  69418. /**
  69419. * Removes all the elements in the container from the scene
  69420. * @param container contains the elements to remove
  69421. */
  69422. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  69423. var _this = this;
  69424. if (!container.sounds) {
  69425. return;
  69426. }
  69427. container.sounds.forEach(function (sound) {
  69428. sound.stop();
  69429. sound.autoplay = false;
  69430. _this.scene.mainSoundTrack.RemoveSound(sound);
  69431. });
  69432. };
  69433. /**
  69434. * Disposes the component and the associated ressources.
  69435. */
  69436. AudioSceneComponent.prototype.dispose = function () {
  69437. var scene = this.scene;
  69438. if (scene._mainSoundTrack) {
  69439. scene.mainSoundTrack.dispose();
  69440. }
  69441. if (scene.soundTracks) {
  69442. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  69443. scene.soundTracks[scIndex].dispose();
  69444. }
  69445. }
  69446. };
  69447. /**
  69448. * Disables audio in the associated scene.
  69449. */
  69450. AudioSceneComponent.prototype.disableAudio = function () {
  69451. var scene = this.scene;
  69452. this._audioEnabled = false;
  69453. var i;
  69454. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69455. scene.mainSoundTrack.soundCollection[i].pause();
  69456. }
  69457. if (scene.soundTracks) {
  69458. for (i = 0; i < scene.soundTracks.length; i++) {
  69459. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69460. scene.soundTracks[i].soundCollection[j].pause();
  69461. }
  69462. }
  69463. }
  69464. };
  69465. /**
  69466. * Enables audio in the associated scene.
  69467. */
  69468. AudioSceneComponent.prototype.enableAudio = function () {
  69469. var scene = this.scene;
  69470. this._audioEnabled = true;
  69471. var i;
  69472. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69473. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  69474. scene.mainSoundTrack.soundCollection[i].play();
  69475. }
  69476. }
  69477. if (scene.soundTracks) {
  69478. for (i = 0; i < scene.soundTracks.length; i++) {
  69479. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69480. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  69481. scene.soundTracks[i].soundCollection[j].play();
  69482. }
  69483. }
  69484. }
  69485. }
  69486. };
  69487. /**
  69488. * Switch audio to headphone output.
  69489. */
  69490. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  69491. var scene = this.scene;
  69492. this._headphone = true;
  69493. scene.mainSoundTrack.switchPanningModelToHRTF();
  69494. if (scene.soundTracks) {
  69495. for (var i = 0; i < scene.soundTracks.length; i++) {
  69496. scene.soundTracks[i].switchPanningModelToHRTF();
  69497. }
  69498. }
  69499. };
  69500. /**
  69501. * Switch audio to normal speakers.
  69502. */
  69503. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  69504. var scene = this.scene;
  69505. this._headphone = false;
  69506. scene.mainSoundTrack.switchPanningModelToEqualPower();
  69507. if (scene.soundTracks) {
  69508. for (var i = 0; i < scene.soundTracks.length; i++) {
  69509. scene.soundTracks[i].switchPanningModelToEqualPower();
  69510. }
  69511. }
  69512. };
  69513. AudioSceneComponent.prototype._afterRender = function () {
  69514. var scene = this.scene;
  69515. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  69516. return;
  69517. }
  69518. var listeningCamera;
  69519. var audioEngine = BABYLON.Engine.audioEngine;
  69520. if (scene.activeCameras.length > 0) {
  69521. listeningCamera = scene.activeCameras[0];
  69522. }
  69523. else {
  69524. listeningCamera = scene.activeCamera;
  69525. }
  69526. if (listeningCamera && audioEngine.audioContext) {
  69527. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  69528. // for VR cameras
  69529. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  69530. listeningCamera = listeningCamera.rigCameras[0];
  69531. }
  69532. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  69533. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  69534. cameraDirection.normalize();
  69535. // To avoid some errors on GearVR
  69536. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  69537. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  69538. }
  69539. var i;
  69540. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69541. var sound = scene.mainSoundTrack.soundCollection[i];
  69542. if (sound.useCustomAttenuation) {
  69543. sound.updateDistanceFromListener();
  69544. }
  69545. }
  69546. if (scene.soundTracks) {
  69547. for (i = 0; i < scene.soundTracks.length; i++) {
  69548. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69549. sound = scene.soundTracks[i].soundCollection[j];
  69550. if (sound.useCustomAttenuation) {
  69551. sound.updateDistanceFromListener();
  69552. }
  69553. }
  69554. }
  69555. }
  69556. }
  69557. };
  69558. return AudioSceneComponent;
  69559. }());
  69560. BABYLON.AudioSceneComponent = AudioSceneComponent;
  69561. })(BABYLON || (BABYLON = {}));
  69562. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  69563. var BABYLON;
  69564. (function (BABYLON) {
  69565. /**
  69566. * This defines an action helpful to play a defined sound on a triggered action.
  69567. */
  69568. var PlaySoundAction = /** @class */ (function (_super) {
  69569. __extends(PlaySoundAction, _super);
  69570. /**
  69571. * Instantiate the action
  69572. * @param triggerOptions defines the trigger options
  69573. * @param sound defines the sound to play
  69574. * @param condition defines the trigger related conditions
  69575. */
  69576. function PlaySoundAction(triggerOptions, sound, condition) {
  69577. var _this = _super.call(this, triggerOptions, condition) || this;
  69578. _this._sound = sound;
  69579. return _this;
  69580. }
  69581. /** @hidden */
  69582. PlaySoundAction.prototype._prepare = function () {
  69583. };
  69584. /**
  69585. * Execute the action and play the sound.
  69586. */
  69587. PlaySoundAction.prototype.execute = function () {
  69588. if (this._sound !== undefined)
  69589. this._sound.play();
  69590. };
  69591. /**
  69592. * Serializes the actions and its related information.
  69593. * @param parent defines the object to serialize in
  69594. * @returns the serialized object
  69595. */
  69596. PlaySoundAction.prototype.serialize = function (parent) {
  69597. return _super.prototype._serialize.call(this, {
  69598. name: "PlaySoundAction",
  69599. properties: [{ name: "sound", value: this._sound.name }]
  69600. }, parent);
  69601. };
  69602. return PlaySoundAction;
  69603. }(BABYLON.Action));
  69604. BABYLON.PlaySoundAction = PlaySoundAction;
  69605. /**
  69606. * This defines an action helpful to stop a defined sound on a triggered action.
  69607. */
  69608. var StopSoundAction = /** @class */ (function (_super) {
  69609. __extends(StopSoundAction, _super);
  69610. /**
  69611. * Instantiate the action
  69612. * @param triggerOptions defines the trigger options
  69613. * @param sound defines the sound to stop
  69614. * @param condition defines the trigger related conditions
  69615. */
  69616. function StopSoundAction(triggerOptions, sound, condition) {
  69617. var _this = _super.call(this, triggerOptions, condition) || this;
  69618. _this._sound = sound;
  69619. return _this;
  69620. }
  69621. /** @hidden */
  69622. StopSoundAction.prototype._prepare = function () {
  69623. };
  69624. /**
  69625. * Execute the action and stop the sound.
  69626. */
  69627. StopSoundAction.prototype.execute = function () {
  69628. if (this._sound !== undefined)
  69629. this._sound.stop();
  69630. };
  69631. /**
  69632. * Serializes the actions and its related information.
  69633. * @param parent defines the object to serialize in
  69634. * @returns the serialized object
  69635. */
  69636. StopSoundAction.prototype.serialize = function (parent) {
  69637. return _super.prototype._serialize.call(this, {
  69638. name: "StopSoundAction",
  69639. properties: [{ name: "sound", value: this._sound.name }]
  69640. }, parent);
  69641. };
  69642. return StopSoundAction;
  69643. }(BABYLON.Action));
  69644. BABYLON.StopSoundAction = StopSoundAction;
  69645. })(BABYLON || (BABYLON = {}));
  69646. //# sourceMappingURL=babylon.directAudioActions.js.map
  69647. var BABYLON;
  69648. (function (BABYLON) {
  69649. var CubeTexture = /** @class */ (function (_super) {
  69650. __extends(CubeTexture, _super);
  69651. /**
  69652. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  69653. * as prefiltered data.
  69654. * @param rootUrl defines the url of the texture or the root name of the six images
  69655. * @param scene defines the scene the texture is attached to
  69656. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  69657. * @param noMipmap defines if mipmaps should be created or not
  69658. * @param files defines the six files to load for the different faces
  69659. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  69660. * @param onError defines a callback triggered in case of error during load
  69661. * @param format defines the internal format to use for the texture once loaded
  69662. * @param prefiltered defines whether or not the texture is created from prefiltered data
  69663. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  69664. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69665. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69666. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69667. * @return the cube texture
  69668. */
  69669. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  69670. if (extensions === void 0) { extensions = null; }
  69671. if (noMipmap === void 0) { noMipmap = false; }
  69672. if (files === void 0) { files = null; }
  69673. if (onLoad === void 0) { onLoad = null; }
  69674. if (onError === void 0) { onError = null; }
  69675. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69676. if (prefiltered === void 0) { prefiltered = false; }
  69677. if (forcedExtension === void 0) { forcedExtension = null; }
  69678. if (createPolynomials === void 0) { createPolynomials = false; }
  69679. if (lodScale === void 0) { lodScale = 0.8; }
  69680. if (lodOffset === void 0) { lodOffset = 0; }
  69681. var _this = _super.call(this, scene) || this;
  69682. /**
  69683. * Gets or sets the center of the bounding box associated with the cube texture
  69684. * It must define where the camera used to render the texture was set
  69685. */
  69686. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69687. _this._rotationY = 0;
  69688. /** @hidden */
  69689. _this._prefiltered = false;
  69690. _this.name = rootUrl;
  69691. _this.url = rootUrl;
  69692. _this._noMipmap = noMipmap;
  69693. _this.hasAlpha = false;
  69694. _this._format = format;
  69695. _this.isCube = true;
  69696. _this._textureMatrix = BABYLON.Matrix.Identity();
  69697. _this._createPolynomials = createPolynomials;
  69698. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69699. if (!rootUrl && !files) {
  69700. return _this;
  69701. }
  69702. var lastDot = rootUrl.lastIndexOf(".");
  69703. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  69704. var isDDS = (extension === ".dds");
  69705. var isEnv = (extension === ".env");
  69706. if (isEnv) {
  69707. _this.gammaSpace = false;
  69708. _this._prefiltered = false;
  69709. }
  69710. else {
  69711. _this._prefiltered = prefiltered;
  69712. if (prefiltered) {
  69713. _this.gammaSpace = false;
  69714. }
  69715. }
  69716. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  69717. if (!files) {
  69718. if (!isEnv && !isDDS && !extensions) {
  69719. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  69720. }
  69721. files = [];
  69722. if (extensions) {
  69723. for (var index = 0; index < extensions.length; index++) {
  69724. files.push(rootUrl + extensions[index]);
  69725. }
  69726. }
  69727. }
  69728. _this._files = files;
  69729. if (!_this._texture) {
  69730. if (!scene.useDelayedTextureLoading) {
  69731. if (prefiltered) {
  69732. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  69733. }
  69734. else {
  69735. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  69736. }
  69737. }
  69738. else {
  69739. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69740. }
  69741. }
  69742. else if (onLoad) {
  69743. if (_this._texture.isReady) {
  69744. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  69745. }
  69746. else {
  69747. _this._texture.onLoadedObservable.add(onLoad);
  69748. }
  69749. }
  69750. return _this;
  69751. }
  69752. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  69753. get: function () {
  69754. return this._boundingBoxSize;
  69755. },
  69756. /**
  69757. * Gets or sets the size of the bounding box associated with the cube texture
  69758. * When defined, the cubemap will switch to local mode
  69759. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69760. * @example https://www.babylonjs-playground.com/#RNASML
  69761. */
  69762. set: function (value) {
  69763. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69764. return;
  69765. }
  69766. this._boundingBoxSize = value;
  69767. var scene = this.getScene();
  69768. if (scene) {
  69769. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69770. }
  69771. },
  69772. enumerable: true,
  69773. configurable: true
  69774. });
  69775. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  69776. /**
  69777. * Gets texture matrix rotation angle around Y axis radians.
  69778. */
  69779. get: function () {
  69780. return this._rotationY;
  69781. },
  69782. /**
  69783. * Sets texture matrix rotation angle around Y axis in radians.
  69784. */
  69785. set: function (value) {
  69786. this._rotationY = value;
  69787. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  69788. },
  69789. enumerable: true,
  69790. configurable: true
  69791. });
  69792. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  69793. var rootUrlKey = "";
  69794. files.forEach(function (url) { return rootUrlKey += url; });
  69795. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  69796. };
  69797. /**
  69798. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  69799. * @param url defines the url of the prefiltered texture
  69800. * @param scene defines the scene the texture is attached to
  69801. * @param forcedExtension defines the extension of the file if different from the url
  69802. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69803. * @return the prefiltered texture
  69804. */
  69805. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  69806. if (forcedExtension === void 0) { forcedExtension = null; }
  69807. if (createPolynomials === void 0) { createPolynomials = true; }
  69808. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  69809. };
  69810. // Methods
  69811. CubeTexture.prototype.delayLoad = function () {
  69812. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69813. return;
  69814. }
  69815. var scene = this.getScene();
  69816. if (!scene) {
  69817. return;
  69818. }
  69819. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69820. this._texture = this._getFromCache(this.url, this._noMipmap);
  69821. if (!this._texture) {
  69822. if (this._prefiltered) {
  69823. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  69824. }
  69825. else {
  69826. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  69827. }
  69828. }
  69829. };
  69830. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  69831. return this._textureMatrix;
  69832. };
  69833. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69834. this._textureMatrix = value;
  69835. };
  69836. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69837. var texture = BABYLON.SerializationHelper.Parse(function () {
  69838. var prefiltered = false;
  69839. if (parsedTexture.prefiltered) {
  69840. prefiltered = parsedTexture.prefiltered;
  69841. }
  69842. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  69843. }, parsedTexture, scene);
  69844. // Local Cubemaps
  69845. if (parsedTexture.boundingBoxPosition) {
  69846. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  69847. }
  69848. if (parsedTexture.boundingBoxSize) {
  69849. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  69850. }
  69851. // Animations
  69852. if (parsedTexture.animations) {
  69853. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  69854. var parsedAnimation = parsedTexture.animations[animationIndex];
  69855. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69856. }
  69857. }
  69858. return texture;
  69859. };
  69860. CubeTexture.prototype.clone = function () {
  69861. var _this = this;
  69862. return BABYLON.SerializationHelper.Clone(function () {
  69863. var scene = _this.getScene();
  69864. if (!scene) {
  69865. return _this;
  69866. }
  69867. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  69868. }, this);
  69869. };
  69870. __decorate([
  69871. BABYLON.serialize("rotationY")
  69872. ], CubeTexture.prototype, "rotationY", null);
  69873. return CubeTexture;
  69874. }(BABYLON.BaseTexture));
  69875. BABYLON.CubeTexture = CubeTexture;
  69876. })(BABYLON || (BABYLON = {}));
  69877. //# sourceMappingURL=babylon.cubeTexture.js.map
  69878. var BABYLON;
  69879. (function (BABYLON) {
  69880. /**
  69881. * Raw cube texture where the raw buffers are passed in
  69882. */
  69883. var RawCubeTexture = /** @class */ (function (_super) {
  69884. __extends(RawCubeTexture, _super);
  69885. /**
  69886. * Creates a cube texture where the raw buffers are passed in.
  69887. * @param scene defines the scene the texture is attached to
  69888. * @param data defines the array of data to use to create each face
  69889. * @param size defines the size of the textures
  69890. * @param format defines the format of the data
  69891. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  69892. * @param generateMipMaps defines if the engine should generate the mip levels
  69893. * @param invertY defines if data must be stored with Y axis inverted
  69894. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  69895. * @param compression defines the compression used (null by default)
  69896. */
  69897. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  69898. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69899. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69900. if (generateMipMaps === void 0) { generateMipMaps = false; }
  69901. if (invertY === void 0) { invertY = false; }
  69902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69903. if (compression === void 0) { compression = null; }
  69904. var _this = _super.call(this, "", scene) || this;
  69905. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  69906. return _this;
  69907. }
  69908. /**
  69909. * Updates the raw cube texture.
  69910. * @param data defines the data to store
  69911. * @param format defines the data format
  69912. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  69913. * @param invertY defines if data must be stored with Y axis inverted
  69914. * @param compression defines the compression used (null by default)
  69915. * @param level defines which level of the texture to update
  69916. */
  69917. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  69918. if (compression === void 0) { compression = null; }
  69919. if (level === void 0) { level = 0; }
  69920. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  69921. };
  69922. /**
  69923. * Updates a raw cube texture with RGBD encoded data.
  69924. * @param data defines the array of data [mipmap][face] to use to create each face
  69925. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  69926. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69927. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69928. * @returns a promsie that resolves when the operation is complete
  69929. */
  69930. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  69931. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  69932. if (lodScale === void 0) { lodScale = 0.8; }
  69933. if (lodOffset === void 0) { lodOffset = 0; }
  69934. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  69935. };
  69936. /**
  69937. * Clones the raw cube texture.
  69938. * @return a new cube texture
  69939. */
  69940. RawCubeTexture.prototype.clone = function () {
  69941. var _this = this;
  69942. return BABYLON.SerializationHelper.Clone(function () {
  69943. var scene = _this.getScene();
  69944. var internalTexture = _this._texture;
  69945. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  69946. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  69947. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  69948. }
  69949. return texture;
  69950. }, this);
  69951. };
  69952. /** @hidden */
  69953. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  69954. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  69955. internalTexture._bufferViewArrayArray = data;
  69956. internalTexture._lodGenerationScale = lodScale;
  69957. internalTexture._lodGenerationOffset = lodOffset;
  69958. internalTexture._sphericalPolynomial = sphericalPolynomial;
  69959. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  69960. internalTexture.isReady = true;
  69961. });
  69962. };
  69963. return RawCubeTexture;
  69964. }(BABYLON.CubeTexture));
  69965. BABYLON.RawCubeTexture = RawCubeTexture;
  69966. })(BABYLON || (BABYLON = {}));
  69967. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  69968. var BABYLON;
  69969. (function (BABYLON) {
  69970. var RenderTargetTexture = /** @class */ (function (_super) {
  69971. __extends(RenderTargetTexture, _super);
  69972. /**
  69973. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  69974. * or used a shadow, depth texture...
  69975. * @param name The friendly name of the texture
  69976. * @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)
  69977. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  69978. * @param generateMipMaps True if mip maps need to be generated after render.
  69979. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  69980. * @param type The type of the buffer in the RTT (int, half float, float...)
  69981. * @param isCube True if a cube texture needs to be created
  69982. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  69983. * @param generateDepthBuffer True to generate a depth buffer
  69984. * @param generateStencilBuffer True to generate a stencil buffer
  69985. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  69986. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  69987. */
  69988. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  69989. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  69990. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69991. if (isCube === void 0) { isCube = false; }
  69992. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69993. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69994. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  69995. if (isMulti === void 0) { isMulti = false; }
  69996. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69997. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69998. _this.isCube = isCube;
  69999. _this.renderParticles = true;
  70000. _this.renderSprites = false;
  70001. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  70002. _this.ignoreCameraViewport = false;
  70003. // Events
  70004. /**
  70005. * An event triggered when the texture is unbind.
  70006. */
  70007. _this.onBeforeBindObservable = new BABYLON.Observable();
  70008. /**
  70009. * An event triggered when the texture is unbind.
  70010. */
  70011. _this.onAfterUnbindObservable = new BABYLON.Observable();
  70012. /**
  70013. * An event triggered before rendering the texture
  70014. */
  70015. _this.onBeforeRenderObservable = new BABYLON.Observable();
  70016. /**
  70017. * An event triggered after rendering the texture
  70018. */
  70019. _this.onAfterRenderObservable = new BABYLON.Observable();
  70020. /**
  70021. * An event triggered after the texture clear
  70022. */
  70023. _this.onClearObservable = new BABYLON.Observable();
  70024. _this._currentRefreshId = -1;
  70025. _this._refreshRate = 1;
  70026. _this._samples = 1;
  70027. /**
  70028. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  70029. * It must define where the camera used to render the texture is set
  70030. */
  70031. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70032. scene = _this.getScene();
  70033. if (!scene) {
  70034. return _this;
  70035. }
  70036. _this.renderList = new Array();
  70037. _this._engine = scene.getEngine();
  70038. _this.name = name;
  70039. _this.isRenderTarget = true;
  70040. _this._initialSizeParameter = size;
  70041. _this._processSizeParameter(size);
  70042. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  70043. });
  70044. _this._generateMipMaps = generateMipMaps ? true : false;
  70045. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  70046. // Rendering groups
  70047. _this._renderingManager = new BABYLON.RenderingManager(scene);
  70048. _this._renderingManager._useSceneAutoClearSetup = true;
  70049. if (isMulti) {
  70050. return _this;
  70051. }
  70052. _this._renderTargetOptions = {
  70053. generateMipMaps: generateMipMaps,
  70054. type: type,
  70055. format: format,
  70056. samplingMode: samplingMode,
  70057. generateDepthBuffer: generateDepthBuffer,
  70058. generateStencilBuffer: generateStencilBuffer
  70059. };
  70060. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  70061. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70062. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70063. }
  70064. if (isCube) {
  70065. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  70066. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  70067. _this._textureMatrix = BABYLON.Matrix.Identity();
  70068. }
  70069. else {
  70070. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  70071. }
  70072. return _this;
  70073. }
  70074. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  70075. get: function () {
  70076. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  70077. },
  70078. enumerable: true,
  70079. configurable: true
  70080. });
  70081. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  70082. get: function () {
  70083. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  70084. },
  70085. enumerable: true,
  70086. configurable: true
  70087. });
  70088. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  70089. get: function () {
  70090. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  70091. },
  70092. enumerable: true,
  70093. configurable: true
  70094. });
  70095. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  70096. /**
  70097. * Use this list to define the list of mesh you want to render.
  70098. */
  70099. get: function () {
  70100. return this._renderList;
  70101. },
  70102. set: function (value) {
  70103. this._renderList = value;
  70104. if (this._renderList) {
  70105. this._hookArray(this._renderList);
  70106. }
  70107. },
  70108. enumerable: true,
  70109. configurable: true
  70110. });
  70111. RenderTargetTexture.prototype._hookArray = function (array) {
  70112. var _this = this;
  70113. var oldPush = array.push;
  70114. array.push = function () {
  70115. var items = [];
  70116. for (var _i = 0; _i < arguments.length; _i++) {
  70117. items[_i] = arguments[_i];
  70118. }
  70119. var result = oldPush.apply(array, items);
  70120. _this.getScene().meshes.forEach(function (mesh) {
  70121. mesh._markSubMeshesAsLightDirty();
  70122. });
  70123. return result;
  70124. };
  70125. var oldSplice = array.splice;
  70126. array.splice = function (index, deleteCount) {
  70127. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70128. _this.getScene().meshes.forEach(function (mesh) {
  70129. mesh._markSubMeshesAsLightDirty();
  70130. });
  70131. return deleted;
  70132. };
  70133. };
  70134. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  70135. set: function (callback) {
  70136. if (this._onAfterUnbindObserver) {
  70137. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  70138. }
  70139. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  70140. },
  70141. enumerable: true,
  70142. configurable: true
  70143. });
  70144. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  70145. set: function (callback) {
  70146. if (this._onBeforeRenderObserver) {
  70147. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  70148. }
  70149. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  70150. },
  70151. enumerable: true,
  70152. configurable: true
  70153. });
  70154. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  70155. set: function (callback) {
  70156. if (this._onAfterRenderObserver) {
  70157. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  70158. }
  70159. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  70160. },
  70161. enumerable: true,
  70162. configurable: true
  70163. });
  70164. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  70165. set: function (callback) {
  70166. if (this._onClearObserver) {
  70167. this.onClearObservable.remove(this._onClearObserver);
  70168. }
  70169. this._onClearObserver = this.onClearObservable.add(callback);
  70170. },
  70171. enumerable: true,
  70172. configurable: true
  70173. });
  70174. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  70175. get: function () {
  70176. return this._renderTargetOptions;
  70177. },
  70178. enumerable: true,
  70179. configurable: true
  70180. });
  70181. RenderTargetTexture.prototype._onRatioRescale = function () {
  70182. if (this._sizeRatio) {
  70183. this.resize(this._initialSizeParameter);
  70184. }
  70185. };
  70186. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  70187. get: function () {
  70188. return this._boundingBoxSize;
  70189. },
  70190. /**
  70191. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  70192. * When defined, the cubemap will switch to local mode
  70193. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  70194. * @example https://www.babylonjs-playground.com/#RNASML
  70195. */
  70196. set: function (value) {
  70197. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  70198. return;
  70199. }
  70200. this._boundingBoxSize = value;
  70201. var scene = this.getScene();
  70202. if (scene) {
  70203. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  70204. }
  70205. },
  70206. enumerable: true,
  70207. configurable: true
  70208. });
  70209. /**
  70210. * Creates a depth stencil texture.
  70211. * This is only available in WebGL 2 or with the depth texture extension available.
  70212. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  70213. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  70214. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  70215. */
  70216. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  70217. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  70218. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  70219. if (generateStencil === void 0) { generateStencil = false; }
  70220. if (!this.getScene()) {
  70221. return;
  70222. }
  70223. var engine = this.getScene().getEngine();
  70224. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  70225. bilinearFiltering: bilinearFiltering,
  70226. comparisonFunction: comparisonFunction,
  70227. generateStencil: generateStencil,
  70228. isCube: this.isCube
  70229. });
  70230. engine.setFrameBufferDepthStencilTexture(this);
  70231. };
  70232. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  70233. if (size.ratio) {
  70234. this._sizeRatio = size.ratio;
  70235. this._size = {
  70236. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  70237. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  70238. };
  70239. }
  70240. else {
  70241. this._size = size;
  70242. }
  70243. };
  70244. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  70245. get: function () {
  70246. return this._samples;
  70247. },
  70248. set: function (value) {
  70249. if (this._samples === value) {
  70250. return;
  70251. }
  70252. var scene = this.getScene();
  70253. if (!scene) {
  70254. return;
  70255. }
  70256. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  70257. },
  70258. enumerable: true,
  70259. configurable: true
  70260. });
  70261. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  70262. this._currentRefreshId = -1;
  70263. };
  70264. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  70265. get: function () {
  70266. return this._refreshRate;
  70267. },
  70268. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70269. set: function (value) {
  70270. this._refreshRate = value;
  70271. this.resetRefreshCounter();
  70272. },
  70273. enumerable: true,
  70274. configurable: true
  70275. });
  70276. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  70277. if (!this._postProcessManager) {
  70278. var scene = this.getScene();
  70279. if (!scene) {
  70280. return;
  70281. }
  70282. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  70283. this._postProcesses = new Array();
  70284. }
  70285. this._postProcesses.push(postProcess);
  70286. this._postProcesses[0].autoClear = false;
  70287. };
  70288. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  70289. if (!this._postProcesses) {
  70290. return;
  70291. }
  70292. if (dispose) {
  70293. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  70294. var postProcess = _a[_i];
  70295. postProcess.dispose();
  70296. }
  70297. }
  70298. this._postProcesses = [];
  70299. };
  70300. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  70301. if (!this._postProcesses) {
  70302. return;
  70303. }
  70304. var index = this._postProcesses.indexOf(postProcess);
  70305. if (index === -1) {
  70306. return;
  70307. }
  70308. this._postProcesses.splice(index, 1);
  70309. if (this._postProcesses.length > 0) {
  70310. this._postProcesses[0].autoClear = false;
  70311. }
  70312. };
  70313. /** @hidden */
  70314. RenderTargetTexture.prototype._shouldRender = function () {
  70315. if (this._currentRefreshId === -1) { // At least render once
  70316. this._currentRefreshId = 1;
  70317. return true;
  70318. }
  70319. if (this.refreshRate === this._currentRefreshId) {
  70320. this._currentRefreshId = 1;
  70321. return true;
  70322. }
  70323. this._currentRefreshId++;
  70324. return false;
  70325. };
  70326. RenderTargetTexture.prototype.getRenderSize = function () {
  70327. if (this._size.width) {
  70328. return this._size.width;
  70329. }
  70330. return this._size;
  70331. };
  70332. RenderTargetTexture.prototype.getRenderWidth = function () {
  70333. if (this._size.width) {
  70334. return this._size.width;
  70335. }
  70336. return this._size;
  70337. };
  70338. RenderTargetTexture.prototype.getRenderHeight = function () {
  70339. if (this._size.width) {
  70340. return this._size.height;
  70341. }
  70342. return this._size;
  70343. };
  70344. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  70345. get: function () {
  70346. return true;
  70347. },
  70348. enumerable: true,
  70349. configurable: true
  70350. });
  70351. RenderTargetTexture.prototype.scale = function (ratio) {
  70352. var newSize = this.getRenderSize() * ratio;
  70353. this.resize(newSize);
  70354. };
  70355. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  70356. if (this.isCube) {
  70357. return this._textureMatrix;
  70358. }
  70359. return _super.prototype.getReflectionTextureMatrix.call(this);
  70360. };
  70361. RenderTargetTexture.prototype.resize = function (size) {
  70362. this.releaseInternalTexture();
  70363. var scene = this.getScene();
  70364. if (!scene) {
  70365. return;
  70366. }
  70367. this._processSizeParameter(size);
  70368. if (this.isCube) {
  70369. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  70370. }
  70371. else {
  70372. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  70373. }
  70374. };
  70375. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  70376. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  70377. if (dumpForDebug === void 0) { dumpForDebug = false; }
  70378. var scene = this.getScene();
  70379. if (!scene) {
  70380. return;
  70381. }
  70382. var engine = scene.getEngine();
  70383. if (this.useCameraPostProcesses !== undefined) {
  70384. useCameraPostProcess = this.useCameraPostProcesses;
  70385. }
  70386. if (this._waitingRenderList) {
  70387. this.renderList = [];
  70388. for (var index = 0; index < this._waitingRenderList.length; index++) {
  70389. var id = this._waitingRenderList[index];
  70390. var mesh_1 = scene.getMeshByID(id);
  70391. if (mesh_1) {
  70392. this.renderList.push(mesh_1);
  70393. }
  70394. }
  70395. delete this._waitingRenderList;
  70396. }
  70397. // Is predicate defined?
  70398. if (this.renderListPredicate) {
  70399. if (this.renderList) {
  70400. this.renderList.splice(0); // Clear previous renderList
  70401. }
  70402. else {
  70403. this.renderList = [];
  70404. }
  70405. var scene = this.getScene();
  70406. if (!scene) {
  70407. return;
  70408. }
  70409. var sceneMeshes = scene.meshes;
  70410. for (var index = 0; index < sceneMeshes.length; index++) {
  70411. var mesh = sceneMeshes[index];
  70412. if (this.renderListPredicate(mesh)) {
  70413. this.renderList.push(mesh);
  70414. }
  70415. }
  70416. }
  70417. this.onBeforeBindObservable.notifyObservers(this);
  70418. // Set custom projection.
  70419. // Needs to be before binding to prevent changing the aspect ratio.
  70420. var camera;
  70421. if (this.activeCamera) {
  70422. camera = this.activeCamera;
  70423. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70424. if (this.activeCamera !== scene.activeCamera) {
  70425. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  70426. }
  70427. }
  70428. else {
  70429. camera = scene.activeCamera;
  70430. if (camera) {
  70431. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70432. }
  70433. }
  70434. // Prepare renderingManager
  70435. this._renderingManager.reset();
  70436. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  70437. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  70438. var sceneRenderId = scene.getRenderId();
  70439. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  70440. var mesh = currentRenderList[meshIndex];
  70441. if (mesh) {
  70442. if (!mesh.isReady(this.refreshRate === 0)) {
  70443. this.resetRefreshCounter();
  70444. continue;
  70445. }
  70446. mesh._preActivateForIntermediateRendering(sceneRenderId);
  70447. var isMasked = void 0;
  70448. if (!this.renderList && camera) {
  70449. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  70450. }
  70451. else {
  70452. isMasked = false;
  70453. }
  70454. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  70455. mesh._activate(sceneRenderId);
  70456. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  70457. var subMesh = mesh.subMeshes[subIndex];
  70458. scene._activeIndices.addCount(subMesh.indexCount, false);
  70459. this._renderingManager.dispatch(subMesh, mesh);
  70460. }
  70461. }
  70462. }
  70463. }
  70464. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  70465. var particleSystem = scene.particleSystems[particleIndex];
  70466. var emitter = particleSystem.emitter;
  70467. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  70468. continue;
  70469. }
  70470. if (currentRenderList.indexOf(emitter) >= 0) {
  70471. this._renderingManager.dispatchParticles(particleSystem);
  70472. }
  70473. }
  70474. if (this.isCube) {
  70475. for (var face = 0; face < 6; face++) {
  70476. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70477. scene.incrementRenderId();
  70478. scene.resetCachedMaterial();
  70479. }
  70480. }
  70481. else {
  70482. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70483. }
  70484. this.onAfterUnbindObservable.notifyObservers(this);
  70485. if (scene.activeCamera) {
  70486. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  70487. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  70488. }
  70489. engine.setViewport(scene.activeCamera.viewport);
  70490. }
  70491. scene.resetCachedMaterial();
  70492. };
  70493. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  70494. var minimum = 128;
  70495. var x = renderDimension * scale;
  70496. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  70497. // Ensure we don't exceed the render dimension (while staying POT)
  70498. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  70499. };
  70500. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70501. var _this = this;
  70502. if (!this._texture) {
  70503. return;
  70504. }
  70505. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  70506. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70507. });
  70508. };
  70509. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  70510. var scene = this.getScene();
  70511. if (!scene) {
  70512. return;
  70513. }
  70514. var engine = scene.getEngine();
  70515. if (!this._texture) {
  70516. return;
  70517. }
  70518. // Bind
  70519. if (this._postProcessManager) {
  70520. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  70521. }
  70522. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  70523. if (this._texture) {
  70524. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  70525. }
  70526. }
  70527. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  70528. // Clear
  70529. if (this.onClearObservable.hasObservers()) {
  70530. this.onClearObservable.notifyObservers(engine);
  70531. }
  70532. else {
  70533. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  70534. }
  70535. if (!this._doNotChangeAspectRatio) {
  70536. scene.updateTransformMatrix(true);
  70537. }
  70538. // Render
  70539. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  70540. if (this._postProcessManager) {
  70541. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  70542. }
  70543. else if (useCameraPostProcess) {
  70544. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  70545. }
  70546. if (!this._doNotChangeAspectRatio) {
  70547. scene.updateTransformMatrix(true);
  70548. }
  70549. // Dump ?
  70550. if (dumpForDebug) {
  70551. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  70552. }
  70553. // Unbind
  70554. if (!this.isCube || faceIndex === 5) {
  70555. if (this.isCube) {
  70556. if (faceIndex === 5) {
  70557. engine.generateMipMapsForCubemap(this._texture);
  70558. }
  70559. }
  70560. this.unbindFrameBuffer(engine, faceIndex);
  70561. }
  70562. else {
  70563. this.onAfterRenderObservable.notifyObservers(faceIndex);
  70564. }
  70565. };
  70566. /**
  70567. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  70568. * This allowed control for front to back rendering or reversly depending of the special needs.
  70569. *
  70570. * @param renderingGroupId The rendering group id corresponding to its index
  70571. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  70572. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  70573. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  70574. */
  70575. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  70576. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  70577. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  70578. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  70579. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  70580. };
  70581. /**
  70582. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70583. *
  70584. * @param renderingGroupId The rendering group id corresponding to its index
  70585. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70586. */
  70587. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70588. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70589. this._renderingManager._useSceneAutoClearSetup = false;
  70590. };
  70591. RenderTargetTexture.prototype.clone = function () {
  70592. var textureSize = this.getSize();
  70593. 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);
  70594. // Base texture
  70595. newTexture.hasAlpha = this.hasAlpha;
  70596. newTexture.level = this.level;
  70597. // RenderTarget Texture
  70598. newTexture.coordinatesMode = this.coordinatesMode;
  70599. if (this.renderList) {
  70600. newTexture.renderList = this.renderList.slice(0);
  70601. }
  70602. return newTexture;
  70603. };
  70604. RenderTargetTexture.prototype.serialize = function () {
  70605. if (!this.name) {
  70606. return null;
  70607. }
  70608. var serializationObject = _super.prototype.serialize.call(this);
  70609. serializationObject.renderTargetSize = this.getRenderSize();
  70610. serializationObject.renderList = [];
  70611. if (this.renderList) {
  70612. for (var index = 0; index < this.renderList.length; index++) {
  70613. serializationObject.renderList.push(this.renderList[index].id);
  70614. }
  70615. }
  70616. return serializationObject;
  70617. };
  70618. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  70619. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  70620. var objBuffer = this.getInternalTexture();
  70621. var scene = this.getScene();
  70622. if (objBuffer && scene) {
  70623. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  70624. }
  70625. };
  70626. RenderTargetTexture.prototype.dispose = function () {
  70627. if (this._postProcessManager) {
  70628. this._postProcessManager.dispose();
  70629. this._postProcessManager = null;
  70630. }
  70631. this.clearPostProcesses(true);
  70632. if (this._resizeObserver) {
  70633. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  70634. this._resizeObserver = null;
  70635. }
  70636. this.renderList = null;
  70637. // Remove from custom render targets
  70638. var scene = this.getScene();
  70639. if (!scene) {
  70640. return;
  70641. }
  70642. var index = scene.customRenderTargets.indexOf(this);
  70643. if (index >= 0) {
  70644. scene.customRenderTargets.splice(index, 1);
  70645. }
  70646. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  70647. var camera = _a[_i];
  70648. index = camera.customRenderTargets.indexOf(this);
  70649. if (index >= 0) {
  70650. camera.customRenderTargets.splice(index, 1);
  70651. }
  70652. }
  70653. _super.prototype.dispose.call(this);
  70654. };
  70655. /** @hidden */
  70656. RenderTargetTexture.prototype._rebuild = function () {
  70657. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70658. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70659. }
  70660. if (this._postProcessManager) {
  70661. this._postProcessManager._rebuild();
  70662. }
  70663. };
  70664. /**
  70665. * Clear the info related to rendering groups preventing retention point in material dispose.
  70666. */
  70667. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  70668. if (this._renderingManager) {
  70669. this._renderingManager.freeRenderingGroups();
  70670. }
  70671. };
  70672. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  70673. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  70674. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  70675. return RenderTargetTexture;
  70676. }(BABYLON.Texture));
  70677. BABYLON.RenderTargetTexture = RenderTargetTexture;
  70678. })(BABYLON || (BABYLON = {}));
  70679. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  70680. var BABYLON;
  70681. (function (BABYLON) {
  70682. ;
  70683. var MultiRenderTarget = /** @class */ (function (_super) {
  70684. __extends(MultiRenderTarget, _super);
  70685. function MultiRenderTarget(name, size, count, scene, options) {
  70686. var _this = this;
  70687. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  70688. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  70689. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  70690. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  70691. _this._engine = scene.getEngine();
  70692. if (!_this.isSupported) {
  70693. _this.dispose();
  70694. return;
  70695. }
  70696. var types = [];
  70697. var samplingModes = [];
  70698. for (var i = 0; i < count; i++) {
  70699. if (options && options.types && options.types[i] !== undefined) {
  70700. types.push(options.types[i]);
  70701. }
  70702. else {
  70703. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70704. }
  70705. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  70706. samplingModes.push(options.samplingModes[i]);
  70707. }
  70708. else {
  70709. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70710. }
  70711. }
  70712. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  70713. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  70714. _this._size = size;
  70715. _this._multiRenderTargetOptions = {
  70716. samplingModes: samplingModes,
  70717. generateMipMaps: generateMipMaps,
  70718. generateDepthBuffer: generateDepthBuffer,
  70719. generateStencilBuffer: generateStencilBuffer,
  70720. generateDepthTexture: generateDepthTexture,
  70721. types: types,
  70722. textureCount: count
  70723. };
  70724. _this._createInternalTextures();
  70725. _this._createTextures();
  70726. return _this;
  70727. }
  70728. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  70729. get: function () {
  70730. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  70731. },
  70732. enumerable: true,
  70733. configurable: true
  70734. });
  70735. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  70736. get: function () {
  70737. return this._textures;
  70738. },
  70739. enumerable: true,
  70740. configurable: true
  70741. });
  70742. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  70743. get: function () {
  70744. return this._textures[this._textures.length - 1];
  70745. },
  70746. enumerable: true,
  70747. configurable: true
  70748. });
  70749. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  70750. set: function (wrap) {
  70751. if (this._textures) {
  70752. for (var i = 0; i < this._textures.length; i++) {
  70753. this._textures[i].wrapU = wrap;
  70754. }
  70755. }
  70756. },
  70757. enumerable: true,
  70758. configurable: true
  70759. });
  70760. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  70761. set: function (wrap) {
  70762. if (this._textures) {
  70763. for (var i = 0; i < this._textures.length; i++) {
  70764. this._textures[i].wrapV = wrap;
  70765. }
  70766. }
  70767. },
  70768. enumerable: true,
  70769. configurable: true
  70770. });
  70771. /** @hidden */
  70772. MultiRenderTarget.prototype._rebuild = function () {
  70773. this.releaseInternalTextures();
  70774. this._createInternalTextures();
  70775. for (var i = 0; i < this._internalTextures.length; i++) {
  70776. var texture = this._textures[i];
  70777. texture._texture = this._internalTextures[i];
  70778. }
  70779. // Keeps references to frame buffer and stencil/depth buffer
  70780. this._texture = this._internalTextures[0];
  70781. };
  70782. MultiRenderTarget.prototype._createInternalTextures = function () {
  70783. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  70784. };
  70785. MultiRenderTarget.prototype._createTextures = function () {
  70786. this._textures = [];
  70787. for (var i = 0; i < this._internalTextures.length; i++) {
  70788. var texture = new BABYLON.Texture(null, this.getScene());
  70789. texture._texture = this._internalTextures[i];
  70790. this._textures.push(texture);
  70791. }
  70792. // Keeps references to frame buffer and stencil/depth buffer
  70793. this._texture = this._internalTextures[0];
  70794. };
  70795. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  70796. get: function () {
  70797. return this._samples;
  70798. },
  70799. set: function (value) {
  70800. if (this._samples === value) {
  70801. return;
  70802. }
  70803. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  70804. },
  70805. enumerable: true,
  70806. configurable: true
  70807. });
  70808. MultiRenderTarget.prototype.resize = function (size) {
  70809. this.releaseInternalTextures();
  70810. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  70811. this._createInternalTextures();
  70812. };
  70813. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70814. var _this = this;
  70815. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  70816. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70817. });
  70818. };
  70819. MultiRenderTarget.prototype.dispose = function () {
  70820. this.releaseInternalTextures();
  70821. _super.prototype.dispose.call(this);
  70822. };
  70823. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  70824. if (!this._internalTextures) {
  70825. return;
  70826. }
  70827. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  70828. if (this._internalTextures[i] !== undefined) {
  70829. this._internalTextures[i].dispose();
  70830. this._internalTextures.splice(i, 1);
  70831. }
  70832. }
  70833. };
  70834. return MultiRenderTarget;
  70835. }(BABYLON.RenderTargetTexture));
  70836. BABYLON.MultiRenderTarget = MultiRenderTarget;
  70837. })(BABYLON || (BABYLON = {}));
  70838. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  70839. var BABYLON;
  70840. (function (BABYLON) {
  70841. var MirrorTexture = /** @class */ (function (_super) {
  70842. __extends(MirrorTexture, _super);
  70843. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  70844. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70846. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70847. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  70848. _this.scene = scene;
  70849. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  70850. _this._transformMatrix = BABYLON.Matrix.Zero();
  70851. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  70852. _this._adaptiveBlurKernel = 0;
  70853. _this._blurKernelX = 0;
  70854. _this._blurKernelY = 0;
  70855. _this._blurRatio = 1.0;
  70856. _this.ignoreCameraViewport = true;
  70857. _this._updateGammaSpace();
  70858. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70859. _this._updateGammaSpace;
  70860. });
  70861. _this.onBeforeRenderObservable.add(function () {
  70862. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  70863. _this._savedViewMatrix = scene.getViewMatrix();
  70864. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  70865. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  70866. scene.clipPlane = _this.mirrorPlane;
  70867. scene.getEngine().cullBackFaces = false;
  70868. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  70869. });
  70870. _this.onAfterRenderObservable.add(function () {
  70871. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  70872. scene.getEngine().cullBackFaces = true;
  70873. scene._mirroredCameraPosition = null;
  70874. delete scene.clipPlane;
  70875. });
  70876. return _this;
  70877. }
  70878. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  70879. get: function () {
  70880. return this._blurRatio;
  70881. },
  70882. set: function (value) {
  70883. if (this._blurRatio === value) {
  70884. return;
  70885. }
  70886. this._blurRatio = value;
  70887. this._preparePostProcesses();
  70888. },
  70889. enumerable: true,
  70890. configurable: true
  70891. });
  70892. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  70893. set: function (value) {
  70894. this._adaptiveBlurKernel = value;
  70895. this._autoComputeBlurKernel();
  70896. },
  70897. enumerable: true,
  70898. configurable: true
  70899. });
  70900. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  70901. set: function (value) {
  70902. this.blurKernelX = value;
  70903. this.blurKernelY = value;
  70904. },
  70905. enumerable: true,
  70906. configurable: true
  70907. });
  70908. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  70909. get: function () {
  70910. return this._blurKernelX;
  70911. },
  70912. set: function (value) {
  70913. if (this._blurKernelX === value) {
  70914. return;
  70915. }
  70916. this._blurKernelX = value;
  70917. this._preparePostProcesses();
  70918. },
  70919. enumerable: true,
  70920. configurable: true
  70921. });
  70922. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  70923. get: function () {
  70924. return this._blurKernelY;
  70925. },
  70926. set: function (value) {
  70927. if (this._blurKernelY === value) {
  70928. return;
  70929. }
  70930. this._blurKernelY = value;
  70931. this._preparePostProcesses();
  70932. },
  70933. enumerable: true,
  70934. configurable: true
  70935. });
  70936. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  70937. var engine = this.getScene().getEngine();
  70938. var dw = this.getRenderWidth() / engine.getRenderWidth();
  70939. var dh = this.getRenderHeight() / engine.getRenderHeight();
  70940. this.blurKernelX = this._adaptiveBlurKernel * dw;
  70941. this.blurKernelY = this._adaptiveBlurKernel * dh;
  70942. };
  70943. MirrorTexture.prototype._onRatioRescale = function () {
  70944. if (this._sizeRatio) {
  70945. this.resize(this._initialSizeParameter);
  70946. if (!this._adaptiveBlurKernel) {
  70947. this._preparePostProcesses();
  70948. }
  70949. }
  70950. if (this._adaptiveBlurKernel) {
  70951. this._autoComputeBlurKernel();
  70952. }
  70953. };
  70954. MirrorTexture.prototype._updateGammaSpace = function () {
  70955. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  70956. };
  70957. MirrorTexture.prototype._preparePostProcesses = function () {
  70958. this.clearPostProcesses(true);
  70959. if (this._blurKernelX && this._blurKernelY) {
  70960. var engine = this.getScene().getEngine();
  70961. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70962. 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);
  70963. this._blurX.autoClear = false;
  70964. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  70965. this._blurX.inputTexture = this._texture;
  70966. }
  70967. else {
  70968. this._blurX.alwaysForcePOT = true;
  70969. }
  70970. 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);
  70971. this._blurY.autoClear = false;
  70972. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  70973. this.addPostProcess(this._blurX);
  70974. this.addPostProcess(this._blurY);
  70975. }
  70976. else {
  70977. if (this._blurY) {
  70978. this.removePostProcess(this._blurY);
  70979. this._blurY.dispose();
  70980. this._blurY = null;
  70981. }
  70982. if (this._blurX) {
  70983. this.removePostProcess(this._blurX);
  70984. this._blurX.dispose();
  70985. this._blurX = null;
  70986. }
  70987. }
  70988. };
  70989. MirrorTexture.prototype.clone = function () {
  70990. var scene = this.getScene();
  70991. if (!scene) {
  70992. return this;
  70993. }
  70994. var textureSize = this.getSize();
  70995. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  70996. // Base texture
  70997. newTexture.hasAlpha = this.hasAlpha;
  70998. newTexture.level = this.level;
  70999. // Mirror Texture
  71000. newTexture.mirrorPlane = this.mirrorPlane.clone();
  71001. if (this.renderList) {
  71002. newTexture.renderList = this.renderList.slice(0);
  71003. }
  71004. return newTexture;
  71005. };
  71006. MirrorTexture.prototype.serialize = function () {
  71007. if (!this.name) {
  71008. return null;
  71009. }
  71010. var serializationObject = _super.prototype.serialize.call(this);
  71011. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  71012. return serializationObject;
  71013. };
  71014. MirrorTexture.prototype.dispose = function () {
  71015. _super.prototype.dispose.call(this);
  71016. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  71017. };
  71018. return MirrorTexture;
  71019. }(BABYLON.RenderTargetTexture));
  71020. BABYLON.MirrorTexture = MirrorTexture;
  71021. })(BABYLON || (BABYLON = {}));
  71022. //# sourceMappingURL=babylon.mirrorTexture.js.map
  71023. var BABYLON;
  71024. (function (BABYLON) {
  71025. /**
  71026. * Creates a refraction texture used by refraction channel of the standard material.
  71027. * @param name the texture name
  71028. * @param size size of the underlying texture
  71029. * @param scene root scene
  71030. */
  71031. var RefractionTexture = /** @class */ (function (_super) {
  71032. __extends(RefractionTexture, _super);
  71033. function RefractionTexture(name, size, scene, generateMipMaps) {
  71034. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  71035. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  71036. _this.depth = 2.0;
  71037. _this.onBeforeRenderObservable.add(function () {
  71038. scene.clipPlane = _this.refractionPlane;
  71039. });
  71040. _this.onAfterRenderObservable.add(function () {
  71041. delete scene.clipPlane;
  71042. });
  71043. return _this;
  71044. }
  71045. RefractionTexture.prototype.clone = function () {
  71046. var scene = this.getScene();
  71047. if (!scene) {
  71048. return this;
  71049. }
  71050. var textureSize = this.getSize();
  71051. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  71052. // Base texture
  71053. newTexture.hasAlpha = this.hasAlpha;
  71054. newTexture.level = this.level;
  71055. // Refraction Texture
  71056. newTexture.refractionPlane = this.refractionPlane.clone();
  71057. if (this.renderList) {
  71058. newTexture.renderList = this.renderList.slice(0);
  71059. }
  71060. newTexture.depth = this.depth;
  71061. return newTexture;
  71062. };
  71063. RefractionTexture.prototype.serialize = function () {
  71064. if (!this.name) {
  71065. return null;
  71066. }
  71067. var serializationObject = _super.prototype.serialize.call(this);
  71068. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  71069. serializationObject.depth = this.depth;
  71070. return serializationObject;
  71071. };
  71072. return RefractionTexture;
  71073. }(BABYLON.RenderTargetTexture));
  71074. BABYLON.RefractionTexture = RefractionTexture;
  71075. })(BABYLON || (BABYLON = {}));
  71076. //# sourceMappingURL=babylon.refractionTexture.js.map
  71077. var BABYLON;
  71078. (function (BABYLON) {
  71079. /**
  71080. * A class extending {BABYLON.Texture} allowing drawing on a texture
  71081. * @see http://doc.babylonjs.com/how_to/dynamictexture
  71082. */
  71083. var DynamicTexture = /** @class */ (function (_super) {
  71084. __extends(DynamicTexture, _super);
  71085. /**
  71086. * Creates a {BABYLON.DynamicTexture}
  71087. * @param name defines the name of the texture
  71088. * @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
  71089. * @param scene defines the scene where you want the texture
  71090. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  71091. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  71092. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  71093. */
  71094. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  71095. if (scene === void 0) { scene = null; }
  71096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71097. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71098. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  71099. _this.name = name;
  71100. _this._engine = _this.getScene().getEngine();
  71101. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71102. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71103. _this._generateMipMaps = generateMipMaps;
  71104. if (options.getContext) {
  71105. _this._canvas = options;
  71106. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  71107. }
  71108. else {
  71109. _this._canvas = document.createElement("canvas");
  71110. if (options.width || options.width === 0) {
  71111. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  71112. }
  71113. else {
  71114. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  71115. }
  71116. }
  71117. var textureSize = _this.getSize();
  71118. _this._canvas.width = textureSize.width;
  71119. _this._canvas.height = textureSize.height;
  71120. _this._context = _this._canvas.getContext("2d");
  71121. return _this;
  71122. }
  71123. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  71124. /**
  71125. * Gets the current state of canRescale
  71126. */
  71127. get: function () {
  71128. return true;
  71129. },
  71130. enumerable: true,
  71131. configurable: true
  71132. });
  71133. DynamicTexture.prototype._recreate = function (textureSize) {
  71134. this._canvas.width = textureSize.width;
  71135. this._canvas.height = textureSize.height;
  71136. this.releaseInternalTexture();
  71137. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  71138. };
  71139. /**
  71140. * Scales the texture
  71141. * @param ratio the scale factor to apply to both width and height
  71142. */
  71143. DynamicTexture.prototype.scale = function (ratio) {
  71144. var textureSize = this.getSize();
  71145. textureSize.width *= ratio;
  71146. textureSize.height *= ratio;
  71147. this._recreate(textureSize);
  71148. };
  71149. /**
  71150. * Resizes the texture
  71151. * @param width the new width
  71152. * @param height the new height
  71153. */
  71154. DynamicTexture.prototype.scaleTo = function (width, height) {
  71155. var textureSize = this.getSize();
  71156. textureSize.width = width;
  71157. textureSize.height = height;
  71158. this._recreate(textureSize);
  71159. };
  71160. /**
  71161. * Gets the context of the canvas used by the texture
  71162. * @returns the canvas context of the dynamic texture
  71163. */
  71164. DynamicTexture.prototype.getContext = function () {
  71165. return this._context;
  71166. };
  71167. /**
  71168. * Clears the texture
  71169. */
  71170. DynamicTexture.prototype.clear = function () {
  71171. var size = this.getSize();
  71172. this._context.fillRect(0, 0, size.width, size.height);
  71173. };
  71174. /**
  71175. * Updates the texture
  71176. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  71177. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  71178. */
  71179. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  71180. if (premulAlpha === void 0) { premulAlpha = false; }
  71181. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  71182. };
  71183. /**
  71184. * Draws text onto the texture
  71185. * @param text defines the text to be drawn
  71186. * @param x defines the placement of the text from the left
  71187. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  71188. * @param font defines the font to be used with font-style, font-size, font-name
  71189. * @param color defines the color used for the text
  71190. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  71191. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  71192. * @param update defines whether texture is immediately update (default is true)
  71193. */
  71194. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  71195. if (update === void 0) { update = true; }
  71196. var size = this.getSize();
  71197. if (clearColor) {
  71198. this._context.fillStyle = clearColor;
  71199. this._context.fillRect(0, 0, size.width, size.height);
  71200. }
  71201. this._context.font = font;
  71202. if (x === null || x === undefined) {
  71203. var textSize = this._context.measureText(text);
  71204. x = (size.width - textSize.width) / 2;
  71205. }
  71206. if (y === null || y === undefined) {
  71207. var fontSize = parseInt((font.replace(/\D/g, '')));
  71208. y = (size.height / 2) + (fontSize / 3.65);
  71209. }
  71210. this._context.fillStyle = color;
  71211. this._context.fillText(text, x, y);
  71212. if (update) {
  71213. this.update(invertY);
  71214. }
  71215. };
  71216. /**
  71217. * Clones the texture
  71218. * @returns the clone of the texture.
  71219. */
  71220. DynamicTexture.prototype.clone = function () {
  71221. var scene = this.getScene();
  71222. if (!scene) {
  71223. return this;
  71224. }
  71225. var textureSize = this.getSize();
  71226. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  71227. // Base texture
  71228. newTexture.hasAlpha = this.hasAlpha;
  71229. newTexture.level = this.level;
  71230. // Dynamic Texture
  71231. newTexture.wrapU = this.wrapU;
  71232. newTexture.wrapV = this.wrapV;
  71233. return newTexture;
  71234. };
  71235. /**
  71236. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  71237. * @returns a serialized dynamic texture object
  71238. */
  71239. DynamicTexture.prototype.serialize = function () {
  71240. var scene = this.getScene();
  71241. if (scene && !scene.isReady()) {
  71242. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  71243. }
  71244. var serializationObject = _super.prototype.serialize.call(this);
  71245. serializationObject.base64String = this._canvas.toDataURL();
  71246. serializationObject.invertY = this._invertY;
  71247. serializationObject.samplingMode = this.samplingMode;
  71248. return serializationObject;
  71249. };
  71250. /** @hidden */
  71251. DynamicTexture.prototype._rebuild = function () {
  71252. this.update();
  71253. };
  71254. return DynamicTexture;
  71255. }(BABYLON.Texture));
  71256. BABYLON.DynamicTexture = DynamicTexture;
  71257. })(BABYLON || (BABYLON = {}));
  71258. //# sourceMappingURL=babylon.dynamicTexture.js.map
  71259. var BABYLON;
  71260. (function (BABYLON) {
  71261. var VideoTexture = /** @class */ (function (_super) {
  71262. __extends(VideoTexture, _super);
  71263. /**
  71264. * Creates a video texture.
  71265. * Sample : https://doc.babylonjs.com/how_to/video_texture
  71266. * @param {string | null} name optional name, will detect from video source, if not defined
  71267. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  71268. * @param {BABYLON.Scene} scene is obviously the current scene.
  71269. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  71270. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  71271. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  71272. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  71273. */
  71274. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  71275. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71276. if (invertY === void 0) { invertY = false; }
  71277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71278. if (settings === void 0) { settings = {
  71279. autoPlay: true,
  71280. loop: true,
  71281. autoUpdateTexture: true,
  71282. }; }
  71283. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71284. _this._onUserActionRequestedObservable = null;
  71285. _this._stillImageCaptured = false;
  71286. _this._poster = false;
  71287. _this._createInternalTexture = function () {
  71288. if (_this._texture != null) {
  71289. if (_this._poster) {
  71290. _this._texture.dispose();
  71291. _this._poster = false;
  71292. }
  71293. else {
  71294. return;
  71295. }
  71296. }
  71297. if (!_this._engine.needPOTTextures ||
  71298. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  71299. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71300. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71301. }
  71302. else {
  71303. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71304. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71305. _this._generateMipMaps = false;
  71306. }
  71307. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  71308. if (!_this.video.autoplay) {
  71309. var oldHandler_1 = _this.video.onplaying;
  71310. var error_1 = false;
  71311. _this.video.onplaying = function () {
  71312. _this.video.onplaying = oldHandler_1;
  71313. _this._texture.isReady = true;
  71314. _this._updateInternalTexture();
  71315. if (!error_1) {
  71316. _this.video.pause();
  71317. }
  71318. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71319. _this.onLoadObservable.notifyObservers(_this);
  71320. }
  71321. };
  71322. var playing = _this.video.play();
  71323. if (playing) {
  71324. playing.then(function () {
  71325. // Everything is good.
  71326. })
  71327. .catch(function () {
  71328. error_1 = true;
  71329. // On Chrome for instance, new policies might prevent playing without user interaction.
  71330. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  71331. _this._onUserActionRequestedObservable.notifyObservers(_this);
  71332. }
  71333. });
  71334. }
  71335. else {
  71336. _this.video.onplaying = oldHandler_1;
  71337. _this._texture.isReady = true;
  71338. _this._updateInternalTexture();
  71339. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71340. _this.onLoadObservable.notifyObservers(_this);
  71341. }
  71342. }
  71343. }
  71344. else {
  71345. _this._texture.isReady = true;
  71346. _this._updateInternalTexture();
  71347. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71348. _this.onLoadObservable.notifyObservers(_this);
  71349. }
  71350. }
  71351. };
  71352. _this.reset = function () {
  71353. if (_this._texture == null) {
  71354. return;
  71355. }
  71356. if (!_this._poster) {
  71357. _this._texture.dispose();
  71358. _this._texture = null;
  71359. }
  71360. };
  71361. _this._updateInternalTexture = function (e) {
  71362. if (_this._texture == null || !_this._texture.isReady) {
  71363. return;
  71364. }
  71365. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  71366. return;
  71367. }
  71368. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  71369. };
  71370. _this._engine = _this.getScene().getEngine();
  71371. _this._generateMipMaps = generateMipMaps;
  71372. _this._samplingMode = samplingMode;
  71373. _this.autoUpdateTexture = settings.autoUpdateTexture;
  71374. _this.name = name || _this._getName(src);
  71375. _this.video = _this._getVideo(src);
  71376. if (settings.poster) {
  71377. _this.video.poster = settings.poster;
  71378. }
  71379. if (settings.autoPlay !== undefined) {
  71380. _this.video.autoplay = settings.autoPlay;
  71381. }
  71382. if (settings.loop !== undefined) {
  71383. _this.video.loop = settings.loop;
  71384. }
  71385. _this.video.setAttribute("playsinline", "");
  71386. _this.video.addEventListener("canplay", _this._createInternalTexture);
  71387. _this.video.addEventListener("paused", _this._updateInternalTexture);
  71388. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  71389. _this.video.addEventListener("emptied", _this.reset);
  71390. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  71391. _this._createInternalTexture();
  71392. }
  71393. if (settings.poster) {
  71394. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  71395. _this._poster = true;
  71396. }
  71397. return _this;
  71398. }
  71399. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  71400. get: function () {
  71401. if (!this._onUserActionRequestedObservable) {
  71402. this._onUserActionRequestedObservable = new BABYLON.Observable();
  71403. }
  71404. return this._onUserActionRequestedObservable;
  71405. },
  71406. enumerable: true,
  71407. configurable: true
  71408. });
  71409. VideoTexture.prototype._getName = function (src) {
  71410. if (src instanceof HTMLVideoElement) {
  71411. return src.currentSrc;
  71412. }
  71413. if (typeof src === "object") {
  71414. return src.toString();
  71415. }
  71416. return src;
  71417. };
  71418. ;
  71419. VideoTexture.prototype._getVideo = function (src) {
  71420. if (src instanceof HTMLVideoElement) {
  71421. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  71422. return src;
  71423. }
  71424. var video = document.createElement("video");
  71425. if (typeof src === "string") {
  71426. BABYLON.Tools.SetCorsBehavior(src, video);
  71427. video.src = src;
  71428. }
  71429. else {
  71430. BABYLON.Tools.SetCorsBehavior(src[0], video);
  71431. src.forEach(function (url) {
  71432. var source = document.createElement("source");
  71433. source.src = url;
  71434. video.appendChild(source);
  71435. });
  71436. }
  71437. return video;
  71438. };
  71439. ;
  71440. /**
  71441. * @hidden Internal method to initiate `update`.
  71442. */
  71443. VideoTexture.prototype._rebuild = function () {
  71444. this.update();
  71445. };
  71446. /**
  71447. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  71448. */
  71449. VideoTexture.prototype.update = function () {
  71450. if (!this.autoUpdateTexture) {
  71451. // Expecting user to call `updateTexture` manually
  71452. return;
  71453. }
  71454. this.updateTexture(true);
  71455. };
  71456. /**
  71457. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  71458. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  71459. */
  71460. VideoTexture.prototype.updateTexture = function (isVisible) {
  71461. if (!isVisible) {
  71462. return;
  71463. }
  71464. if (this.video.paused && this._stillImageCaptured) {
  71465. return;
  71466. }
  71467. this._stillImageCaptured = true;
  71468. this._updateInternalTexture();
  71469. };
  71470. /**
  71471. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  71472. * @param url New url.
  71473. */
  71474. VideoTexture.prototype.updateURL = function (url) {
  71475. this.video.src = url;
  71476. };
  71477. VideoTexture.prototype.dispose = function () {
  71478. _super.prototype.dispose.call(this);
  71479. if (this._onUserActionRequestedObservable) {
  71480. this._onUserActionRequestedObservable.clear();
  71481. this._onUserActionRequestedObservable = null;
  71482. }
  71483. this.video.removeEventListener("canplay", this._createInternalTexture);
  71484. this.video.removeEventListener("paused", this._updateInternalTexture);
  71485. this.video.removeEventListener("seeked", this._updateInternalTexture);
  71486. this.video.removeEventListener("emptied", this.reset);
  71487. this.video.pause();
  71488. };
  71489. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  71490. var video = document.createElement("video");
  71491. video.setAttribute('autoplay', '');
  71492. video.setAttribute('muted', '');
  71493. video.setAttribute('playsinline', '');
  71494. var constraintsDeviceId;
  71495. if (constraints && constraints.deviceId) {
  71496. constraintsDeviceId = {
  71497. exact: constraints.deviceId,
  71498. };
  71499. }
  71500. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  71501. if (navigator.mediaDevices) {
  71502. navigator.mediaDevices.getUserMedia({ video: constraints })
  71503. .then(function (stream) {
  71504. if (video.mozSrcObject !== undefined) {
  71505. // hack for Firefox < 19
  71506. video.mozSrcObject = stream;
  71507. }
  71508. else {
  71509. video.srcObject = stream;
  71510. }
  71511. var onPlaying = function () {
  71512. if (onReady) {
  71513. onReady(new VideoTexture("video", video, scene, true, true));
  71514. }
  71515. video.removeEventListener("playing", onPlaying);
  71516. };
  71517. video.addEventListener("playing", onPlaying);
  71518. video.play();
  71519. })
  71520. .catch(function (err) {
  71521. BABYLON.Tools.Error(err.name);
  71522. });
  71523. }
  71524. else {
  71525. navigator.getUserMedia =
  71526. navigator.getUserMedia ||
  71527. navigator.webkitGetUserMedia ||
  71528. navigator.mozGetUserMedia ||
  71529. navigator.msGetUserMedia;
  71530. if (navigator.getUserMedia) {
  71531. navigator.getUserMedia({
  71532. video: {
  71533. deviceId: constraintsDeviceId,
  71534. width: {
  71535. min: (constraints && constraints.minWidth) || 256,
  71536. max: (constraints && constraints.maxWidth) || 640,
  71537. },
  71538. height: {
  71539. min: (constraints && constraints.minHeight) || 256,
  71540. max: (constraints && constraints.maxHeight) || 480,
  71541. },
  71542. },
  71543. }, function (stream) {
  71544. if (video.mozSrcObject !== undefined) {
  71545. // hack for Firefox < 19
  71546. video.mozSrcObject = stream;
  71547. }
  71548. else {
  71549. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  71550. }
  71551. video.play();
  71552. if (onReady) {
  71553. onReady(new VideoTexture("video", video, scene, true, true));
  71554. }
  71555. }, function (e) {
  71556. BABYLON.Tools.Error(e.name);
  71557. });
  71558. }
  71559. }
  71560. };
  71561. return VideoTexture;
  71562. }(BABYLON.Texture));
  71563. BABYLON.VideoTexture = VideoTexture;
  71564. })(BABYLON || (BABYLON = {}));
  71565. //# sourceMappingURL=babylon.videoTexture.js.map
  71566. var BABYLON;
  71567. (function (BABYLON) {
  71568. var RawTexture = /** @class */ (function (_super) {
  71569. __extends(RawTexture, _super);
  71570. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  71571. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71572. if (invertY === void 0) { invertY = false; }
  71573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71574. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71575. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71576. _this.format = format;
  71577. _this._engine = scene.getEngine();
  71578. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  71579. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71580. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71581. return _this;
  71582. }
  71583. RawTexture.prototype.update = function (data) {
  71584. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71585. };
  71586. // Statics
  71587. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71588. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71589. if (invertY === void 0) { invertY = false; }
  71590. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71591. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  71592. };
  71593. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71594. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71595. if (invertY === void 0) { invertY = false; }
  71596. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71597. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71598. };
  71599. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71600. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71601. if (invertY === void 0) { invertY = false; }
  71602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71603. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71604. };
  71605. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71606. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71607. if (invertY === void 0) { invertY = false; }
  71608. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71609. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71610. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  71611. };
  71612. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71613. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71614. if (invertY === void 0) { invertY = false; }
  71615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71616. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71617. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  71618. };
  71619. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71620. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71621. if (invertY === void 0) { invertY = false; }
  71622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71623. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71624. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  71625. };
  71626. return RawTexture;
  71627. }(BABYLON.Texture));
  71628. BABYLON.RawTexture = RawTexture;
  71629. })(BABYLON || (BABYLON = {}));
  71630. //# sourceMappingURL=babylon.rawTexture.js.map
  71631. var BABYLON;
  71632. (function (BABYLON) {
  71633. /**
  71634. * Class used to store 3D textures containing user data
  71635. */
  71636. var RawTexture3D = /** @class */ (function (_super) {
  71637. __extends(RawTexture3D, _super);
  71638. /**
  71639. * Create a new RawTexture3D
  71640. * @param data defines the data of the texture
  71641. * @param width defines the width of the texture
  71642. * @param height defines the height of the texture
  71643. * @param depth defines the depth of the texture
  71644. * @param format defines the texture format to use
  71645. * @param scene defines the hosting scene
  71646. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  71647. * @param invertY defines if texture must be stored with Y axis inverted
  71648. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  71649. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  71650. */
  71651. function RawTexture3D(data, width, height, depth,
  71652. /** Gets or sets the texture format to use */
  71653. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  71654. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71655. if (invertY === void 0) { invertY = false; }
  71656. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71657. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71658. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71659. _this.format = format;
  71660. _this._engine = scene.getEngine();
  71661. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  71662. _this.is3D = true;
  71663. return _this;
  71664. }
  71665. /**
  71666. * Update the texture with new data
  71667. * @param data defines the data to store in the texture
  71668. */
  71669. RawTexture3D.prototype.update = function (data) {
  71670. if (!this._texture) {
  71671. return;
  71672. }
  71673. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71674. };
  71675. return RawTexture3D;
  71676. }(BABYLON.Texture));
  71677. BABYLON.RawTexture3D = RawTexture3D;
  71678. })(BABYLON || (BABYLON = {}));
  71679. //# sourceMappingURL=babylon.rawTexture3D.js.map
  71680. var BABYLON;
  71681. (function (BABYLON) {
  71682. /**
  71683. * PostProcessManager is used to manage one or more post processes or post process pipelines
  71684. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71685. */
  71686. var PostProcessManager = /** @class */ (function () {
  71687. /**
  71688. * Creates a new instance PostProcess
  71689. * @param scene The scene that the post process is associated with.
  71690. */
  71691. function PostProcessManager(scene) {
  71692. this._vertexBuffers = {};
  71693. this._scene = scene;
  71694. }
  71695. PostProcessManager.prototype._prepareBuffers = function () {
  71696. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  71697. return;
  71698. }
  71699. // VBO
  71700. var vertices = [];
  71701. vertices.push(1, 1);
  71702. vertices.push(-1, 1);
  71703. vertices.push(-1, -1);
  71704. vertices.push(1, -1);
  71705. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71706. this._buildIndexBuffer();
  71707. };
  71708. PostProcessManager.prototype._buildIndexBuffer = function () {
  71709. // Indices
  71710. var indices = [];
  71711. indices.push(0);
  71712. indices.push(1);
  71713. indices.push(2);
  71714. indices.push(0);
  71715. indices.push(2);
  71716. indices.push(3);
  71717. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  71718. };
  71719. /**
  71720. * Rebuilds the vertex buffers of the manager.
  71721. * @hidden
  71722. */
  71723. PostProcessManager.prototype._rebuild = function () {
  71724. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71725. if (!vb) {
  71726. return;
  71727. }
  71728. vb._rebuild();
  71729. this._buildIndexBuffer();
  71730. };
  71731. // Methods
  71732. /**
  71733. * Prepares a frame to be run through a post process.
  71734. * @param sourceTexture The input texture to the post procesess. (default: null)
  71735. * @param postProcesses An array of post processes to be run. (default: null)
  71736. * @returns True if the post processes were able to be run.
  71737. * @hidden
  71738. */
  71739. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  71740. if (sourceTexture === void 0) { sourceTexture = null; }
  71741. if (postProcesses === void 0) { postProcesses = null; }
  71742. var camera = this._scene.activeCamera;
  71743. if (!camera) {
  71744. return false;
  71745. }
  71746. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71747. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71748. return false;
  71749. }
  71750. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  71751. return true;
  71752. };
  71753. /**
  71754. * Manually render a set of post processes to a texture.
  71755. * @param postProcesses An array of post processes to be run.
  71756. * @param targetTexture The target texture to render to.
  71757. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  71758. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  71759. * @param lodLevel defines which lod of the texture to render to
  71760. */
  71761. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  71762. if (targetTexture === void 0) { targetTexture = null; }
  71763. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71764. if (faceIndex === void 0) { faceIndex = 0; }
  71765. if (lodLevel === void 0) { lodLevel = 0; }
  71766. var engine = this._scene.getEngine();
  71767. for (var index = 0; index < postProcesses.length; index++) {
  71768. if (index < postProcesses.length - 1) {
  71769. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  71770. }
  71771. else {
  71772. if (targetTexture) {
  71773. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  71774. }
  71775. else {
  71776. engine.restoreDefaultFramebuffer();
  71777. }
  71778. }
  71779. var pp = postProcesses[index];
  71780. var effect = pp.apply();
  71781. if (effect) {
  71782. pp.onBeforeRenderObservable.notifyObservers(effect);
  71783. // VBOs
  71784. this._prepareBuffers();
  71785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71786. // Draw order
  71787. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71788. pp.onAfterRenderObservable.notifyObservers(effect);
  71789. }
  71790. }
  71791. // Restore depth buffer
  71792. engine.setDepthBuffer(true);
  71793. engine.setDepthWrite(true);
  71794. };
  71795. /**
  71796. * Finalize the result of the output of the postprocesses.
  71797. * @param doNotPresent If true the result will not be displayed to the screen.
  71798. * @param targetTexture The target texture to render to.
  71799. * @param faceIndex The index of the face to bind the target texture to.
  71800. * @param postProcesses The array of post processes to render.
  71801. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  71802. * @hidden
  71803. */
  71804. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  71805. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71806. var camera = this._scene.activeCamera;
  71807. if (!camera) {
  71808. return;
  71809. }
  71810. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71811. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71812. return;
  71813. }
  71814. var engine = this._scene.getEngine();
  71815. for (var index = 0, len = postProcesses.length; index < len; index++) {
  71816. var pp = postProcesses[index];
  71817. if (index < len - 1) {
  71818. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  71819. }
  71820. else {
  71821. if (targetTexture) {
  71822. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  71823. pp._outputTexture = targetTexture;
  71824. }
  71825. else {
  71826. engine.restoreDefaultFramebuffer();
  71827. pp._outputTexture = null;
  71828. }
  71829. }
  71830. if (doNotPresent) {
  71831. break;
  71832. }
  71833. var effect = pp.apply();
  71834. if (effect) {
  71835. pp.onBeforeRenderObservable.notifyObservers(effect);
  71836. // VBOs
  71837. this._prepareBuffers();
  71838. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71839. // Draw order
  71840. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71841. pp.onAfterRenderObservable.notifyObservers(effect);
  71842. }
  71843. }
  71844. // Restore states
  71845. engine.setDepthBuffer(true);
  71846. engine.setDepthWrite(true);
  71847. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71848. };
  71849. /**
  71850. * Disposes of the post process manager.
  71851. */
  71852. PostProcessManager.prototype.dispose = function () {
  71853. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71854. if (buffer) {
  71855. buffer.dispose();
  71856. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71857. }
  71858. if (this._indexBuffer) {
  71859. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71860. this._indexBuffer = null;
  71861. }
  71862. };
  71863. return PostProcessManager;
  71864. }());
  71865. BABYLON.PostProcessManager = PostProcessManager;
  71866. })(BABYLON || (BABYLON = {}));
  71867. //# sourceMappingURL=babylon.postProcessManager.js.map
  71868. var BABYLON;
  71869. (function (BABYLON) {
  71870. /**
  71871. * PostProcess can be used to apply a shader to a texture after it has been rendered
  71872. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71873. */
  71874. var PostProcess = /** @class */ (function () {
  71875. /**
  71876. * Creates a new instance PostProcess
  71877. * @param name The name of the PostProcess.
  71878. * @param fragmentUrl The url of the fragment shader to be used.
  71879. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  71880. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  71881. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  71882. * @param camera The camera to apply the render pass to.
  71883. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71884. * @param engine The engine which the post process will be applied. (default: current engine)
  71885. * @param reusable If the post process can be reused on the same frame. (default: false)
  71886. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  71887. * @param textureType Type of textures used when performing the post process. (default: 0)
  71888. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  71889. * @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
  71890. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  71891. */
  71892. function PostProcess(
  71893. /** Name of the PostProcess. */
  71894. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  71895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  71896. if (defines === void 0) { defines = null; }
  71897. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71898. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  71899. if (blockCompilation === void 0) { blockCompilation = false; }
  71900. this.name = name;
  71901. /**
  71902. * Width of the texture to apply the post process on
  71903. */
  71904. this.width = -1;
  71905. /**
  71906. * Height of the texture to apply the post process on
  71907. */
  71908. this.height = -1;
  71909. /**
  71910. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  71911. * @hidden
  71912. */
  71913. this._outputTexture = null;
  71914. /**
  71915. * If the buffer needs to be cleared before applying the post process. (default: true)
  71916. * Should be set to false if shader will overwrite all previous pixels.
  71917. */
  71918. this.autoClear = true;
  71919. /**
  71920. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  71921. */
  71922. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  71923. /**
  71924. * Animations to be used for the post processing
  71925. */
  71926. this.animations = new Array();
  71927. /**
  71928. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  71929. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  71930. */
  71931. this.enablePixelPerfectMode = false;
  71932. /**
  71933. * Force the postprocess to be applied without taking in account viewport
  71934. */
  71935. this.forceFullscreenViewport = true;
  71936. /**
  71937. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  71938. *
  71939. * | Value | Type | Description |
  71940. * | ----- | ----------------------------------- | ----------- |
  71941. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  71942. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  71943. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  71944. *
  71945. */
  71946. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  71947. /**
  71948. * Force textures to be a power of two (default: false)
  71949. */
  71950. this.alwaysForcePOT = false;
  71951. this._samples = 1;
  71952. /**
  71953. * Modify the scale of the post process to be the same as the viewport (default: false)
  71954. */
  71955. this.adaptScaleToCurrentViewport = false;
  71956. this._reusable = false;
  71957. /**
  71958. * Smart array of input and output textures for the post process.
  71959. * @hidden
  71960. */
  71961. this._textures = new BABYLON.SmartArray(2);
  71962. /**
  71963. * The index in _textures that corresponds to the output texture.
  71964. * @hidden
  71965. */
  71966. this._currentRenderTextureInd = 0;
  71967. this._scaleRatio = new BABYLON.Vector2(1, 1);
  71968. this._texelSize = BABYLON.Vector2.Zero();
  71969. // Events
  71970. /**
  71971. * An event triggered when the postprocess is activated.
  71972. */
  71973. this.onActivateObservable = new BABYLON.Observable();
  71974. /**
  71975. * An event triggered when the postprocess changes its size.
  71976. */
  71977. this.onSizeChangedObservable = new BABYLON.Observable();
  71978. /**
  71979. * An event triggered when the postprocess applies its effect.
  71980. */
  71981. this.onApplyObservable = new BABYLON.Observable();
  71982. /**
  71983. * An event triggered before rendering the postprocess
  71984. */
  71985. this.onBeforeRenderObservable = new BABYLON.Observable();
  71986. /**
  71987. * An event triggered after rendering the postprocess
  71988. */
  71989. this.onAfterRenderObservable = new BABYLON.Observable();
  71990. if (camera != null) {
  71991. this._camera = camera;
  71992. this._scene = camera.getScene();
  71993. camera.attachPostProcess(this);
  71994. this._engine = this._scene.getEngine();
  71995. this._scene.postProcesses.push(this);
  71996. }
  71997. else if (engine) {
  71998. this._engine = engine;
  71999. this._engine.postProcesses.push(this);
  72000. }
  72001. this._options = options;
  72002. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  72003. this._reusable = reusable || false;
  72004. this._textureType = textureType;
  72005. this._samplers = samplers || [];
  72006. this._samplers.push("textureSampler");
  72007. this._fragmentUrl = fragmentUrl;
  72008. this._vertexUrl = vertexUrl;
  72009. this._parameters = parameters || [];
  72010. this._parameters.push("scale");
  72011. this._indexParameters = indexParameters;
  72012. if (!blockCompilation) {
  72013. this.updateEffect(defines);
  72014. }
  72015. }
  72016. Object.defineProperty(PostProcess.prototype, "samples", {
  72017. /**
  72018. * Number of sample textures (default: 1)
  72019. */
  72020. get: function () {
  72021. return this._samples;
  72022. },
  72023. set: function (n) {
  72024. var _this = this;
  72025. this._samples = n;
  72026. this._textures.forEach(function (texture) {
  72027. if (texture.samples !== _this._samples) {
  72028. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  72029. }
  72030. });
  72031. },
  72032. enumerable: true,
  72033. configurable: true
  72034. });
  72035. Object.defineProperty(PostProcess.prototype, "onActivate", {
  72036. /**
  72037. * A function that is added to the onActivateObservable
  72038. */
  72039. set: function (callback) {
  72040. if (this._onActivateObserver) {
  72041. this.onActivateObservable.remove(this._onActivateObserver);
  72042. }
  72043. if (callback) {
  72044. this._onActivateObserver = this.onActivateObservable.add(callback);
  72045. }
  72046. },
  72047. enumerable: true,
  72048. configurable: true
  72049. });
  72050. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  72051. /**
  72052. * A function that is added to the onSizeChangedObservable
  72053. */
  72054. set: function (callback) {
  72055. if (this._onSizeChangedObserver) {
  72056. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  72057. }
  72058. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  72059. },
  72060. enumerable: true,
  72061. configurable: true
  72062. });
  72063. Object.defineProperty(PostProcess.prototype, "onApply", {
  72064. /**
  72065. * A function that is added to the onApplyObservable
  72066. */
  72067. set: function (callback) {
  72068. if (this._onApplyObserver) {
  72069. this.onApplyObservable.remove(this._onApplyObserver);
  72070. }
  72071. this._onApplyObserver = this.onApplyObservable.add(callback);
  72072. },
  72073. enumerable: true,
  72074. configurable: true
  72075. });
  72076. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  72077. /**
  72078. * A function that is added to the onBeforeRenderObservable
  72079. */
  72080. set: function (callback) {
  72081. if (this._onBeforeRenderObserver) {
  72082. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72083. }
  72084. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72085. },
  72086. enumerable: true,
  72087. configurable: true
  72088. });
  72089. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  72090. /**
  72091. * A function that is added to the onAfterRenderObservable
  72092. */
  72093. set: function (callback) {
  72094. if (this._onAfterRenderObserver) {
  72095. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72096. }
  72097. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72098. },
  72099. enumerable: true,
  72100. configurable: true
  72101. });
  72102. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  72103. /**
  72104. * 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
  72105. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  72106. */
  72107. get: function () {
  72108. return this._textures.data[this._currentRenderTextureInd];
  72109. },
  72110. set: function (value) {
  72111. this._forcedOutputTexture = value;
  72112. },
  72113. enumerable: true,
  72114. configurable: true
  72115. });
  72116. /**
  72117. * Gets the camera which post process is applied to.
  72118. * @returns The camera the post process is applied to.
  72119. */
  72120. PostProcess.prototype.getCamera = function () {
  72121. return this._camera;
  72122. };
  72123. Object.defineProperty(PostProcess.prototype, "texelSize", {
  72124. /**
  72125. * Gets the texel size of the postprocess.
  72126. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  72127. */
  72128. get: function () {
  72129. if (this._shareOutputWithPostProcess) {
  72130. return this._shareOutputWithPostProcess.texelSize;
  72131. }
  72132. if (this._forcedOutputTexture) {
  72133. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  72134. }
  72135. return this._texelSize;
  72136. },
  72137. enumerable: true,
  72138. configurable: true
  72139. });
  72140. /**
  72141. * Gets the engine which this post process belongs to.
  72142. * @returns The engine the post process was enabled with.
  72143. */
  72144. PostProcess.prototype.getEngine = function () {
  72145. return this._engine;
  72146. };
  72147. /**
  72148. * The effect that is created when initializing the post process.
  72149. * @returns The created effect corrisponding the the postprocess.
  72150. */
  72151. PostProcess.prototype.getEffect = function () {
  72152. return this._effect;
  72153. };
  72154. /**
  72155. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  72156. * @param postProcess The post process to share the output with.
  72157. * @returns This post process.
  72158. */
  72159. PostProcess.prototype.shareOutputWith = function (postProcess) {
  72160. this._disposeTextures();
  72161. this._shareOutputWithPostProcess = postProcess;
  72162. return this;
  72163. };
  72164. /**
  72165. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  72166. * This should be called if the post process that shares output with this post process is disabled/disposed.
  72167. */
  72168. PostProcess.prototype.useOwnOutput = function () {
  72169. if (this._textures.length == 0) {
  72170. this._textures = new BABYLON.SmartArray(2);
  72171. }
  72172. this._shareOutputWithPostProcess = null;
  72173. };
  72174. /**
  72175. * Updates the effect with the current post process compile time values and recompiles the shader.
  72176. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  72177. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  72178. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  72179. * @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
  72180. * @param onCompiled Called when the shader has been compiled.
  72181. * @param onError Called if there is an error when compiling a shader.
  72182. */
  72183. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  72184. if (defines === void 0) { defines = null; }
  72185. if (uniforms === void 0) { uniforms = null; }
  72186. if (samplers === void 0) { samplers = null; }
  72187. 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);
  72188. };
  72189. /**
  72190. * The post process is reusable if it can be used multiple times within one frame.
  72191. * @returns If the post process is reusable
  72192. */
  72193. PostProcess.prototype.isReusable = function () {
  72194. return this._reusable;
  72195. };
  72196. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  72197. PostProcess.prototype.markTextureDirty = function () {
  72198. this.width = -1;
  72199. };
  72200. /**
  72201. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  72202. * 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.
  72203. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  72204. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  72205. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  72206. * @returns The target texture that was bound to be written to.
  72207. */
  72208. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  72209. var _this = this;
  72210. if (sourceTexture === void 0) { sourceTexture = null; }
  72211. camera = camera || this._camera;
  72212. var scene = camera.getScene();
  72213. var engine = scene.getEngine();
  72214. var maxSize = engine.getCaps().maxTextureSize;
  72215. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  72216. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  72217. // 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
  72218. var webVRCamera = camera.parent;
  72219. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  72220. requiredWidth /= 2;
  72221. }
  72222. var desiredWidth = (this._options.width || requiredWidth);
  72223. var desiredHeight = this._options.height || requiredHeight;
  72224. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  72225. if (this.adaptScaleToCurrentViewport) {
  72226. var currentViewport = engine.currentViewport;
  72227. if (currentViewport) {
  72228. desiredWidth *= currentViewport.width;
  72229. desiredHeight *= currentViewport.height;
  72230. }
  72231. }
  72232. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  72233. if (!this._options.width) {
  72234. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  72235. }
  72236. if (!this._options.height) {
  72237. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  72238. }
  72239. }
  72240. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  72241. if (this._textures.length > 0) {
  72242. for (var i = 0; i < this._textures.length; i++) {
  72243. this._engine._releaseTexture(this._textures.data[i]);
  72244. }
  72245. this._textures.reset();
  72246. }
  72247. this.width = desiredWidth;
  72248. this.height = desiredHeight;
  72249. var textureSize = { width: this.width, height: this.height };
  72250. var textureOptions = {
  72251. generateMipMaps: false,
  72252. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  72253. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  72254. samplingMode: this.renderTargetSamplingMode,
  72255. type: this._textureType
  72256. };
  72257. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72258. if (this._reusable) {
  72259. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72260. }
  72261. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  72262. this.onSizeChangedObservable.notifyObservers(this);
  72263. }
  72264. this._textures.forEach(function (texture) {
  72265. if (texture.samples !== _this.samples) {
  72266. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  72267. }
  72268. });
  72269. }
  72270. var target;
  72271. if (this._shareOutputWithPostProcess) {
  72272. target = this._shareOutputWithPostProcess.inputTexture;
  72273. }
  72274. else if (this._forcedOutputTexture) {
  72275. target = this._forcedOutputTexture;
  72276. this.width = this._forcedOutputTexture.width;
  72277. this.height = this._forcedOutputTexture.height;
  72278. }
  72279. else {
  72280. target = this.inputTexture;
  72281. }
  72282. // Bind the input of this post process to be used as the output of the previous post process.
  72283. if (this.enablePixelPerfectMode) {
  72284. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  72285. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  72286. }
  72287. else {
  72288. this._scaleRatio.copyFromFloats(1, 1);
  72289. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  72290. }
  72291. this.onActivateObservable.notifyObservers(camera);
  72292. // Clear
  72293. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  72294. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  72295. }
  72296. if (this._reusable) {
  72297. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  72298. }
  72299. return target;
  72300. };
  72301. Object.defineProperty(PostProcess.prototype, "isSupported", {
  72302. /**
  72303. * If the post process is supported.
  72304. */
  72305. get: function () {
  72306. return this._effect.isSupported;
  72307. },
  72308. enumerable: true,
  72309. configurable: true
  72310. });
  72311. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  72312. /**
  72313. * The aspect ratio of the output texture.
  72314. */
  72315. get: function () {
  72316. if (this._shareOutputWithPostProcess) {
  72317. return this._shareOutputWithPostProcess.aspectRatio;
  72318. }
  72319. if (this._forcedOutputTexture) {
  72320. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  72321. }
  72322. return this.width / this.height;
  72323. },
  72324. enumerable: true,
  72325. configurable: true
  72326. });
  72327. /**
  72328. * Get a value indicating if the post-process is ready to be used
  72329. * @returns true if the post-process is ready (shader is compiled)
  72330. */
  72331. PostProcess.prototype.isReady = function () {
  72332. return this._effect && this._effect.isReady();
  72333. };
  72334. /**
  72335. * Binds all textures and uniforms to the shader, this will be run on every pass.
  72336. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  72337. */
  72338. PostProcess.prototype.apply = function () {
  72339. // Check
  72340. if (!this._effect || !this._effect.isReady())
  72341. return null;
  72342. // States
  72343. this._engine.enableEffect(this._effect);
  72344. this._engine.setState(false);
  72345. this._engine.setDepthBuffer(false);
  72346. this._engine.setDepthWrite(false);
  72347. // Alpha
  72348. this._engine.setAlphaMode(this.alphaMode);
  72349. if (this.alphaConstants) {
  72350. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  72351. }
  72352. // Bind the output texture of the preivous post process as the input to this post process.
  72353. var source;
  72354. if (this._shareOutputWithPostProcess) {
  72355. source = this._shareOutputWithPostProcess.inputTexture;
  72356. }
  72357. else if (this._forcedOutputTexture) {
  72358. source = this._forcedOutputTexture;
  72359. }
  72360. else {
  72361. source = this.inputTexture;
  72362. }
  72363. this._effect._bindTexture("textureSampler", source);
  72364. // Parameters
  72365. this._effect.setVector2("scale", this._scaleRatio);
  72366. this.onApplyObservable.notifyObservers(this._effect);
  72367. return this._effect;
  72368. };
  72369. PostProcess.prototype._disposeTextures = function () {
  72370. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  72371. return;
  72372. }
  72373. if (this._textures.length > 0) {
  72374. for (var i = 0; i < this._textures.length; i++) {
  72375. this._engine._releaseTexture(this._textures.data[i]);
  72376. }
  72377. }
  72378. this._textures.dispose();
  72379. };
  72380. /**
  72381. * Disposes the post process.
  72382. * @param camera The camera to dispose the post process on.
  72383. */
  72384. PostProcess.prototype.dispose = function (camera) {
  72385. camera = camera || this._camera;
  72386. this._disposeTextures();
  72387. if (this._scene) {
  72388. var index_1 = this._scene.postProcesses.indexOf(this);
  72389. if (index_1 !== -1) {
  72390. this._scene.postProcesses.splice(index_1, 1);
  72391. }
  72392. }
  72393. else {
  72394. var index_2 = this._engine.postProcesses.indexOf(this);
  72395. if (index_2 !== -1) {
  72396. this._engine.postProcesses.splice(index_2, 1);
  72397. }
  72398. }
  72399. if (!camera) {
  72400. return;
  72401. }
  72402. camera.detachPostProcess(this);
  72403. var index = camera._postProcesses.indexOf(this);
  72404. if (index === 0 && camera._postProcesses.length > 0) {
  72405. var firstPostProcess = this._camera._getFirstPostProcess();
  72406. if (firstPostProcess) {
  72407. firstPostProcess.markTextureDirty();
  72408. }
  72409. }
  72410. this.onActivateObservable.clear();
  72411. this.onAfterRenderObservable.clear();
  72412. this.onApplyObservable.clear();
  72413. this.onBeforeRenderObservable.clear();
  72414. this.onSizeChangedObservable.clear();
  72415. };
  72416. return PostProcess;
  72417. }());
  72418. BABYLON.PostProcess = PostProcess;
  72419. })(BABYLON || (BABYLON = {}));
  72420. //# sourceMappingURL=babylon.postProcess.js.map
  72421. var BABYLON;
  72422. (function (BABYLON) {
  72423. var PassPostProcess = /** @class */ (function (_super) {
  72424. __extends(PassPostProcess, _super);
  72425. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72426. if (camera === void 0) { camera = null; }
  72427. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72428. if (blockCompilation === void 0) { blockCompilation = false; }
  72429. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  72430. }
  72431. return PassPostProcess;
  72432. }(BABYLON.PostProcess));
  72433. BABYLON.PassPostProcess = PassPostProcess;
  72434. })(BABYLON || (BABYLON = {}));
  72435. //# sourceMappingURL=babylon.passPostProcess.js.map
  72436. var __assign = (this && this.__assign) || function () {
  72437. __assign = Object.assign || function(t) {
  72438. for (var s, i = 1, n = arguments.length; i < n; i++) {
  72439. s = arguments[i];
  72440. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  72441. t[p] = s[p];
  72442. }
  72443. return t;
  72444. };
  72445. return __assign.apply(this, arguments);
  72446. };
  72447. var BABYLON;
  72448. (function (BABYLON) {
  72449. /**
  72450. * Default implementation IShadowGenerator.
  72451. * This is the main object responsible of generating shadows in the framework.
  72452. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  72453. */
  72454. var ShadowGenerator = /** @class */ (function () {
  72455. /**
  72456. * Creates a ShadowGenerator object.
  72457. * A ShadowGenerator is the required tool to use the shadows.
  72458. * Each light casting shadows needs to use its own ShadowGenerator.
  72459. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  72460. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  72461. * @param light The light object generating the shadows.
  72462. * @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.
  72463. */
  72464. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  72465. this._bias = 0.00005;
  72466. this._normalBias = 0;
  72467. this._blurBoxOffset = 1;
  72468. this._blurScale = 2;
  72469. this._blurKernel = 1;
  72470. this._useKernelBlur = false;
  72471. this._filter = ShadowGenerator.FILTER_NONE;
  72472. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  72473. this._contactHardeningLightSizeUVRatio = 0.1;
  72474. this._darkness = 0;
  72475. this._transparencyShadow = false;
  72476. /**
  72477. * Controls the extent to which the shadows fade out at the edge of the frustum
  72478. * Used only by directionals and spots
  72479. */
  72480. this.frustumEdgeFalloff = 0;
  72481. /**
  72482. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  72483. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  72484. * It might on the other hand introduce peter panning.
  72485. */
  72486. this.forceBackFacesOnly = false;
  72487. this._lightDirection = BABYLON.Vector3.Zero();
  72488. this._viewMatrix = BABYLON.Matrix.Zero();
  72489. this._projectionMatrix = BABYLON.Matrix.Zero();
  72490. this._transformMatrix = BABYLON.Matrix.Zero();
  72491. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72492. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72493. this._currentFaceIndex = 0;
  72494. this._currentFaceIndexCache = 0;
  72495. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  72496. this._mapSize = mapSize;
  72497. this._light = light;
  72498. this._scene = light.getScene();
  72499. light._shadowGenerator = this;
  72500. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  72501. if (!component) {
  72502. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  72503. this._scene._addComponent(component);
  72504. }
  72505. // Texture type fallback from float to int if not supported.
  72506. var caps = this._scene.getEngine().getCaps();
  72507. if (!useFullFloatFirst) {
  72508. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72509. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72510. }
  72511. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72512. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72513. }
  72514. else {
  72515. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72516. }
  72517. }
  72518. else {
  72519. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72520. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72521. }
  72522. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72523. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72524. }
  72525. else {
  72526. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72527. }
  72528. }
  72529. this._initializeGenerator();
  72530. this._applyFilterValues();
  72531. }
  72532. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  72533. /**
  72534. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  72535. */
  72536. get: function () {
  72537. return this._bias;
  72538. },
  72539. /**
  72540. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  72541. */
  72542. set: function (bias) {
  72543. this._bias = bias;
  72544. },
  72545. enumerable: true,
  72546. configurable: true
  72547. });
  72548. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  72549. /**
  72550. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72551. */
  72552. get: function () {
  72553. return this._normalBias;
  72554. },
  72555. /**
  72556. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72557. */
  72558. set: function (normalBias) {
  72559. this._normalBias = normalBias;
  72560. },
  72561. enumerable: true,
  72562. configurable: true
  72563. });
  72564. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  72565. /**
  72566. * Gets the blur box offset: offset applied during the blur pass.
  72567. * Only usefull if useKernelBlur = false
  72568. */
  72569. get: function () {
  72570. return this._blurBoxOffset;
  72571. },
  72572. /**
  72573. * Sets the blur box offset: offset applied during the blur pass.
  72574. * Only usefull if useKernelBlur = false
  72575. */
  72576. set: function (value) {
  72577. if (this._blurBoxOffset === value) {
  72578. return;
  72579. }
  72580. this._blurBoxOffset = value;
  72581. this._disposeBlurPostProcesses();
  72582. },
  72583. enumerable: true,
  72584. configurable: true
  72585. });
  72586. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  72587. /**
  72588. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  72589. * 2 means half of the size.
  72590. */
  72591. get: function () {
  72592. return this._blurScale;
  72593. },
  72594. /**
  72595. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  72596. * 2 means half of the size.
  72597. */
  72598. set: function (value) {
  72599. if (this._blurScale === value) {
  72600. return;
  72601. }
  72602. this._blurScale = value;
  72603. this._disposeBlurPostProcesses();
  72604. },
  72605. enumerable: true,
  72606. configurable: true
  72607. });
  72608. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  72609. /**
  72610. * Gets the blur kernel: kernel size of the blur pass.
  72611. * Only usefull if useKernelBlur = true
  72612. */
  72613. get: function () {
  72614. return this._blurKernel;
  72615. },
  72616. /**
  72617. * Sets the blur kernel: kernel size of the blur pass.
  72618. * Only usefull if useKernelBlur = true
  72619. */
  72620. set: function (value) {
  72621. if (this._blurKernel === value) {
  72622. return;
  72623. }
  72624. this._blurKernel = value;
  72625. this._disposeBlurPostProcesses();
  72626. },
  72627. enumerable: true,
  72628. configurable: true
  72629. });
  72630. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  72631. /**
  72632. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  72633. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72634. */
  72635. get: function () {
  72636. return this._useKernelBlur;
  72637. },
  72638. /**
  72639. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  72640. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72641. */
  72642. set: function (value) {
  72643. if (this._useKernelBlur === value) {
  72644. return;
  72645. }
  72646. this._useKernelBlur = value;
  72647. this._disposeBlurPostProcesses();
  72648. },
  72649. enumerable: true,
  72650. configurable: true
  72651. });
  72652. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  72653. /**
  72654. * Gets the depth scale used in ESM mode.
  72655. */
  72656. get: function () {
  72657. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  72658. },
  72659. /**
  72660. * Sets the depth scale used in ESM mode.
  72661. * This can override the scale stored on the light.
  72662. */
  72663. set: function (value) {
  72664. this._depthScale = value;
  72665. },
  72666. enumerable: true,
  72667. configurable: true
  72668. });
  72669. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  72670. /**
  72671. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  72672. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72673. */
  72674. get: function () {
  72675. return this._filter;
  72676. },
  72677. /**
  72678. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  72679. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72680. */
  72681. set: function (value) {
  72682. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  72683. if (this._light.needCube()) {
  72684. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72685. this.useExponentialShadowMap = true;
  72686. return;
  72687. }
  72688. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72689. this.useCloseExponentialShadowMap = true;
  72690. return;
  72691. }
  72692. // PCF on cubemap would also be expensive
  72693. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72694. this.usePoissonSampling = true;
  72695. return;
  72696. }
  72697. }
  72698. // Weblg1 fallback for PCF.
  72699. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72700. if (this._scene.getEngine().webGLVersion === 1) {
  72701. this.usePoissonSampling = true;
  72702. return;
  72703. }
  72704. }
  72705. if (this._filter === value) {
  72706. return;
  72707. }
  72708. this._filter = value;
  72709. this._disposeBlurPostProcesses();
  72710. this._applyFilterValues();
  72711. this._light._markMeshesAsLightDirty();
  72712. },
  72713. enumerable: true,
  72714. configurable: true
  72715. });
  72716. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  72717. /**
  72718. * Gets if the current filter is set to Poisson Sampling.
  72719. */
  72720. get: function () {
  72721. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  72722. },
  72723. /**
  72724. * Sets the current filter to Poisson Sampling.
  72725. */
  72726. set: function (value) {
  72727. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  72728. return;
  72729. }
  72730. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  72731. },
  72732. enumerable: true,
  72733. configurable: true
  72734. });
  72735. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  72736. /**
  72737. * Gets if the current filter is set to VSM.
  72738. * DEPRECATED. Should use useExponentialShadowMap instead.
  72739. */
  72740. get: function () {
  72741. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72742. return this.useExponentialShadowMap;
  72743. },
  72744. /**
  72745. * Sets the current filter is to VSM.
  72746. * DEPRECATED. Should use useExponentialShadowMap instead.
  72747. */
  72748. set: function (value) {
  72749. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72750. this.useExponentialShadowMap = value;
  72751. },
  72752. enumerable: true,
  72753. configurable: true
  72754. });
  72755. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  72756. /**
  72757. * Gets if the current filter is set to blurred VSM.
  72758. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72759. */
  72760. get: function () {
  72761. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72762. return this.useBlurExponentialShadowMap;
  72763. },
  72764. /**
  72765. * Sets the current filter is to blurred VSM.
  72766. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72767. */
  72768. set: function (value) {
  72769. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72770. this.useBlurExponentialShadowMap = value;
  72771. },
  72772. enumerable: true,
  72773. configurable: true
  72774. });
  72775. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  72776. /**
  72777. * Gets if the current filter is set to ESM.
  72778. */
  72779. get: function () {
  72780. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  72781. },
  72782. /**
  72783. * Sets the current filter is to ESM.
  72784. */
  72785. set: function (value) {
  72786. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  72787. return;
  72788. }
  72789. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72790. },
  72791. enumerable: true,
  72792. configurable: true
  72793. });
  72794. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  72795. /**
  72796. * Gets if the current filter is set to filtered ESM.
  72797. */
  72798. get: function () {
  72799. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  72800. },
  72801. /**
  72802. * Gets if the current filter is set to filtered ESM.
  72803. */
  72804. set: function (value) {
  72805. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72806. return;
  72807. }
  72808. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72809. },
  72810. enumerable: true,
  72811. configurable: true
  72812. });
  72813. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  72814. /**
  72815. * Gets if the current filter is set to "close ESM" (using the inverse of the
  72816. * exponential to prevent steep falloff artifacts).
  72817. */
  72818. get: function () {
  72819. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  72820. },
  72821. /**
  72822. * Sets the current filter to "close ESM" (using the inverse of the
  72823. * exponential to prevent steep falloff artifacts).
  72824. */
  72825. set: function (value) {
  72826. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  72827. return;
  72828. }
  72829. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72830. },
  72831. enumerable: true,
  72832. configurable: true
  72833. });
  72834. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  72835. /**
  72836. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  72837. * exponential to prevent steep falloff artifacts).
  72838. */
  72839. get: function () {
  72840. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  72841. },
  72842. /**
  72843. * Sets the current filter to filtered "close ESM" (using the inverse of the
  72844. * exponential to prevent steep falloff artifacts).
  72845. */
  72846. set: function (value) {
  72847. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72848. return;
  72849. }
  72850. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72851. },
  72852. enumerable: true,
  72853. configurable: true
  72854. });
  72855. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  72856. /**
  72857. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  72858. */
  72859. get: function () {
  72860. return this.filter === ShadowGenerator.FILTER_PCF;
  72861. },
  72862. /**
  72863. * Sets the current filter to "PCF" (percentage closer filtering).
  72864. */
  72865. set: function (value) {
  72866. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  72867. return;
  72868. }
  72869. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  72870. },
  72871. enumerable: true,
  72872. configurable: true
  72873. });
  72874. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  72875. /**
  72876. * Gets the PCF or PCSS Quality.
  72877. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72878. */
  72879. get: function () {
  72880. return this._filteringQuality;
  72881. },
  72882. /**
  72883. * Sets the PCF or PCSS Quality.
  72884. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72885. */
  72886. set: function (filteringQuality) {
  72887. this._filteringQuality = filteringQuality;
  72888. },
  72889. enumerable: true,
  72890. configurable: true
  72891. });
  72892. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  72893. /**
  72894. * Gets if the current filter is set to "PCSS" (contact hardening).
  72895. */
  72896. get: function () {
  72897. return this.filter === ShadowGenerator.FILTER_PCSS;
  72898. },
  72899. /**
  72900. * Sets the current filter to "PCSS" (contact hardening).
  72901. */
  72902. set: function (value) {
  72903. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  72904. return;
  72905. }
  72906. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  72907. },
  72908. enumerable: true,
  72909. configurable: true
  72910. });
  72911. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  72912. /**
  72913. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72914. * Using a ratio helps keeping shape stability independently of the map size.
  72915. *
  72916. * It does not account for the light projection as it was having too much
  72917. * instability during the light setup or during light position changes.
  72918. *
  72919. * Only valid if useContactHardeningShadow is true.
  72920. */
  72921. get: function () {
  72922. return this._contactHardeningLightSizeUVRatio;
  72923. },
  72924. /**
  72925. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72926. * Using a ratio helps keeping shape stability independently of the map size.
  72927. *
  72928. * It does not account for the light projection as it was having too much
  72929. * instability during the light setup or during light position changes.
  72930. *
  72931. * Only valid if useContactHardeningShadow is true.
  72932. */
  72933. set: function (contactHardeningLightSizeUVRatio) {
  72934. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  72935. },
  72936. enumerable: true,
  72937. configurable: true
  72938. });
  72939. /**
  72940. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  72941. * 0 means strongest and 1 would means no shadow.
  72942. * @returns the darkness.
  72943. */
  72944. ShadowGenerator.prototype.getDarkness = function () {
  72945. return this._darkness;
  72946. };
  72947. /**
  72948. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  72949. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  72950. * @returns the shadow generator allowing fluent coding.
  72951. */
  72952. ShadowGenerator.prototype.setDarkness = function (darkness) {
  72953. if (darkness >= 1.0)
  72954. this._darkness = 1.0;
  72955. else if (darkness <= 0.0)
  72956. this._darkness = 0.0;
  72957. else
  72958. this._darkness = darkness;
  72959. return this;
  72960. };
  72961. /**
  72962. * Sets the ability to have transparent shadow (boolean).
  72963. * @param transparent True if transparent else False
  72964. * @returns the shadow generator allowing fluent coding
  72965. */
  72966. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  72967. this._transparencyShadow = transparent;
  72968. return this;
  72969. };
  72970. /**
  72971. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  72972. * @returns The render target texture if present otherwise, null
  72973. */
  72974. ShadowGenerator.prototype.getShadowMap = function () {
  72975. return this._shadowMap;
  72976. };
  72977. /**
  72978. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  72979. * @returns The render target texture if the shadow map is present otherwise, null
  72980. */
  72981. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  72982. if (this._shadowMap2) {
  72983. return this._shadowMap2;
  72984. }
  72985. return this._shadowMap;
  72986. };
  72987. /**
  72988. * Helper function to add a mesh and its descendants to the list of shadow casters.
  72989. * @param mesh Mesh to add
  72990. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  72991. * @returns the Shadow Generator itself
  72992. */
  72993. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  72994. if (includeDescendants === void 0) { includeDescendants = true; }
  72995. var _a;
  72996. if (!this._shadowMap) {
  72997. return this;
  72998. }
  72999. if (!this._shadowMap.renderList) {
  73000. this._shadowMap.renderList = [];
  73001. }
  73002. this._shadowMap.renderList.push(mesh);
  73003. if (includeDescendants) {
  73004. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  73005. }
  73006. return this;
  73007. };
  73008. /**
  73009. * Helper function to remove a mesh and its descendants from the list of shadow casters
  73010. * @param mesh Mesh to remove
  73011. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  73012. * @returns the Shadow Generator itself
  73013. */
  73014. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  73015. if (includeDescendants === void 0) { includeDescendants = true; }
  73016. if (!this._shadowMap || !this._shadowMap.renderList) {
  73017. return this;
  73018. }
  73019. var index = this._shadowMap.renderList.indexOf(mesh);
  73020. if (index !== -1) {
  73021. this._shadowMap.renderList.splice(index, 1);
  73022. }
  73023. if (includeDescendants) {
  73024. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  73025. var child = _a[_i];
  73026. this.removeShadowCaster(child);
  73027. }
  73028. }
  73029. return this;
  73030. };
  73031. /**
  73032. * Returns the associated light object.
  73033. * @returns the light generating the shadow
  73034. */
  73035. ShadowGenerator.prototype.getLight = function () {
  73036. return this._light;
  73037. };
  73038. ShadowGenerator.prototype._initializeGenerator = function () {
  73039. this._light._markMeshesAsLightDirty();
  73040. this._initializeShadowMap();
  73041. };
  73042. ShadowGenerator.prototype._initializeShadowMap = function () {
  73043. var _this = this;
  73044. // Render target
  73045. var engine = this._scene.getEngine();
  73046. if (engine.webGLVersion > 1) {
  73047. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  73048. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  73049. }
  73050. else {
  73051. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  73052. }
  73053. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73054. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73055. this._shadowMap.anisotropicFilteringLevel = 1;
  73056. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73057. this._shadowMap.renderParticles = false;
  73058. this._shadowMap.ignoreCameraViewport = true;
  73059. // Record Face Index before render.
  73060. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  73061. _this._currentFaceIndex = faceIndex;
  73062. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73063. engine.setColorWrite(false);
  73064. }
  73065. });
  73066. // Custom render function.
  73067. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  73068. // Blur if required afer render.
  73069. this._shadowMap.onAfterUnbindObservable.add(function () {
  73070. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73071. engine.setColorWrite(true);
  73072. }
  73073. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  73074. return;
  73075. }
  73076. var shadowMap = _this.getShadowMapForRendering();
  73077. if (shadowMap) {
  73078. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  73079. }
  73080. });
  73081. // Clear according to the chosen filter.
  73082. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  73083. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  73084. this._shadowMap.onClearObservable.add(function (engine) {
  73085. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73086. engine.clear(clearOne, false, true, false);
  73087. }
  73088. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  73089. engine.clear(clearZero, true, true, false);
  73090. }
  73091. else {
  73092. engine.clear(clearOne, true, true, false);
  73093. }
  73094. });
  73095. };
  73096. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  73097. var _this = this;
  73098. var engine = this._scene.getEngine();
  73099. var targetSize = this._mapSize / this.blurScale;
  73100. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  73101. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  73102. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73103. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73104. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73105. }
  73106. if (this.useKernelBlur) {
  73107. 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);
  73108. this._kernelBlurXPostprocess.width = targetSize;
  73109. this._kernelBlurXPostprocess.height = targetSize;
  73110. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  73111. effect.setTexture("textureSampler", _this._shadowMap);
  73112. });
  73113. 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);
  73114. this._kernelBlurXPostprocess.autoClear = false;
  73115. this._kernelBlurYPostprocess.autoClear = false;
  73116. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73117. this._kernelBlurXPostprocess.packedFloat = true;
  73118. this._kernelBlurYPostprocess.packedFloat = true;
  73119. }
  73120. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  73121. }
  73122. else {
  73123. 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);
  73124. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  73125. effect.setFloat2("screenSize", targetSize, targetSize);
  73126. effect.setTexture("textureSampler", _this._shadowMap);
  73127. });
  73128. this._boxBlurPostprocess.autoClear = false;
  73129. this._blurPostProcesses = [this._boxBlurPostprocess];
  73130. }
  73131. };
  73132. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73133. var index;
  73134. var engine = this._scene.getEngine();
  73135. if (depthOnlySubMeshes.length) {
  73136. engine.setColorWrite(false);
  73137. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73138. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  73139. }
  73140. engine.setColorWrite(true);
  73141. }
  73142. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73143. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  73144. }
  73145. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73146. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  73147. }
  73148. if (this._transparencyShadow) {
  73149. for (index = 0; index < transparentSubMeshes.length; index++) {
  73150. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  73151. }
  73152. }
  73153. };
  73154. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  73155. var _this = this;
  73156. var mesh = subMesh.getRenderingMesh();
  73157. var scene = this._scene;
  73158. var engine = scene.getEngine();
  73159. var material = subMesh.getMaterial();
  73160. if (!material) {
  73161. return;
  73162. }
  73163. // Culling
  73164. engine.setState(material.backFaceCulling);
  73165. // Managing instances
  73166. var batch = mesh._getInstancesRenderList(subMesh._id);
  73167. if (batch.mustReturn) {
  73168. return;
  73169. }
  73170. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  73171. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  73172. engine.enableEffect(this._effect);
  73173. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  73174. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  73175. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  73176. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  73177. this._effect.setVector3("lightData", this._cachedDirection);
  73178. }
  73179. else {
  73180. this._effect.setVector3("lightData", this._cachedPosition);
  73181. }
  73182. if (scene.activeCamera) {
  73183. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  73184. }
  73185. // Alpha test
  73186. if (material && material.needAlphaTesting()) {
  73187. var alphaTexture = material.getAlphaTestTexture();
  73188. if (alphaTexture) {
  73189. this._effect.setTexture("diffuseSampler", alphaTexture);
  73190. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  73191. }
  73192. }
  73193. // Bones
  73194. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73195. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  73196. }
  73197. // Morph targets
  73198. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  73199. if (this.forceBackFacesOnly) {
  73200. engine.setState(true, 0, false, true);
  73201. }
  73202. // Draw
  73203. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73204. if (this.forceBackFacesOnly) {
  73205. engine.setState(true, 0, false, false);
  73206. }
  73207. }
  73208. else {
  73209. // Need to reset refresh rate of the shadowMap
  73210. if (this._shadowMap) {
  73211. this._shadowMap.resetRefreshCounter();
  73212. }
  73213. }
  73214. };
  73215. ShadowGenerator.prototype._applyFilterValues = function () {
  73216. if (!this._shadowMap) {
  73217. return;
  73218. }
  73219. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  73220. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  73221. }
  73222. else {
  73223. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73224. }
  73225. };
  73226. /**
  73227. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  73228. * @param onCompiled Callback triggered at the and of the effects compilation
  73229. * @param options Sets of optional options forcing the compilation with different modes
  73230. */
  73231. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  73232. var _this = this;
  73233. var localOptions = __assign({ useInstances: false }, options);
  73234. var shadowMap = this.getShadowMap();
  73235. if (!shadowMap) {
  73236. if (onCompiled) {
  73237. onCompiled(this);
  73238. }
  73239. return;
  73240. }
  73241. var renderList = shadowMap.renderList;
  73242. if (!renderList) {
  73243. if (onCompiled) {
  73244. onCompiled(this);
  73245. }
  73246. return;
  73247. }
  73248. var subMeshes = new Array();
  73249. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  73250. var mesh = renderList_1[_i];
  73251. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  73252. }
  73253. if (subMeshes.length === 0) {
  73254. if (onCompiled) {
  73255. onCompiled(this);
  73256. }
  73257. return;
  73258. }
  73259. var currentIndex = 0;
  73260. var checkReady = function () {
  73261. if (!_this._scene || !_this._scene.getEngine()) {
  73262. return;
  73263. }
  73264. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  73265. currentIndex++;
  73266. if (currentIndex >= subMeshes.length) {
  73267. if (onCompiled) {
  73268. onCompiled(_this);
  73269. }
  73270. return;
  73271. }
  73272. }
  73273. setTimeout(checkReady, 16);
  73274. };
  73275. checkReady();
  73276. };
  73277. /**
  73278. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  73279. * @param options Sets of optional options forcing the compilation with different modes
  73280. * @returns A promise that resolves when the compilation completes
  73281. */
  73282. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  73283. var _this = this;
  73284. return new Promise(function (resolve) {
  73285. _this.forceCompilation(function () {
  73286. resolve();
  73287. }, options);
  73288. });
  73289. };
  73290. /**
  73291. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  73292. * @param subMesh The submesh we want to render in the shadow map
  73293. * @param useInstances Defines wether will draw in the map using instances
  73294. * @returns true if ready otherwise, false
  73295. */
  73296. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  73297. var defines = [];
  73298. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73299. defines.push("#define FLOAT");
  73300. }
  73301. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73302. defines.push("#define ESM");
  73303. }
  73304. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  73305. defines.push("#define DEPTHTEXTURE");
  73306. }
  73307. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73308. var mesh = subMesh.getMesh();
  73309. var material = subMesh.getMaterial();
  73310. // Normal bias.
  73311. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73312. attribs.push(BABYLON.VertexBuffer.NormalKind);
  73313. defines.push("#define NORMAL");
  73314. if (mesh.nonUniformScaling) {
  73315. defines.push("#define NONUNIFORMSCALING");
  73316. }
  73317. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  73318. defines.push("#define DIRECTIONINLIGHTDATA");
  73319. }
  73320. }
  73321. // Alpha test
  73322. if (material && material.needAlphaTesting()) {
  73323. var alphaTexture = material.getAlphaTestTexture();
  73324. if (alphaTexture) {
  73325. defines.push("#define ALPHATEST");
  73326. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73327. attribs.push(BABYLON.VertexBuffer.UVKind);
  73328. defines.push("#define UV1");
  73329. }
  73330. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73331. if (alphaTexture.coordinatesIndex === 1) {
  73332. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73333. defines.push("#define UV2");
  73334. }
  73335. }
  73336. }
  73337. }
  73338. // Bones
  73339. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73340. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73341. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73342. if (mesh.numBoneInfluencers > 4) {
  73343. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73344. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73345. }
  73346. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73347. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  73348. }
  73349. else {
  73350. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73351. }
  73352. // Morph targets
  73353. var manager = mesh.morphTargetManager;
  73354. var morphInfluencers = 0;
  73355. if (manager) {
  73356. if (manager.numInfluencers > 0) {
  73357. defines.push("#define MORPHTARGETS");
  73358. morphInfluencers = manager.numInfluencers;
  73359. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  73360. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  73361. }
  73362. }
  73363. // Instances
  73364. if (useInstances) {
  73365. defines.push("#define INSTANCES");
  73366. attribs.push("world0");
  73367. attribs.push("world1");
  73368. attribs.push("world2");
  73369. attribs.push("world3");
  73370. }
  73371. // Get correct effect
  73372. var join = defines.join("\n");
  73373. if (this._cachedDefines !== join) {
  73374. this._cachedDefines = join;
  73375. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  73376. }
  73377. if (!this._effect.isReady()) {
  73378. return false;
  73379. }
  73380. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73381. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  73382. this._initializeBlurRTTAndPostProcesses();
  73383. }
  73384. }
  73385. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  73386. return false;
  73387. }
  73388. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  73389. return false;
  73390. }
  73391. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  73392. return false;
  73393. }
  73394. return true;
  73395. };
  73396. /**
  73397. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  73398. * @param defines Defines of the material we want to update
  73399. * @param lightIndex Index of the light in the enabled light list of the material
  73400. */
  73401. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  73402. var scene = this._scene;
  73403. var light = this._light;
  73404. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73405. return;
  73406. }
  73407. defines["SHADOW" + lightIndex] = true;
  73408. if (this.useContactHardeningShadow) {
  73409. defines["SHADOWPCSS" + lightIndex] = true;
  73410. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73411. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73412. }
  73413. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73414. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73415. }
  73416. // else default to high.
  73417. }
  73418. if (this.usePercentageCloserFiltering) {
  73419. defines["SHADOWPCF" + lightIndex] = true;
  73420. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73421. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73422. }
  73423. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73424. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73425. }
  73426. // else default to high.
  73427. }
  73428. else if (this.usePoissonSampling) {
  73429. defines["SHADOWPOISSON" + lightIndex] = true;
  73430. }
  73431. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73432. defines["SHADOWESM" + lightIndex] = true;
  73433. }
  73434. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73435. defines["SHADOWCLOSEESM" + lightIndex] = true;
  73436. }
  73437. if (light.needCube()) {
  73438. defines["SHADOWCUBE" + lightIndex] = true;
  73439. }
  73440. };
  73441. /**
  73442. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  73443. * defined in the generator but impacting the effect).
  73444. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  73445. * @param effect The effect we are binfing the information for
  73446. */
  73447. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  73448. var light = this._light;
  73449. var scene = this._scene;
  73450. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73451. return;
  73452. }
  73453. var camera = scene.activeCamera;
  73454. if (!camera) {
  73455. return;
  73456. }
  73457. var shadowMap = this.getShadowMap();
  73458. if (!shadowMap) {
  73459. return;
  73460. }
  73461. if (!light.needCube()) {
  73462. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  73463. }
  73464. // Only PCF uses depth stencil texture.
  73465. if (this._filter === ShadowGenerator.FILTER_PCF) {
  73466. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73467. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73468. }
  73469. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  73470. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73471. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  73472. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73473. }
  73474. else {
  73475. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73476. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  73477. }
  73478. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  73479. };
  73480. /**
  73481. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  73482. * (eq to shadow prjection matrix * light transform matrix)
  73483. * @returns The transform matrix used to create the shadow map
  73484. */
  73485. ShadowGenerator.prototype.getTransformMatrix = function () {
  73486. var scene = this._scene;
  73487. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  73488. return this._transformMatrix;
  73489. }
  73490. this._currentRenderID = scene.getRenderId();
  73491. this._currentFaceIndexCache = this._currentFaceIndex;
  73492. var lightPosition = this._light.position;
  73493. if (this._light.computeTransformedInformation()) {
  73494. lightPosition = this._light.transformedPosition;
  73495. }
  73496. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  73497. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  73498. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  73499. }
  73500. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  73501. this._cachedPosition.copyFrom(lightPosition);
  73502. this._cachedDirection.copyFrom(this._lightDirection);
  73503. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  73504. var shadowMap = this.getShadowMap();
  73505. if (shadowMap) {
  73506. var renderList = shadowMap.renderList;
  73507. if (renderList) {
  73508. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  73509. }
  73510. }
  73511. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  73512. }
  73513. return this._transformMatrix;
  73514. };
  73515. /**
  73516. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  73517. * Cube and 2D textures for instance.
  73518. */
  73519. ShadowGenerator.prototype.recreateShadowMap = function () {
  73520. var shadowMap = this._shadowMap;
  73521. if (!shadowMap) {
  73522. return;
  73523. }
  73524. // Track render list.
  73525. var renderList = shadowMap.renderList;
  73526. // Clean up existing data.
  73527. this._disposeRTTandPostProcesses();
  73528. // Reinitializes.
  73529. this._initializeGenerator();
  73530. // Reaffect the filter to ensure a correct fallback if necessary.
  73531. this.filter = this.filter;
  73532. // Reaffect the filter.
  73533. this._applyFilterValues();
  73534. // Reaffect Render List.
  73535. this._shadowMap.renderList = renderList;
  73536. };
  73537. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  73538. if (this._shadowMap2) {
  73539. this._shadowMap2.dispose();
  73540. this._shadowMap2 = null;
  73541. }
  73542. if (this._boxBlurPostprocess) {
  73543. this._boxBlurPostprocess.dispose();
  73544. this._boxBlurPostprocess = null;
  73545. }
  73546. if (this._kernelBlurXPostprocess) {
  73547. this._kernelBlurXPostprocess.dispose();
  73548. this._kernelBlurXPostprocess = null;
  73549. }
  73550. if (this._kernelBlurYPostprocess) {
  73551. this._kernelBlurYPostprocess.dispose();
  73552. this._kernelBlurYPostprocess = null;
  73553. }
  73554. this._blurPostProcesses = [];
  73555. };
  73556. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  73557. if (this._shadowMap) {
  73558. this._shadowMap.dispose();
  73559. this._shadowMap = null;
  73560. }
  73561. this._disposeBlurPostProcesses();
  73562. };
  73563. /**
  73564. * Disposes the ShadowGenerator.
  73565. * Returns nothing.
  73566. */
  73567. ShadowGenerator.prototype.dispose = function () {
  73568. this._disposeRTTandPostProcesses();
  73569. if (this._light) {
  73570. this._light._shadowGenerator = null;
  73571. this._light._markMeshesAsLightDirty();
  73572. }
  73573. };
  73574. /**
  73575. * Serializes the shadow generator setup to a json object.
  73576. * @returns The serialized JSON object
  73577. */
  73578. ShadowGenerator.prototype.serialize = function () {
  73579. var serializationObject = {};
  73580. var shadowMap = this.getShadowMap();
  73581. if (!shadowMap) {
  73582. return serializationObject;
  73583. }
  73584. serializationObject.lightId = this._light.id;
  73585. serializationObject.mapSize = shadowMap.getRenderSize();
  73586. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  73587. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  73588. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73589. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73590. serializationObject.usePoissonSampling = this.usePoissonSampling;
  73591. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  73592. serializationObject.depthScale = this.depthScale;
  73593. serializationObject.darkness = this.getDarkness();
  73594. serializationObject.blurBoxOffset = this.blurBoxOffset;
  73595. serializationObject.blurKernel = this.blurKernel;
  73596. serializationObject.blurScale = this.blurScale;
  73597. serializationObject.useKernelBlur = this.useKernelBlur;
  73598. serializationObject.transparencyShadow = this._transparencyShadow;
  73599. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  73600. serializationObject.bias = this.bias;
  73601. serializationObject.normalBias = this.normalBias;
  73602. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  73603. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  73604. serializationObject.filteringQuality = this.filteringQuality;
  73605. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  73606. serializationObject.renderList = [];
  73607. if (shadowMap.renderList) {
  73608. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  73609. var mesh = shadowMap.renderList[meshIndex];
  73610. serializationObject.renderList.push(mesh.id);
  73611. }
  73612. }
  73613. return serializationObject;
  73614. };
  73615. /**
  73616. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  73617. * @param parsedShadowGenerator The JSON object to parse
  73618. * @param scene The scene to create the shadow map for
  73619. * @returns The parsed shadow generator
  73620. */
  73621. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  73622. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  73623. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  73624. var shadowMap = shadowGenerator.getShadowMap();
  73625. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  73626. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  73627. meshes.forEach(function (mesh) {
  73628. if (!shadowMap) {
  73629. return;
  73630. }
  73631. if (!shadowMap.renderList) {
  73632. shadowMap.renderList = [];
  73633. }
  73634. shadowMap.renderList.push(mesh);
  73635. });
  73636. }
  73637. if (parsedShadowGenerator.usePoissonSampling) {
  73638. shadowGenerator.usePoissonSampling = true;
  73639. }
  73640. else if (parsedShadowGenerator.useExponentialShadowMap) {
  73641. shadowGenerator.useExponentialShadowMap = true;
  73642. }
  73643. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  73644. shadowGenerator.useBlurExponentialShadowMap = true;
  73645. }
  73646. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  73647. shadowGenerator.useCloseExponentialShadowMap = true;
  73648. }
  73649. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  73650. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  73651. }
  73652. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  73653. shadowGenerator.usePercentageCloserFiltering = true;
  73654. }
  73655. else if (parsedShadowGenerator.useContactHardeningShadow) {
  73656. shadowGenerator.useContactHardeningShadow = true;
  73657. }
  73658. if (parsedShadowGenerator.filteringQuality) {
  73659. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  73660. }
  73661. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  73662. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  73663. }
  73664. // Backward compat
  73665. else if (parsedShadowGenerator.useVarianceShadowMap) {
  73666. shadowGenerator.useExponentialShadowMap = true;
  73667. }
  73668. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  73669. shadowGenerator.useBlurExponentialShadowMap = true;
  73670. }
  73671. if (parsedShadowGenerator.depthScale) {
  73672. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  73673. }
  73674. if (parsedShadowGenerator.blurScale) {
  73675. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  73676. }
  73677. if (parsedShadowGenerator.blurBoxOffset) {
  73678. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  73679. }
  73680. if (parsedShadowGenerator.useKernelBlur) {
  73681. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  73682. }
  73683. if (parsedShadowGenerator.blurKernel) {
  73684. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  73685. }
  73686. if (parsedShadowGenerator.bias !== undefined) {
  73687. shadowGenerator.bias = parsedShadowGenerator.bias;
  73688. }
  73689. if (parsedShadowGenerator.normalBias !== undefined) {
  73690. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  73691. }
  73692. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  73693. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  73694. }
  73695. if (parsedShadowGenerator.darkness) {
  73696. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  73697. }
  73698. if (parsedShadowGenerator.transparencyShadow) {
  73699. shadowGenerator.setTransparencyShadow(true);
  73700. }
  73701. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  73702. return shadowGenerator;
  73703. };
  73704. /**
  73705. * Shadow generator mode None: no filtering applied.
  73706. */
  73707. ShadowGenerator.FILTER_NONE = 0;
  73708. /**
  73709. * Shadow generator mode ESM: Exponential Shadow Mapping.
  73710. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73711. */
  73712. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  73713. /**
  73714. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  73715. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  73716. */
  73717. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  73718. /**
  73719. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  73720. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73721. */
  73722. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  73723. /**
  73724. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  73725. * edge artifacts on steep falloff.
  73726. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73727. */
  73728. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  73729. /**
  73730. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  73731. * edge artifacts on steep falloff.
  73732. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73733. */
  73734. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  73735. /**
  73736. * Shadow generator mode PCF: Percentage Closer Filtering
  73737. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73738. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  73739. */
  73740. ShadowGenerator.FILTER_PCF = 6;
  73741. /**
  73742. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  73743. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73744. * Contact Hardening
  73745. */
  73746. ShadowGenerator.FILTER_PCSS = 7;
  73747. /**
  73748. * Reserved for PCF and PCSS
  73749. * Highest Quality.
  73750. *
  73751. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  73752. *
  73753. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  73754. */
  73755. ShadowGenerator.QUALITY_HIGH = 0;
  73756. /**
  73757. * Reserved for PCF and PCSS
  73758. * Good tradeoff for quality/perf cross devices
  73759. *
  73760. * Execute PCF on a 3*3 kernel.
  73761. *
  73762. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  73763. */
  73764. ShadowGenerator.QUALITY_MEDIUM = 1;
  73765. /**
  73766. * Reserved for PCF and PCSS
  73767. * The lowest quality but the fastest.
  73768. *
  73769. * Execute PCF on a 1*1 kernel.
  73770. *
  73771. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  73772. */
  73773. ShadowGenerator.QUALITY_LOW = 2;
  73774. return ShadowGenerator;
  73775. }());
  73776. BABYLON.ShadowGenerator = ShadowGenerator;
  73777. })(BABYLON || (BABYLON = {}));
  73778. //# sourceMappingURL=babylon.shadowGenerator.js.map
  73779. var BABYLON;
  73780. (function (BABYLON) {
  73781. // Adds the parser to the scene parsers.
  73782. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  73783. // Shadows
  73784. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  73785. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  73786. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  73787. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  73788. // SG would be available on their associated lights
  73789. }
  73790. }
  73791. });
  73792. /**
  73793. * Defines the shadow generator component responsible to manage any shadow generators
  73794. * in a given scene.
  73795. */
  73796. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  73797. /**
  73798. * Creates a new instance of the component for the given scene
  73799. * @param scene Defines the scene to register the component in
  73800. */
  73801. function ShadowGeneratorSceneComponent(scene) {
  73802. /**
  73803. * The component name helpfull to identify the component in the list of scene components.
  73804. */
  73805. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  73806. this.scene = scene;
  73807. }
  73808. /**
  73809. * Registers the component in a given scene
  73810. */
  73811. ShadowGeneratorSceneComponent.prototype.register = function () {
  73812. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  73813. };
  73814. /**
  73815. * Rebuilds the elements related to this component in case of
  73816. * context lost for instance.
  73817. */
  73818. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  73819. // Nothing To Do Here.
  73820. };
  73821. /**
  73822. * Serializes the component data to the specified json object
  73823. * @param serializationObject The object to serialize to
  73824. */
  73825. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  73826. // Shadows
  73827. serializationObject.shadowGenerators = [];
  73828. var lights = this.scene.lights;
  73829. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  73830. var light = lights_1[_i];
  73831. var shadowGenerator = light.getShadowGenerator();
  73832. if (shadowGenerator) {
  73833. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73834. }
  73835. }
  73836. };
  73837. /**
  73838. * Adds all the element from the container to the scene
  73839. * @param container the container holding the elements
  73840. */
  73841. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  73842. // Nothing To Do Here. (directly attached to a light)
  73843. };
  73844. /**
  73845. * Removes all the elements in the container from the scene
  73846. * @param container contains the elements to remove
  73847. */
  73848. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  73849. // Nothing To Do Here. (directly attached to a light)
  73850. };
  73851. /**
  73852. * Rebuilds the elements related to this component in case of
  73853. * context lost for instance.
  73854. */
  73855. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  73856. // Nothing To Do Here.
  73857. };
  73858. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  73859. // Shadows
  73860. var scene = this.scene;
  73861. if (this.scene.shadowsEnabled) {
  73862. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  73863. var light = scene.lights[lightIndex];
  73864. var shadowGenerator = light.getShadowGenerator();
  73865. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  73866. var shadowMap = (shadowGenerator.getShadowMap());
  73867. if (scene.textures.indexOf(shadowMap) !== -1) {
  73868. renderTargets.push(shadowMap);
  73869. }
  73870. }
  73871. }
  73872. }
  73873. };
  73874. return ShadowGeneratorSceneComponent;
  73875. }());
  73876. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  73877. })(BABYLON || (BABYLON = {}));
  73878. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  73879. var BABYLON;
  73880. (function (BABYLON) {
  73881. var DefaultLoadingScreen = /** @class */ (function () {
  73882. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  73883. if (_loadingText === void 0) { _loadingText = ""; }
  73884. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  73885. var _this = this;
  73886. this._renderingCanvas = _renderingCanvas;
  73887. this._loadingText = _loadingText;
  73888. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  73889. // Resize
  73890. this._resizeLoadingUI = function () {
  73891. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  73892. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  73893. if (!_this._loadingDiv) {
  73894. return;
  73895. }
  73896. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  73897. _this._loadingDiv.style.left = canvasRect.left + "px";
  73898. _this._loadingDiv.style.top = canvasRect.top + "px";
  73899. _this._loadingDiv.style.width = canvasRect.width + "px";
  73900. _this._loadingDiv.style.height = canvasRect.height + "px";
  73901. };
  73902. }
  73903. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  73904. if (this._loadingDiv) {
  73905. // Do not add a loading screen if there is already one
  73906. return;
  73907. }
  73908. this._loadingDiv = document.createElement("div");
  73909. this._loadingDiv.id = "babylonjsLoadingDiv";
  73910. this._loadingDiv.style.opacity = "0";
  73911. this._loadingDiv.style.transition = "opacity 1.5s ease";
  73912. this._loadingDiv.style.pointerEvents = "none";
  73913. // Loading text
  73914. this._loadingTextDiv = document.createElement("div");
  73915. this._loadingTextDiv.style.position = "absolute";
  73916. this._loadingTextDiv.style.left = "0";
  73917. this._loadingTextDiv.style.top = "50%";
  73918. this._loadingTextDiv.style.marginTop = "80px";
  73919. this._loadingTextDiv.style.width = "100%";
  73920. this._loadingTextDiv.style.height = "20px";
  73921. this._loadingTextDiv.style.fontFamily = "Arial";
  73922. this._loadingTextDiv.style.fontSize = "14px";
  73923. this._loadingTextDiv.style.color = "white";
  73924. this._loadingTextDiv.style.textAlign = "center";
  73925. this._loadingTextDiv.innerHTML = "Loading";
  73926. this._loadingDiv.appendChild(this._loadingTextDiv);
  73927. //set the predefined text
  73928. this._loadingTextDiv.innerHTML = this._loadingText;
  73929. // Generating keyframes
  73930. var style = document.createElement('style');
  73931. style.type = 'text/css';
  73932. 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 }";
  73933. style.innerHTML = keyFrames;
  73934. document.getElementsByTagName('head')[0].appendChild(style);
  73935. // Loading img
  73936. var imgBack = new Image();
  73937. 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";
  73938. imgBack.style.position = "absolute";
  73939. imgBack.style.left = "50%";
  73940. imgBack.style.top = "50%";
  73941. imgBack.style.marginLeft = "-60px";
  73942. imgBack.style.marginTop = "-60px";
  73943. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  73944. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  73945. imgBack.style.transformOrigin = "50% 50%";
  73946. imgBack.style.webkitTransformOrigin = "50% 50%";
  73947. this._loadingDiv.appendChild(imgBack);
  73948. this._resizeLoadingUI();
  73949. window.addEventListener("resize", this._resizeLoadingUI);
  73950. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73951. document.body.appendChild(this._loadingDiv);
  73952. this._loadingDiv.style.opacity = "1";
  73953. };
  73954. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  73955. var _this = this;
  73956. if (!this._loadingDiv) {
  73957. return;
  73958. }
  73959. var onTransitionEnd = function () {
  73960. if (!_this._loadingDiv) {
  73961. return;
  73962. }
  73963. document.body.removeChild(_this._loadingDiv);
  73964. window.removeEventListener("resize", _this._resizeLoadingUI);
  73965. _this._loadingDiv = null;
  73966. };
  73967. this._loadingDiv.style.opacity = "0";
  73968. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  73969. };
  73970. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  73971. set: function (text) {
  73972. this._loadingText = text;
  73973. if (this._loadingTextDiv) {
  73974. this._loadingTextDiv.innerHTML = this._loadingText;
  73975. }
  73976. },
  73977. enumerable: true,
  73978. configurable: true
  73979. });
  73980. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  73981. get: function () {
  73982. return this._loadingDivBackgroundColor;
  73983. },
  73984. set: function (color) {
  73985. this._loadingDivBackgroundColor = color;
  73986. if (!this._loadingDiv) {
  73987. return;
  73988. }
  73989. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73990. },
  73991. enumerable: true,
  73992. configurable: true
  73993. });
  73994. return DefaultLoadingScreen;
  73995. }());
  73996. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  73997. })(BABYLON || (BABYLON = {}));
  73998. //# sourceMappingURL=babylon.loadingScreen.js.map
  73999. var BABYLON;
  74000. (function (BABYLON) {
  74001. var SceneLoaderProgressEvent = /** @class */ (function () {
  74002. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  74003. this.lengthComputable = lengthComputable;
  74004. this.loaded = loaded;
  74005. this.total = total;
  74006. }
  74007. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  74008. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  74009. };
  74010. return SceneLoaderProgressEvent;
  74011. }());
  74012. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  74013. var SceneLoader = /** @class */ (function () {
  74014. function SceneLoader() {
  74015. }
  74016. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  74017. get: function () {
  74018. return 0;
  74019. },
  74020. enumerable: true,
  74021. configurable: true
  74022. });
  74023. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  74024. get: function () {
  74025. return 1;
  74026. },
  74027. enumerable: true,
  74028. configurable: true
  74029. });
  74030. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  74031. get: function () {
  74032. return 2;
  74033. },
  74034. enumerable: true,
  74035. configurable: true
  74036. });
  74037. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  74038. get: function () {
  74039. return 3;
  74040. },
  74041. enumerable: true,
  74042. configurable: true
  74043. });
  74044. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  74045. get: function () {
  74046. return SceneLoader._ForceFullSceneLoadingForIncremental;
  74047. },
  74048. set: function (value) {
  74049. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  74050. },
  74051. enumerable: true,
  74052. configurable: true
  74053. });
  74054. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  74055. get: function () {
  74056. return SceneLoader._ShowLoadingScreen;
  74057. },
  74058. set: function (value) {
  74059. SceneLoader._ShowLoadingScreen = value;
  74060. },
  74061. enumerable: true,
  74062. configurable: true
  74063. });
  74064. Object.defineProperty(SceneLoader, "loggingLevel", {
  74065. get: function () {
  74066. return SceneLoader._loggingLevel;
  74067. },
  74068. set: function (value) {
  74069. SceneLoader._loggingLevel = value;
  74070. },
  74071. enumerable: true,
  74072. configurable: true
  74073. });
  74074. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  74075. get: function () {
  74076. return SceneLoader._CleanBoneMatrixWeights;
  74077. },
  74078. set: function (value) {
  74079. SceneLoader._CleanBoneMatrixWeights = value;
  74080. },
  74081. enumerable: true,
  74082. configurable: true
  74083. });
  74084. SceneLoader._getDefaultPlugin = function () {
  74085. return SceneLoader._registeredPlugins[".babylon"];
  74086. };
  74087. SceneLoader._getPluginForExtension = function (extension) {
  74088. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  74089. if (registeredPlugin) {
  74090. return registeredPlugin;
  74091. }
  74092. 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");
  74093. return SceneLoader._getDefaultPlugin();
  74094. };
  74095. SceneLoader._getPluginForDirectLoad = function (data) {
  74096. for (var extension in SceneLoader._registeredPlugins) {
  74097. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  74098. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  74099. return SceneLoader._registeredPlugins[extension];
  74100. }
  74101. }
  74102. return SceneLoader._getDefaultPlugin();
  74103. };
  74104. SceneLoader._getPluginForFilename = function (sceneFilename) {
  74105. var queryStringPosition = sceneFilename.indexOf("?");
  74106. if (queryStringPosition !== -1) {
  74107. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  74108. }
  74109. var dotPosition = sceneFilename.lastIndexOf(".");
  74110. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  74111. return SceneLoader._getPluginForExtension(extension);
  74112. };
  74113. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  74114. SceneLoader._getDirectLoad = function (sceneFilename) {
  74115. if (sceneFilename.substr(0, 5) === "data:") {
  74116. return sceneFilename.substr(5);
  74117. }
  74118. return null;
  74119. };
  74120. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  74121. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  74122. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  74123. var plugin;
  74124. if (registeredPlugin.plugin.createPlugin) {
  74125. plugin = registeredPlugin.plugin.createPlugin();
  74126. }
  74127. else {
  74128. plugin = registeredPlugin.plugin;
  74129. }
  74130. var useArrayBuffer = registeredPlugin.isBinary;
  74131. var database;
  74132. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  74133. var dataCallback = function (data, responseURL) {
  74134. if (scene.isDisposed) {
  74135. onError("Scene has been disposed");
  74136. return;
  74137. }
  74138. scene.database = database;
  74139. onSuccess(plugin, data, responseURL);
  74140. };
  74141. var request = null;
  74142. var pluginDisposed = false;
  74143. var onDisposeObservable = plugin.onDisposeObservable;
  74144. if (onDisposeObservable) {
  74145. onDisposeObservable.add(function () {
  74146. pluginDisposed = true;
  74147. if (request) {
  74148. request.abort();
  74149. request = null;
  74150. }
  74151. onDispose();
  74152. });
  74153. }
  74154. var manifestChecked = function () {
  74155. if (pluginDisposed) {
  74156. return;
  74157. }
  74158. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  74159. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  74160. } : undefined, database, useArrayBuffer, function (request, exception) {
  74161. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  74162. });
  74163. };
  74164. if (directLoad) {
  74165. dataCallback(directLoad);
  74166. return plugin;
  74167. }
  74168. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  74169. var engine = scene.getEngine();
  74170. var canUseOfflineSupport = engine.enableOfflineSupport;
  74171. if (canUseOfflineSupport) {
  74172. // Also check for exceptions
  74173. var exceptionFound = false;
  74174. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  74175. var regex = _a[_i];
  74176. if (regex.test(fileInfo.url)) {
  74177. exceptionFound = true;
  74178. break;
  74179. }
  74180. }
  74181. canUseOfflineSupport = !exceptionFound;
  74182. }
  74183. if (canUseOfflineSupport) {
  74184. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  74185. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  74186. }
  74187. else {
  74188. manifestChecked();
  74189. }
  74190. }
  74191. // Loading file from disk via input file or drag'n'drop
  74192. else {
  74193. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  74194. if (file) {
  74195. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  74196. }
  74197. else {
  74198. onError("Unable to find file named " + fileInfo.name);
  74199. }
  74200. }
  74201. return plugin;
  74202. };
  74203. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  74204. var url;
  74205. var name;
  74206. if (!sceneFilename) {
  74207. url = rootUrl;
  74208. name = BABYLON.Tools.GetFilename(rootUrl);
  74209. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  74210. }
  74211. else {
  74212. if (sceneFilename.substr(0, 1) === "/") {
  74213. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  74214. return null;
  74215. }
  74216. url = rootUrl + sceneFilename;
  74217. name = sceneFilename;
  74218. }
  74219. ;
  74220. return {
  74221. url: url,
  74222. rootUrl: rootUrl,
  74223. name: name
  74224. };
  74225. };
  74226. // Public functions
  74227. SceneLoader.GetPluginForExtension = function (extension) {
  74228. return SceneLoader._getPluginForExtension(extension).plugin;
  74229. };
  74230. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  74231. return !!SceneLoader._registeredPlugins[extension];
  74232. };
  74233. SceneLoader.RegisterPlugin = function (plugin) {
  74234. if (typeof plugin.extensions === "string") {
  74235. var extension = plugin.extensions;
  74236. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  74237. plugin: plugin,
  74238. isBinary: false
  74239. };
  74240. }
  74241. else {
  74242. var extensions = plugin.extensions;
  74243. Object.keys(extensions).forEach(function (extension) {
  74244. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  74245. plugin: plugin,
  74246. isBinary: extensions[extension].isBinary
  74247. };
  74248. });
  74249. }
  74250. };
  74251. /**
  74252. * Import meshes into a scene
  74253. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  74254. * @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)
  74255. * @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)
  74256. * @param scene the instance of BABYLON.Scene to append to
  74257. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  74258. * @param onProgress a callback with a progress event for each file being loaded
  74259. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74260. * @param pluginExtension the extension used to determine the plugin
  74261. * @returns The loaded plugin
  74262. */
  74263. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74264. if (sceneFilename === void 0) { sceneFilename = ""; }
  74265. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74266. if (onSuccess === void 0) { onSuccess = null; }
  74267. if (onProgress === void 0) { onProgress = null; }
  74268. if (onError === void 0) { onError = null; }
  74269. if (pluginExtension === void 0) { pluginExtension = null; }
  74270. if (!scene) {
  74271. BABYLON.Tools.Error("No scene available to import mesh to");
  74272. return null;
  74273. }
  74274. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74275. if (!fileInfo) {
  74276. return null;
  74277. }
  74278. var loadingToken = {};
  74279. scene._addPendingData(loadingToken);
  74280. var disposeHandler = function () {
  74281. scene._removePendingData(loadingToken);
  74282. };
  74283. var errorHandler = function (message, exception) {
  74284. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  74285. if (onError) {
  74286. onError(scene, errorMessage, exception);
  74287. }
  74288. else {
  74289. BABYLON.Tools.Error(errorMessage);
  74290. // should the exception be thrown?
  74291. }
  74292. disposeHandler();
  74293. };
  74294. var progressHandler = onProgress ? function (event) {
  74295. try {
  74296. onProgress(event);
  74297. }
  74298. catch (e) {
  74299. errorHandler("Error in onProgress callback", e);
  74300. }
  74301. } : undefined;
  74302. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  74303. scene.importedMeshesFiles.push(fileInfo.url);
  74304. if (onSuccess) {
  74305. try {
  74306. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  74307. }
  74308. catch (e) {
  74309. errorHandler("Error in onSuccess callback", e);
  74310. }
  74311. }
  74312. scene._removePendingData(loadingToken);
  74313. };
  74314. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74315. if (plugin.rewriteRootURL) {
  74316. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  74317. }
  74318. if (plugin.importMesh) {
  74319. var syncedPlugin = plugin;
  74320. var meshes = new Array();
  74321. var particleSystems = new Array();
  74322. var skeletons = new Array();
  74323. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  74324. return;
  74325. }
  74326. scene.loadingPluginName = plugin.name;
  74327. successHandler(meshes, particleSystems, skeletons, []);
  74328. }
  74329. else {
  74330. var asyncedPlugin = plugin;
  74331. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  74332. scene.loadingPluginName = plugin.name;
  74333. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  74334. }).catch(function (error) {
  74335. errorHandler(error.message, error);
  74336. });
  74337. }
  74338. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74339. };
  74340. /**
  74341. * Import meshes into a scene
  74342. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  74343. * @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)
  74344. * @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)
  74345. * @param scene the instance of BABYLON.Scene to append to
  74346. * @param onProgress a callback with a progress event for each file being loaded
  74347. * @param pluginExtension the extension used to determine the plugin
  74348. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  74349. */
  74350. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74351. if (sceneFilename === void 0) { sceneFilename = ""; }
  74352. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74353. if (onProgress === void 0) { onProgress = null; }
  74354. if (pluginExtension === void 0) { pluginExtension = null; }
  74355. return new Promise(function (resolve, reject) {
  74356. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  74357. resolve({
  74358. meshes: meshes,
  74359. particleSystems: particleSystems,
  74360. skeletons: skeletons,
  74361. animationGroups: animationGroups
  74362. });
  74363. }, onProgress, function (scene, message, exception) {
  74364. reject(exception || new Error(message));
  74365. }, pluginExtension);
  74366. });
  74367. };
  74368. /**
  74369. * Load a scene
  74370. * @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)
  74371. * @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)
  74372. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74373. * @param onSuccess a callback with the scene when import succeeds
  74374. * @param onProgress a callback with a progress event for each file being loaded
  74375. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74376. * @param pluginExtension the extension used to determine the plugin
  74377. * @returns The loaded plugin
  74378. */
  74379. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  74380. if (onSuccess === void 0) { onSuccess = null; }
  74381. if (onProgress === void 0) { onProgress = null; }
  74382. if (onError === void 0) { onError = null; }
  74383. if (pluginExtension === void 0) { pluginExtension = null; }
  74384. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  74385. };
  74386. /**
  74387. * Load a scene
  74388. * @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)
  74389. * @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)
  74390. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74391. * @param onProgress a callback with a progress event for each file being loaded
  74392. * @param pluginExtension the extension used to determine the plugin
  74393. * @returns The loaded scene
  74394. */
  74395. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  74396. if (onProgress === void 0) { onProgress = null; }
  74397. if (pluginExtension === void 0) { pluginExtension = null; }
  74398. return new Promise(function (resolve, reject) {
  74399. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  74400. resolve(scene);
  74401. }, onProgress, function (scene, message, exception) {
  74402. reject(exception || new Error(message));
  74403. }, pluginExtension);
  74404. });
  74405. };
  74406. /**
  74407. * Append a scene
  74408. * @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)
  74409. * @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)
  74410. * @param scene is the instance of BABYLON.Scene to append to
  74411. * @param onSuccess a callback with the scene when import succeeds
  74412. * @param onProgress a callback with a progress event for each file being loaded
  74413. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74414. * @param pluginExtension the extension used to determine the plugin
  74415. * @returns The loaded plugin
  74416. */
  74417. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74418. if (sceneFilename === void 0) { sceneFilename = ""; }
  74419. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74420. if (onSuccess === void 0) { onSuccess = null; }
  74421. if (onProgress === void 0) { onProgress = null; }
  74422. if (onError === void 0) { onError = null; }
  74423. if (pluginExtension === void 0) { pluginExtension = null; }
  74424. if (!scene) {
  74425. BABYLON.Tools.Error("No scene available to append to");
  74426. return null;
  74427. }
  74428. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74429. if (!fileInfo) {
  74430. return null;
  74431. }
  74432. if (SceneLoader.ShowLoadingScreen) {
  74433. scene.getEngine().displayLoadingUI();
  74434. }
  74435. var loadingToken = {};
  74436. scene._addPendingData(loadingToken);
  74437. var disposeHandler = function () {
  74438. scene._removePendingData(loadingToken);
  74439. scene.getEngine().hideLoadingUI();
  74440. };
  74441. var errorHandler = function (message, exception) {
  74442. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  74443. if (onError) {
  74444. onError(scene, errorMessage, exception);
  74445. }
  74446. else {
  74447. BABYLON.Tools.Error(errorMessage);
  74448. // should the exception be thrown?
  74449. }
  74450. disposeHandler();
  74451. };
  74452. var progressHandler = onProgress ? function (event) {
  74453. try {
  74454. onProgress(event);
  74455. }
  74456. catch (e) {
  74457. errorHandler("Error in onProgress callback", e);
  74458. }
  74459. } : undefined;
  74460. var successHandler = function () {
  74461. if (onSuccess) {
  74462. try {
  74463. onSuccess(scene);
  74464. }
  74465. catch (e) {
  74466. errorHandler("Error in onSuccess callback", e);
  74467. }
  74468. }
  74469. scene._removePendingData(loadingToken);
  74470. };
  74471. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74472. if (plugin.load) {
  74473. var syncedPlugin = plugin;
  74474. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  74475. return;
  74476. }
  74477. scene.loadingPluginName = plugin.name;
  74478. successHandler();
  74479. }
  74480. else {
  74481. var asyncedPlugin = plugin;
  74482. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  74483. scene.loadingPluginName = plugin.name;
  74484. successHandler();
  74485. }).catch(function (error) {
  74486. errorHandler(error.message, error);
  74487. });
  74488. }
  74489. if (SceneLoader.ShowLoadingScreen) {
  74490. scene.executeWhenReady(function () {
  74491. scene.getEngine().hideLoadingUI();
  74492. });
  74493. }
  74494. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74495. };
  74496. /**
  74497. * Append a scene
  74498. * @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)
  74499. * @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)
  74500. * @param scene is the instance of BABYLON.Scene to append to
  74501. * @param onProgress a callback with a progress event for each file being loaded
  74502. * @param pluginExtension the extension used to determine the plugin
  74503. * @returns The given scene
  74504. */
  74505. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74506. if (sceneFilename === void 0) { sceneFilename = ""; }
  74507. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74508. if (onProgress === void 0) { onProgress = null; }
  74509. if (pluginExtension === void 0) { pluginExtension = null; }
  74510. return new Promise(function (resolve, reject) {
  74511. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  74512. resolve(scene);
  74513. }, onProgress, function (scene, message, exception) {
  74514. reject(exception || new Error(message));
  74515. }, pluginExtension);
  74516. });
  74517. };
  74518. /**
  74519. * Load a scene into an asset container
  74520. * @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)
  74521. * @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)
  74522. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  74523. * @param onSuccess a callback with the scene when import succeeds
  74524. * @param onProgress a callback with a progress event for each file being loaded
  74525. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74526. * @param pluginExtension the extension used to determine the plugin
  74527. * @returns The loaded plugin
  74528. */
  74529. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74530. if (sceneFilename === void 0) { sceneFilename = ""; }
  74531. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74532. if (onSuccess === void 0) { onSuccess = null; }
  74533. if (onProgress === void 0) { onProgress = null; }
  74534. if (onError === void 0) { onError = null; }
  74535. if (pluginExtension === void 0) { pluginExtension = null; }
  74536. if (!scene) {
  74537. BABYLON.Tools.Error("No scene available to load asset container to");
  74538. return null;
  74539. }
  74540. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74541. if (!fileInfo) {
  74542. return null;
  74543. }
  74544. var loadingToken = {};
  74545. scene._addPendingData(loadingToken);
  74546. var disposeHandler = function () {
  74547. scene._removePendingData(loadingToken);
  74548. };
  74549. var errorHandler = function (message, exception) {
  74550. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  74551. if (onError) {
  74552. onError(scene, errorMessage, exception);
  74553. }
  74554. else {
  74555. BABYLON.Tools.Error(errorMessage);
  74556. // should the exception be thrown?
  74557. }
  74558. disposeHandler();
  74559. };
  74560. var progressHandler = onProgress ? function (event) {
  74561. try {
  74562. onProgress(event);
  74563. }
  74564. catch (e) {
  74565. errorHandler("Error in onProgress callback", e);
  74566. }
  74567. } : undefined;
  74568. var successHandler = function (assets) {
  74569. if (onSuccess) {
  74570. try {
  74571. onSuccess(assets);
  74572. }
  74573. catch (e) {
  74574. errorHandler("Error in onSuccess callback", e);
  74575. }
  74576. }
  74577. scene._removePendingData(loadingToken);
  74578. };
  74579. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74580. if (plugin.loadAssetContainer) {
  74581. var syncedPlugin = plugin;
  74582. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  74583. if (!assetContainer) {
  74584. return;
  74585. }
  74586. scene.loadingPluginName = plugin.name;
  74587. successHandler(assetContainer);
  74588. }
  74589. else if (plugin.loadAssetContainerAsync) {
  74590. var asyncedPlugin = plugin;
  74591. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  74592. scene.loadingPluginName = plugin.name;
  74593. successHandler(assetContainer);
  74594. }).catch(function (error) {
  74595. errorHandler(error.message, error);
  74596. });
  74597. }
  74598. else {
  74599. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  74600. }
  74601. if (SceneLoader.ShowLoadingScreen) {
  74602. scene.executeWhenReady(function () {
  74603. scene.getEngine().hideLoadingUI();
  74604. });
  74605. }
  74606. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74607. };
  74608. /**
  74609. * Load a scene into an asset container
  74610. * @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)
  74611. * @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)
  74612. * @param scene is the instance of BABYLON.Scene to append to
  74613. * @param onProgress a callback with a progress event for each file being loaded
  74614. * @param pluginExtension the extension used to determine the plugin
  74615. * @returns The loaded asset container
  74616. */
  74617. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74618. if (sceneFilename === void 0) { sceneFilename = ""; }
  74619. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74620. if (onProgress === void 0) { onProgress = null; }
  74621. if (pluginExtension === void 0) { pluginExtension = null; }
  74622. return new Promise(function (resolve, reject) {
  74623. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  74624. resolve(assetContainer);
  74625. }, onProgress, function (scene, message, exception) {
  74626. reject(exception || new Error(message));
  74627. }, pluginExtension);
  74628. });
  74629. };
  74630. // Flags
  74631. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  74632. SceneLoader._ShowLoadingScreen = true;
  74633. SceneLoader._CleanBoneMatrixWeights = false;
  74634. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  74635. // Members
  74636. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  74637. SceneLoader._registeredPlugins = {};
  74638. return SceneLoader;
  74639. }());
  74640. BABYLON.SceneLoader = SceneLoader;
  74641. ;
  74642. })(BABYLON || (BABYLON = {}));
  74643. //# sourceMappingURL=babylon.sceneLoader.js.map
  74644. var BABYLON;
  74645. (function (BABYLON) {
  74646. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  74647. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74648. var parsedMaterial = parsedData.materials[index];
  74649. if (parsedMaterial.id === id) {
  74650. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74651. }
  74652. }
  74653. return null;
  74654. };
  74655. var isDescendantOf = function (mesh, names, hierarchyIds) {
  74656. for (var i in names) {
  74657. if (mesh.name === names[i]) {
  74658. hierarchyIds.push(mesh.id);
  74659. return true;
  74660. }
  74661. }
  74662. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  74663. hierarchyIds.push(mesh.id);
  74664. return true;
  74665. }
  74666. return false;
  74667. };
  74668. var logOperation = function (operation, producer) {
  74669. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  74670. };
  74671. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  74672. if (addToScene === void 0) { addToScene = false; }
  74673. var container = new BABYLON.AssetContainer(scene);
  74674. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74675. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74676. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74677. // and avoid problems with multiple concurrent .babylon loads.
  74678. var log = "importScene has failed JSON parse";
  74679. try {
  74680. var parsedData = JSON.parse(data);
  74681. log = "";
  74682. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74683. var index;
  74684. var cache;
  74685. // Lights
  74686. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  74687. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  74688. var parsedLight = parsedData.lights[index];
  74689. var light = BABYLON.Light.Parse(parsedLight, scene);
  74690. if (light) {
  74691. container.lights.push(light);
  74692. log += (index === 0 ? "\n\tLights:" : "");
  74693. log += "\n\t\t" + light.toString(fullDetails);
  74694. }
  74695. }
  74696. }
  74697. // Animations
  74698. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  74699. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  74700. var parsedAnimation = parsedData.animations[index];
  74701. var animation = BABYLON.Animation.Parse(parsedAnimation);
  74702. scene.animations.push(animation);
  74703. container.animations.push(animation);
  74704. log += (index === 0 ? "\n\tAnimations:" : "");
  74705. log += "\n\t\t" + animation.toString(fullDetails);
  74706. }
  74707. }
  74708. // Materials
  74709. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  74710. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74711. var parsedMaterial = parsedData.materials[index];
  74712. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74713. container.materials.push(mat);
  74714. log += (index === 0 ? "\n\tMaterials:" : "");
  74715. log += "\n\t\t" + mat.toString(fullDetails);
  74716. }
  74717. }
  74718. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74719. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  74720. var parsedMultiMaterial = parsedData.multiMaterials[index];
  74721. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74722. container.multiMaterials.push(mmat);
  74723. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  74724. log += "\n\t\t" + mmat.toString(fullDetails);
  74725. }
  74726. }
  74727. // Morph targets
  74728. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74729. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74730. var managerData = _a[_i];
  74731. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  74732. }
  74733. }
  74734. // Skeletons
  74735. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74736. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  74737. var parsedSkeleton = parsedData.skeletons[index];
  74738. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74739. container.skeletons.push(skeleton);
  74740. log += (index === 0 ? "\n\tSkeletons:" : "");
  74741. log += "\n\t\t" + skeleton.toString(fullDetails);
  74742. }
  74743. }
  74744. // Geometries
  74745. var geometries = parsedData.geometries;
  74746. if (geometries !== undefined && geometries !== null) {
  74747. var addedGeometry = new Array();
  74748. // Boxes
  74749. var boxes = geometries.boxes;
  74750. if (boxes !== undefined && boxes !== null) {
  74751. for (index = 0, cache = boxes.length; index < cache; index++) {
  74752. var parsedBox = boxes[index];
  74753. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  74754. }
  74755. }
  74756. // Spheres
  74757. var spheres = geometries.spheres;
  74758. if (spheres !== undefined && spheres !== null) {
  74759. for (index = 0, cache = spheres.length; index < cache; index++) {
  74760. var parsedSphere = spheres[index];
  74761. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  74762. }
  74763. }
  74764. // Cylinders
  74765. var cylinders = geometries.cylinders;
  74766. if (cylinders !== undefined && cylinders !== null) {
  74767. for (index = 0, cache = cylinders.length; index < cache; index++) {
  74768. var parsedCylinder = cylinders[index];
  74769. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  74770. }
  74771. }
  74772. // Toruses
  74773. var toruses = geometries.toruses;
  74774. if (toruses !== undefined && toruses !== null) {
  74775. for (index = 0, cache = toruses.length; index < cache; index++) {
  74776. var parsedTorus = toruses[index];
  74777. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  74778. }
  74779. }
  74780. // Grounds
  74781. var grounds = geometries.grounds;
  74782. if (grounds !== undefined && grounds !== null) {
  74783. for (index = 0, cache = grounds.length; index < cache; index++) {
  74784. var parsedGround = grounds[index];
  74785. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  74786. }
  74787. }
  74788. // Planes
  74789. var planes = geometries.planes;
  74790. if (planes !== undefined && planes !== null) {
  74791. for (index = 0, cache = planes.length; index < cache; index++) {
  74792. var parsedPlane = planes[index];
  74793. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  74794. }
  74795. }
  74796. // TorusKnots
  74797. var torusKnots = geometries.torusKnots;
  74798. if (torusKnots !== undefined && torusKnots !== null) {
  74799. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  74800. var parsedTorusKnot = torusKnots[index];
  74801. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  74802. }
  74803. }
  74804. // VertexData
  74805. var vertexData = geometries.vertexData;
  74806. if (vertexData !== undefined && vertexData !== null) {
  74807. for (index = 0, cache = vertexData.length; index < cache; index++) {
  74808. var parsedVertexData = vertexData[index];
  74809. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  74810. }
  74811. }
  74812. addedGeometry.forEach(function (g) {
  74813. if (g) {
  74814. container.geometries.push(g);
  74815. }
  74816. });
  74817. }
  74818. // Transform nodes
  74819. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  74820. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  74821. var parsedTransformNode = parsedData.transformNodes[index];
  74822. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  74823. container.transformNodes.push(node);
  74824. }
  74825. }
  74826. // Meshes
  74827. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74828. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74829. var parsedMesh = parsedData.meshes[index];
  74830. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74831. container.meshes.push(mesh);
  74832. log += (index === 0 ? "\n\tMeshes:" : "");
  74833. log += "\n\t\t" + mesh.toString(fullDetails);
  74834. }
  74835. }
  74836. // Cameras
  74837. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  74838. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  74839. var parsedCamera = parsedData.cameras[index];
  74840. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  74841. container.cameras.push(camera);
  74842. log += (index === 0 ? "\n\tCameras:" : "");
  74843. log += "\n\t\t" + camera.toString(fullDetails);
  74844. }
  74845. }
  74846. // Animation Groups
  74847. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  74848. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  74849. var parsedAnimationGroup = parsedData.animationGroups[index];
  74850. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  74851. container.animationGroups.push(animationGroup);
  74852. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  74853. log += "\n\t\t" + animationGroup.toString(fullDetails);
  74854. }
  74855. }
  74856. // Browsing all the graph to connect the dots
  74857. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  74858. var camera = scene.cameras[index];
  74859. if (camera._waitingParentId) {
  74860. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  74861. camera._waitingParentId = null;
  74862. }
  74863. }
  74864. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74865. var light_1 = scene.lights[index];
  74866. if (light_1 && light_1._waitingParentId) {
  74867. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  74868. light_1._waitingParentId = null;
  74869. }
  74870. }
  74871. // Connect parents & children and parse actions
  74872. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  74873. var transformNode = scene.transformNodes[index];
  74874. if (transformNode._waitingParentId) {
  74875. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  74876. transformNode._waitingParentId = null;
  74877. }
  74878. }
  74879. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74880. var mesh = scene.meshes[index];
  74881. if (mesh._waitingParentId) {
  74882. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  74883. mesh._waitingParentId = null;
  74884. }
  74885. }
  74886. // freeze world matrix application
  74887. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74888. var currentMesh = scene.meshes[index];
  74889. if (currentMesh._waitingFreezeWorldMatrix) {
  74890. currentMesh.freezeWorldMatrix();
  74891. currentMesh._waitingFreezeWorldMatrix = null;
  74892. }
  74893. else {
  74894. currentMesh.computeWorldMatrix(true);
  74895. }
  74896. }
  74897. // Lights exclusions / inclusions
  74898. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74899. var light_2 = scene.lights[index];
  74900. // Excluded check
  74901. if (light_2._excludedMeshesIds.length > 0) {
  74902. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  74903. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  74904. if (excludedMesh) {
  74905. light_2.excludedMeshes.push(excludedMesh);
  74906. }
  74907. }
  74908. light_2._excludedMeshesIds = [];
  74909. }
  74910. // Included check
  74911. if (light_2._includedOnlyMeshesIds.length > 0) {
  74912. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  74913. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  74914. if (includedOnlyMesh) {
  74915. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  74916. }
  74917. }
  74918. light_2._includedOnlyMeshesIds = [];
  74919. }
  74920. }
  74921. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  74922. // Actions (scene) Done last as it can access other objects.
  74923. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74924. var mesh = scene.meshes[index];
  74925. if (mesh._waitingActions) {
  74926. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  74927. mesh._waitingActions = null;
  74928. }
  74929. }
  74930. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  74931. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  74932. }
  74933. if (!addToScene) {
  74934. container.removeAllFromScene();
  74935. }
  74936. }
  74937. catch (err) {
  74938. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  74939. if (onError) {
  74940. onError(msg, err);
  74941. }
  74942. else {
  74943. BABYLON.Tools.Log(msg);
  74944. throw err;
  74945. }
  74946. }
  74947. finally {
  74948. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74949. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74950. }
  74951. }
  74952. return container;
  74953. };
  74954. BABYLON.SceneLoader.RegisterPlugin({
  74955. name: "babylon.js",
  74956. extensions: ".babylon",
  74957. canDirectLoad: function (data) {
  74958. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  74959. return true;
  74960. }
  74961. return false;
  74962. },
  74963. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  74964. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74965. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74966. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74967. // and avoid problems with multiple concurrent .babylon loads.
  74968. var log = "importMesh has failed JSON parse";
  74969. try {
  74970. var parsedData = JSON.parse(data);
  74971. log = "";
  74972. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74973. if (!meshesNames) {
  74974. meshesNames = null;
  74975. }
  74976. else if (!Array.isArray(meshesNames)) {
  74977. meshesNames = [meshesNames];
  74978. }
  74979. var hierarchyIds = new Array();
  74980. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74981. var loadedSkeletonsIds = [];
  74982. var loadedMaterialsIds = [];
  74983. var index;
  74984. var cache;
  74985. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74986. var parsedMesh = parsedData.meshes[index];
  74987. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  74988. if (meshesNames !== null) {
  74989. // Remove found mesh name from list.
  74990. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  74991. }
  74992. //Geometry?
  74993. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  74994. //does the file contain geometries?
  74995. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  74996. //find the correct geometry and add it to the scene
  74997. var found = false;
  74998. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  74999. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  75000. return;
  75001. }
  75002. else {
  75003. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  75004. if (parsedGeometryData.id === parsedMesh.geometryId) {
  75005. switch (geometryType) {
  75006. case "boxes":
  75007. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  75008. break;
  75009. case "spheres":
  75010. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  75011. break;
  75012. case "cylinders":
  75013. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  75014. break;
  75015. case "toruses":
  75016. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  75017. break;
  75018. case "grounds":
  75019. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  75020. break;
  75021. case "planes":
  75022. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  75023. break;
  75024. case "torusKnots":
  75025. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  75026. break;
  75027. case "vertexData":
  75028. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  75029. break;
  75030. }
  75031. found = true;
  75032. }
  75033. });
  75034. }
  75035. });
  75036. if (found === false) {
  75037. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  75038. }
  75039. }
  75040. }
  75041. // Material ?
  75042. if (parsedMesh.materialId) {
  75043. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  75044. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  75045. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  75046. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  75047. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  75048. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  75049. var subMatId = parsedMultiMaterial.materials[matIndex];
  75050. loadedMaterialsIds.push(subMatId);
  75051. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  75052. if (mat) {
  75053. log += "\n\tMaterial " + mat.toString(fullDetails);
  75054. }
  75055. }
  75056. loadedMaterialsIds.push(parsedMultiMaterial.id);
  75057. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  75058. if (mmat) {
  75059. materialFound = true;
  75060. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  75061. }
  75062. break;
  75063. }
  75064. }
  75065. }
  75066. if (materialFound === false) {
  75067. loadedMaterialsIds.push(parsedMesh.materialId);
  75068. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  75069. if (!mat) {
  75070. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  75071. }
  75072. else {
  75073. log += "\n\tMaterial " + mat.toString(fullDetails);
  75074. }
  75075. }
  75076. }
  75077. // Skeleton ?
  75078. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  75079. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  75080. if (skeletonAlreadyLoaded === false) {
  75081. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  75082. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  75083. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  75084. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  75085. skeletons.push(skeleton);
  75086. loadedSkeletonsIds.push(parsedSkeleton.id);
  75087. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  75088. }
  75089. }
  75090. }
  75091. }
  75092. // Morph targets ?
  75093. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  75094. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  75095. var managerData = _a[_i];
  75096. BABYLON.MorphTargetManager.Parse(managerData, scene);
  75097. }
  75098. }
  75099. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  75100. meshes.push(mesh);
  75101. log += "\n\tMesh " + mesh.toString(fullDetails);
  75102. }
  75103. }
  75104. // Connecting parents
  75105. var currentMesh;
  75106. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75107. currentMesh = scene.meshes[index];
  75108. if (currentMesh._waitingParentId) {
  75109. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  75110. currentMesh._waitingParentId = null;
  75111. }
  75112. }
  75113. // freeze and compute world matrix application
  75114. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75115. currentMesh = scene.meshes[index];
  75116. if (currentMesh._waitingFreezeWorldMatrix) {
  75117. currentMesh.freezeWorldMatrix();
  75118. currentMesh._waitingFreezeWorldMatrix = null;
  75119. }
  75120. else {
  75121. currentMesh.computeWorldMatrix(true);
  75122. }
  75123. }
  75124. }
  75125. // Particles
  75126. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  75127. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  75128. if (parser) {
  75129. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  75130. var parsedParticleSystem = parsedData.particleSystems[index];
  75131. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  75132. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  75133. }
  75134. }
  75135. }
  75136. }
  75137. return true;
  75138. }
  75139. catch (err) {
  75140. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  75141. if (onError) {
  75142. onError(msg, err);
  75143. }
  75144. else {
  75145. BABYLON.Tools.Log(msg);
  75146. throw err;
  75147. }
  75148. }
  75149. finally {
  75150. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75151. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75152. }
  75153. }
  75154. return false;
  75155. },
  75156. load: function (scene, data, rootUrl, onError) {
  75157. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75158. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75159. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75160. // and avoid problems with multiple concurrent .babylon loads.
  75161. var log = "importScene has failed JSON parse";
  75162. try {
  75163. var parsedData = JSON.parse(data);
  75164. log = "";
  75165. // Scene
  75166. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  75167. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  75168. }
  75169. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  75170. scene.autoClear = parsedData.autoClear;
  75171. }
  75172. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  75173. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  75174. }
  75175. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  75176. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  75177. }
  75178. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  75179. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  75180. }
  75181. // Fog
  75182. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  75183. scene.fogMode = parsedData.fogMode;
  75184. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  75185. scene.fogStart = parsedData.fogStart;
  75186. scene.fogEnd = parsedData.fogEnd;
  75187. scene.fogDensity = parsedData.fogDensity;
  75188. log += "\tFog mode for scene: ";
  75189. switch (scene.fogMode) {
  75190. // getters not compiling, so using hardcoded
  75191. case 1:
  75192. log += "exp\n";
  75193. break;
  75194. case 2:
  75195. log += "exp2\n";
  75196. break;
  75197. case 3:
  75198. log += "linear\n";
  75199. break;
  75200. }
  75201. }
  75202. //Physics
  75203. if (parsedData.physicsEnabled) {
  75204. var physicsPlugin;
  75205. if (parsedData.physicsEngine === "cannon") {
  75206. physicsPlugin = new BABYLON.CannonJSPlugin();
  75207. }
  75208. else if (parsedData.physicsEngine === "oimo") {
  75209. physicsPlugin = new BABYLON.OimoJSPlugin();
  75210. }
  75211. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  75212. //else - default engine, which is currently oimo
  75213. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  75214. scene.enablePhysics(physicsGravity, physicsPlugin);
  75215. }
  75216. // Metadata
  75217. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  75218. scene.metadata = parsedData.metadata;
  75219. }
  75220. //collisions, if defined. otherwise, default is true
  75221. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  75222. scene.collisionsEnabled = parsedData.collisionsEnabled;
  75223. }
  75224. scene.workerCollisions = !!parsedData.workerCollisions;
  75225. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  75226. if (!container) {
  75227. return false;
  75228. }
  75229. if (parsedData.autoAnimate) {
  75230. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  75231. }
  75232. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  75233. scene.setActiveCameraByID(parsedData.activeCameraID);
  75234. }
  75235. // Environment texture
  75236. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  75237. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  75238. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  75239. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  75240. if (parsedData.environmentTextureRotationY) {
  75241. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  75242. }
  75243. scene.environmentTexture = hdrTexture;
  75244. }
  75245. else {
  75246. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  75247. if (parsedData.environmentTextureRotationY) {
  75248. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  75249. }
  75250. scene.environmentTexture = cubeTexture;
  75251. }
  75252. if (parsedData.createDefaultSkybox === true) {
  75253. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  75254. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  75255. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  75256. }
  75257. }
  75258. // Finish
  75259. return true;
  75260. }
  75261. catch (err) {
  75262. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  75263. if (onError) {
  75264. onError(msg, err);
  75265. }
  75266. else {
  75267. BABYLON.Tools.Log(msg);
  75268. throw err;
  75269. }
  75270. }
  75271. finally {
  75272. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75273. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75274. }
  75275. }
  75276. return false;
  75277. },
  75278. loadAssetContainer: function (scene, data, rootUrl, onError) {
  75279. var container = loadAssetContainer(scene, data, rootUrl, onError);
  75280. return container;
  75281. }
  75282. });
  75283. })(BABYLON || (BABYLON = {}));
  75284. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  75285. var BABYLON;
  75286. (function (BABYLON) {
  75287. /**
  75288. * Class used to help managing file picking and drag'n'drop
  75289. */
  75290. var FilesInput = /** @class */ (function () {
  75291. /**
  75292. * Creates a new FilesInput
  75293. * @param engine defines the rendering engine
  75294. * @param scene defines the hosting scene
  75295. * @param sceneLoadedCallback callback called when scene is loaded
  75296. * @param progressCallback callback called to track progress
  75297. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  75298. * @param textureLoadingCallback callback called when a texture is loading
  75299. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  75300. * @param onReloadCallback callback called when a reload is requested
  75301. * @param errorCallback callback call if an error occurs
  75302. */
  75303. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  75304. /**
  75305. * Callback called when a file is processed
  75306. */
  75307. this.onProcessFileCallback = function () { return true; };
  75308. this._engine = engine;
  75309. this._currentScene = scene;
  75310. this._sceneLoadedCallback = sceneLoadedCallback;
  75311. this._progressCallback = progressCallback;
  75312. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  75313. this._textureLoadingCallback = textureLoadingCallback;
  75314. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  75315. this._onReloadCallback = onReloadCallback;
  75316. this._errorCallback = errorCallback;
  75317. }
  75318. /**
  75319. * Calls this function to listen to drag'n'drop events on a specific DOM element
  75320. * @param elementToMonitor defines the DOM element to track
  75321. */
  75322. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  75323. var _this = this;
  75324. if (elementToMonitor) {
  75325. this._elementToMonitor = elementToMonitor;
  75326. this._dragEnterHandler = function (e) { _this.drag(e); };
  75327. this._dragOverHandler = function (e) { _this.drag(e); };
  75328. this._dropHandler = function (e) { _this.drop(e); };
  75329. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  75330. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  75331. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  75332. }
  75333. };
  75334. /**
  75335. * Release all associated resources
  75336. */
  75337. FilesInput.prototype.dispose = function () {
  75338. if (!this._elementToMonitor) {
  75339. return;
  75340. }
  75341. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  75342. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  75343. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  75344. };
  75345. FilesInput.prototype.renderFunction = function () {
  75346. if (this._additionalRenderLoopLogicCallback) {
  75347. this._additionalRenderLoopLogicCallback();
  75348. }
  75349. if (this._currentScene) {
  75350. if (this._textureLoadingCallback) {
  75351. var remaining = this._currentScene.getWaitingItemsCount();
  75352. if (remaining > 0) {
  75353. this._textureLoadingCallback(remaining);
  75354. }
  75355. }
  75356. this._currentScene.render();
  75357. }
  75358. };
  75359. FilesInput.prototype.drag = function (e) {
  75360. e.stopPropagation();
  75361. e.preventDefault();
  75362. };
  75363. FilesInput.prototype.drop = function (eventDrop) {
  75364. eventDrop.stopPropagation();
  75365. eventDrop.preventDefault();
  75366. this.loadFiles(eventDrop);
  75367. };
  75368. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  75369. var _this = this;
  75370. var reader = folder.createReader();
  75371. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  75372. reader.readEntries(function (entries) {
  75373. remaining.count += entries.length;
  75374. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  75375. var entry = entries_1[_i];
  75376. if (entry.isFile) {
  75377. entry.file(function (file) {
  75378. file.correctName = relativePath + file.name;
  75379. files.push(file);
  75380. if (--remaining.count === 0) {
  75381. callback();
  75382. }
  75383. });
  75384. }
  75385. else if (entry.isDirectory) {
  75386. _this._traverseFolder(entry, files, remaining, callback);
  75387. }
  75388. }
  75389. if (--remaining.count) {
  75390. callback();
  75391. }
  75392. });
  75393. };
  75394. FilesInput.prototype._processFiles = function (files) {
  75395. for (var i = 0; i < files.length; i++) {
  75396. var name = files[i].correctName.toLowerCase();
  75397. var extension = name.split('.').pop();
  75398. if (!this.onProcessFileCallback(files[i], name, extension)) {
  75399. continue;
  75400. }
  75401. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  75402. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  75403. this._sceneFileToLoad = files[i];
  75404. }
  75405. FilesInput.FilesToLoad[name] = files[i];
  75406. }
  75407. };
  75408. /**
  75409. * Load files from a drop event
  75410. * @param event defines the drop event to use as source
  75411. */
  75412. FilesInput.prototype.loadFiles = function (event) {
  75413. var _this = this;
  75414. // Handling data transfer via drag'n'drop
  75415. if (event && event.dataTransfer && event.dataTransfer.files) {
  75416. this._filesToLoad = event.dataTransfer.files;
  75417. }
  75418. // Handling files from input files
  75419. if (event && event.target && event.target.files) {
  75420. this._filesToLoad = event.target.files;
  75421. }
  75422. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  75423. return;
  75424. }
  75425. if (this._startingProcessingFilesCallback) {
  75426. this._startingProcessingFilesCallback(this._filesToLoad);
  75427. }
  75428. if (this._filesToLoad && this._filesToLoad.length > 0) {
  75429. var files_1 = new Array();
  75430. var folders = [];
  75431. var items = event.dataTransfer ? event.dataTransfer.items : null;
  75432. for (var i = 0; i < this._filesToLoad.length; i++) {
  75433. var fileToLoad = this._filesToLoad[i];
  75434. var name_1 = fileToLoad.name.toLowerCase();
  75435. var entry = void 0;
  75436. fileToLoad.correctName = name_1;
  75437. if (items) {
  75438. var item = items[i];
  75439. if (item.getAsEntry) {
  75440. entry = item.getAsEntry();
  75441. }
  75442. else if (item.webkitGetAsEntry) {
  75443. entry = item.webkitGetAsEntry();
  75444. }
  75445. }
  75446. if (!entry) {
  75447. files_1.push(fileToLoad);
  75448. }
  75449. else {
  75450. if (entry.isDirectory) {
  75451. folders.push(entry);
  75452. }
  75453. else {
  75454. files_1.push(fileToLoad);
  75455. }
  75456. }
  75457. }
  75458. if (folders.length === 0) {
  75459. this._processFiles(files_1);
  75460. this._processReload();
  75461. }
  75462. else {
  75463. var remaining = { count: folders.length };
  75464. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  75465. var folder = folders_1[_i];
  75466. this._traverseFolder(folder, files_1, remaining, function () {
  75467. _this._processFiles(files_1);
  75468. if (remaining.count === 0) {
  75469. _this._processReload();
  75470. }
  75471. });
  75472. }
  75473. }
  75474. }
  75475. };
  75476. FilesInput.prototype._processReload = function () {
  75477. if (this._onReloadCallback) {
  75478. this._onReloadCallback(this._sceneFileToLoad);
  75479. }
  75480. else {
  75481. this.reload();
  75482. }
  75483. };
  75484. /**
  75485. * Reload the current scene from the loaded files
  75486. */
  75487. FilesInput.prototype.reload = function () {
  75488. var _this = this;
  75489. // If a scene file has been provided
  75490. if (this._sceneFileToLoad) {
  75491. if (this._currentScene) {
  75492. if (BABYLON.Tools.errorsCount > 0) {
  75493. BABYLON.Tools.ClearLogCache();
  75494. }
  75495. this._engine.stopRenderLoop();
  75496. }
  75497. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  75498. if (_this._progressCallback) {
  75499. _this._progressCallback(progress);
  75500. }
  75501. }).then(function (scene) {
  75502. if (_this._currentScene) {
  75503. _this._currentScene.dispose();
  75504. }
  75505. _this._currentScene = scene;
  75506. if (_this._sceneLoadedCallback) {
  75507. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  75508. }
  75509. // Wait for textures and shaders to be ready
  75510. _this._currentScene.executeWhenReady(function () {
  75511. _this._engine.runRenderLoop(function () {
  75512. _this.renderFunction();
  75513. });
  75514. });
  75515. }).catch(function (error) {
  75516. if (_this._errorCallback) {
  75517. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  75518. }
  75519. });
  75520. }
  75521. else {
  75522. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  75523. }
  75524. };
  75525. /**
  75526. * List of files ready to be loaded
  75527. */
  75528. FilesInput.FilesToLoad = {};
  75529. return FilesInput;
  75530. }());
  75531. BABYLON.FilesInput = FilesInput;
  75532. })(BABYLON || (BABYLON = {}));
  75533. //# sourceMappingURL=babylon.filesInput.js.map
  75534. var BABYLON;
  75535. (function (BABYLON) {
  75536. /**
  75537. * Class used to store custom tags
  75538. */
  75539. var Tags = /** @class */ (function () {
  75540. function Tags() {
  75541. }
  75542. /**
  75543. * Adds support for tags on the given object
  75544. * @param obj defines the object to use
  75545. */
  75546. Tags.EnableFor = function (obj) {
  75547. obj._tags = obj._tags || {};
  75548. obj.hasTags = function () {
  75549. return Tags.HasTags(obj);
  75550. };
  75551. obj.addTags = function (tagsString) {
  75552. return Tags.AddTagsTo(obj, tagsString);
  75553. };
  75554. obj.removeTags = function (tagsString) {
  75555. return Tags.RemoveTagsFrom(obj, tagsString);
  75556. };
  75557. obj.matchesTagsQuery = function (tagsQuery) {
  75558. return Tags.MatchesQuery(obj, tagsQuery);
  75559. };
  75560. };
  75561. /**
  75562. * Removes tags support
  75563. * @param obj defines the object to use
  75564. */
  75565. Tags.DisableFor = function (obj) {
  75566. delete obj._tags;
  75567. delete obj.hasTags;
  75568. delete obj.addTags;
  75569. delete obj.removeTags;
  75570. delete obj.matchesTagsQuery;
  75571. };
  75572. /**
  75573. * Gets a boolean indicating if the given object has tags
  75574. * @param obj defines the object to use
  75575. * @returns a boolean
  75576. */
  75577. Tags.HasTags = function (obj) {
  75578. if (!obj._tags) {
  75579. return false;
  75580. }
  75581. return !BABYLON.Tools.IsEmpty(obj._tags);
  75582. };
  75583. /**
  75584. * Gets the tags available on a given object
  75585. * @param obj defines the object to use
  75586. * @param asString defines if the tags must be returned as a string instead of an array of strings
  75587. * @returns the tags
  75588. */
  75589. Tags.GetTags = function (obj, asString) {
  75590. if (asString === void 0) { asString = true; }
  75591. if (!obj._tags) {
  75592. return null;
  75593. }
  75594. if (asString) {
  75595. var tagsArray = [];
  75596. for (var tag in obj._tags) {
  75597. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  75598. tagsArray.push(tag);
  75599. }
  75600. }
  75601. return tagsArray.join(" ");
  75602. }
  75603. else {
  75604. return obj._tags;
  75605. }
  75606. };
  75607. /**
  75608. * Adds tags to an object
  75609. * @param obj defines the object to use
  75610. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  75611. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  75612. */
  75613. Tags.AddTagsTo = function (obj, tagsString) {
  75614. if (!tagsString) {
  75615. return;
  75616. }
  75617. if (typeof tagsString !== "string") {
  75618. return;
  75619. }
  75620. var tags = tagsString.split(" ");
  75621. tags.forEach(function (tag, index, array) {
  75622. Tags._AddTagTo(obj, tag);
  75623. });
  75624. };
  75625. /**
  75626. * @hidden
  75627. */
  75628. Tags._AddTagTo = function (obj, tag) {
  75629. tag = tag.trim();
  75630. if (tag === "" || tag === "true" || tag === "false") {
  75631. return;
  75632. }
  75633. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  75634. return;
  75635. }
  75636. Tags.EnableFor(obj);
  75637. obj._tags[tag] = true;
  75638. };
  75639. /**
  75640. * Removes specific tags from a specific object
  75641. * @param obj defines the object to use
  75642. * @param tagsString defines the tags to remove
  75643. */
  75644. Tags.RemoveTagsFrom = function (obj, tagsString) {
  75645. if (!Tags.HasTags(obj)) {
  75646. return;
  75647. }
  75648. var tags = tagsString.split(" ");
  75649. for (var t in tags) {
  75650. Tags._RemoveTagFrom(obj, tags[t]);
  75651. }
  75652. };
  75653. /**
  75654. * @hidden
  75655. */
  75656. Tags._RemoveTagFrom = function (obj, tag) {
  75657. delete obj._tags[tag];
  75658. };
  75659. /**
  75660. * Defines if tags hosted on an object match a given query
  75661. * @param obj defines the object to use
  75662. * @param tagsQuery defines the tag query
  75663. * @returns a boolean
  75664. */
  75665. Tags.MatchesQuery = function (obj, tagsQuery) {
  75666. if (tagsQuery === undefined) {
  75667. return true;
  75668. }
  75669. if (tagsQuery === "") {
  75670. return Tags.HasTags(obj);
  75671. }
  75672. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  75673. };
  75674. return Tags;
  75675. }());
  75676. BABYLON.Tags = Tags;
  75677. })(BABYLON || (BABYLON = {}));
  75678. //# sourceMappingURL=babylon.tags.js.map
  75679. var BABYLON;
  75680. (function (BABYLON) {
  75681. /**
  75682. * Class used to evalaute queries containing `and` and `or` operators
  75683. */
  75684. var AndOrNotEvaluator = /** @class */ (function () {
  75685. function AndOrNotEvaluator() {
  75686. }
  75687. /**
  75688. * Evaluate a query
  75689. * @param query defines the query to evaluate
  75690. * @param evaluateCallback defines the callback used to filter result
  75691. * @returns true if the query matches
  75692. */
  75693. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  75694. if (!query.match(/\([^\(\)]*\)/g)) {
  75695. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  75696. }
  75697. else {
  75698. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  75699. // remove parenthesis
  75700. r = r.slice(1, r.length - 1);
  75701. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  75702. });
  75703. }
  75704. if (query === "true") {
  75705. return true;
  75706. }
  75707. if (query === "false") {
  75708. return false;
  75709. }
  75710. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  75711. };
  75712. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  75713. evaluateCallback = evaluateCallback || (function (r) {
  75714. return r === "true" ? true : false;
  75715. });
  75716. var result;
  75717. var or = parenthesisContent.split("||");
  75718. for (var i in or) {
  75719. if (or.hasOwnProperty(i)) {
  75720. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  75721. var and = ori.split("&&");
  75722. if (and.length > 1) {
  75723. for (var j = 0; j < and.length; ++j) {
  75724. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  75725. if (andj !== "true" && andj !== "false") {
  75726. if (andj[0] === "!") {
  75727. result = !evaluateCallback(andj.substring(1));
  75728. }
  75729. else {
  75730. result = evaluateCallback(andj);
  75731. }
  75732. }
  75733. else {
  75734. result = andj === "true" ? true : false;
  75735. }
  75736. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  75737. ori = "false";
  75738. break;
  75739. }
  75740. }
  75741. }
  75742. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  75743. result = true;
  75744. break;
  75745. }
  75746. // result equals false (or undefined)
  75747. if (ori !== "true" && ori !== "false") {
  75748. if (ori[0] === "!") {
  75749. result = !evaluateCallback(ori.substring(1));
  75750. }
  75751. else {
  75752. result = evaluateCallback(ori);
  75753. }
  75754. }
  75755. else {
  75756. result = ori === "true" ? true : false;
  75757. }
  75758. }
  75759. }
  75760. // the whole parenthesis scope is replaced by 'true' or 'false'
  75761. return result ? "true" : "false";
  75762. };
  75763. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  75764. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  75765. // remove whitespaces
  75766. r = r.replace(/[\s]/g, function () { return ""; });
  75767. return r.length % 2 ? "!" : "";
  75768. });
  75769. booleanString = booleanString.trim();
  75770. if (booleanString === "!true") {
  75771. booleanString = "false";
  75772. }
  75773. else if (booleanString === "!false") {
  75774. booleanString = "true";
  75775. }
  75776. return booleanString;
  75777. };
  75778. return AndOrNotEvaluator;
  75779. }());
  75780. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  75781. })(BABYLON || (BABYLON = {}));
  75782. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  75783. var BABYLON;
  75784. (function (BABYLON) {
  75785. /**
  75786. * Class used to enable access to IndexedDB
  75787. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  75788. */
  75789. var Database = /** @class */ (function () {
  75790. /**
  75791. * Creates a new Database
  75792. * @param urlToScene defines the url to load the scene
  75793. * @param callbackManifestChecked defines the callback to use when manifest is checked
  75794. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  75795. */
  75796. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  75797. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  75798. var _this = this;
  75799. // Handling various flavors of prefixed version of IndexedDB
  75800. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  75801. this.callbackManifestChecked = callbackManifestChecked;
  75802. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  75803. this.db = null;
  75804. this._enableSceneOffline = false;
  75805. this._enableTexturesOffline = false;
  75806. this.manifestVersionFound = 0;
  75807. this.mustUpdateRessources = false;
  75808. this.hasReachedQuota = false;
  75809. if (!Database.IDBStorageEnabled) {
  75810. this.callbackManifestChecked(true);
  75811. }
  75812. else {
  75813. if (disableManifestCheck) {
  75814. this._enableSceneOffline = true;
  75815. this._enableTexturesOffline = true;
  75816. this.manifestVersionFound = 1;
  75817. BABYLON.Tools.SetImmediate(function () {
  75818. _this.callbackManifestChecked(true);
  75819. });
  75820. }
  75821. else {
  75822. this._checkManifestFile();
  75823. }
  75824. }
  75825. }
  75826. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  75827. /**
  75828. * Gets a boolean indicating if scene must be saved in the database
  75829. */
  75830. get: function () {
  75831. return this._enableSceneOffline;
  75832. },
  75833. enumerable: true,
  75834. configurable: true
  75835. });
  75836. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  75837. /**
  75838. * Gets a boolean indicating if textures must be saved in the database
  75839. */
  75840. get: function () {
  75841. return this._enableTexturesOffline;
  75842. },
  75843. enumerable: true,
  75844. configurable: true
  75845. });
  75846. Database.prototype._checkManifestFile = function () {
  75847. var _this = this;
  75848. var noManifestFile = function () {
  75849. _this._enableSceneOffline = false;
  75850. _this._enableTexturesOffline = false;
  75851. _this.callbackManifestChecked(false);
  75852. };
  75853. var timeStampUsed = false;
  75854. var manifestURL = this.currentSceneUrl + ".manifest";
  75855. var xhr = new XMLHttpRequest();
  75856. if (navigator.onLine) {
  75857. // Adding a timestamp to by-pass browsers' cache
  75858. timeStampUsed = true;
  75859. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  75860. }
  75861. xhr.open("GET", manifestURL, true);
  75862. xhr.addEventListener("load", function () {
  75863. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  75864. try {
  75865. var manifestFile = JSON.parse(xhr.response);
  75866. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  75867. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  75868. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  75869. _this.manifestVersionFound = manifestFile.version;
  75870. }
  75871. if (_this.callbackManifestChecked) {
  75872. _this.callbackManifestChecked(true);
  75873. }
  75874. }
  75875. catch (ex) {
  75876. noManifestFile();
  75877. }
  75878. }
  75879. else {
  75880. noManifestFile();
  75881. }
  75882. }, false);
  75883. xhr.addEventListener("error", function (event) {
  75884. if (timeStampUsed) {
  75885. timeStampUsed = false;
  75886. // Let's retry without the timeStamp
  75887. // It could fail when coupled with HTML5 Offline API
  75888. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  75889. xhr.open("GET", retryManifestURL, true);
  75890. xhr.send();
  75891. }
  75892. else {
  75893. noManifestFile();
  75894. }
  75895. }, false);
  75896. try {
  75897. xhr.send();
  75898. }
  75899. catch (ex) {
  75900. BABYLON.Tools.Error("Error on XHR send request.");
  75901. this.callbackManifestChecked(false);
  75902. }
  75903. };
  75904. /**
  75905. * Open the database and make it available
  75906. * @param successCallback defines the callback to call on success
  75907. * @param errorCallback defines the callback to call on error
  75908. */
  75909. Database.prototype.openAsync = function (successCallback, errorCallback) {
  75910. var _this = this;
  75911. var handleError = function () {
  75912. _this.isSupported = false;
  75913. if (errorCallback)
  75914. errorCallback();
  75915. };
  75916. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  75917. // Your browser doesn't support IndexedDB
  75918. this.isSupported = false;
  75919. if (errorCallback)
  75920. errorCallback();
  75921. }
  75922. else {
  75923. // If the DB hasn't been opened or created yet
  75924. if (!this.db) {
  75925. this.hasReachedQuota = false;
  75926. this.isSupported = true;
  75927. var request = this.idbFactory.open("babylonjs", 1);
  75928. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  75929. request.onerror = function (event) {
  75930. handleError();
  75931. };
  75932. // executes when a version change transaction cannot complete due to other active transactions
  75933. request.onblocked = function (event) {
  75934. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  75935. handleError();
  75936. };
  75937. // DB has been opened successfully
  75938. request.onsuccess = function (event) {
  75939. _this.db = request.result;
  75940. successCallback();
  75941. };
  75942. // Initialization of the DB. Creating Scenes & Textures stores
  75943. request.onupgradeneeded = function (event) {
  75944. _this.db = (event.target).result;
  75945. if (_this.db) {
  75946. try {
  75947. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  75948. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  75949. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  75950. }
  75951. catch (ex) {
  75952. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  75953. handleError();
  75954. }
  75955. }
  75956. };
  75957. }
  75958. // DB has already been created and opened
  75959. else {
  75960. if (successCallback)
  75961. successCallback();
  75962. }
  75963. }
  75964. };
  75965. /**
  75966. * Loads an image from the database
  75967. * @param url defines the url to load from
  75968. * @param image defines the target DOM image
  75969. */
  75970. Database.prototype.loadImageFromDB = function (url, image) {
  75971. var _this = this;
  75972. var completeURL = Database._ReturnFullUrlLocation(url);
  75973. var saveAndLoadImage = function () {
  75974. if (!_this.hasReachedQuota && _this.db !== null) {
  75975. // the texture is not yet in the DB, let's try to save it
  75976. _this._saveImageIntoDBAsync(completeURL, image);
  75977. }
  75978. // If the texture is not in the DB and we've reached the DB quota limit
  75979. // let's load it directly from the web
  75980. else {
  75981. image.src = url;
  75982. }
  75983. };
  75984. if (!this.mustUpdateRessources) {
  75985. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  75986. }
  75987. // First time we're download the images or update requested in the manifest file by a version change
  75988. else {
  75989. saveAndLoadImage();
  75990. }
  75991. };
  75992. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  75993. if (this.isSupported && this.db !== null) {
  75994. var texture;
  75995. var transaction = this.db.transaction(["textures"]);
  75996. transaction.onabort = function (event) {
  75997. image.src = url;
  75998. };
  75999. transaction.oncomplete = function (event) {
  76000. var blobTextureURL;
  76001. if (texture) {
  76002. var URL = window.URL || window.webkitURL;
  76003. blobTextureURL = URL.createObjectURL(texture.data);
  76004. image.onerror = function () {
  76005. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  76006. image.src = url;
  76007. };
  76008. image.src = blobTextureURL;
  76009. }
  76010. else {
  76011. notInDBCallback();
  76012. }
  76013. };
  76014. var getRequest = transaction.objectStore("textures").get(url);
  76015. getRequest.onsuccess = function (event) {
  76016. texture = (event.target).result;
  76017. };
  76018. getRequest.onerror = function (event) {
  76019. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  76020. image.src = url;
  76021. };
  76022. }
  76023. else {
  76024. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76025. image.src = url;
  76026. }
  76027. };
  76028. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  76029. var _this = this;
  76030. if (this.isSupported) {
  76031. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  76032. var generateBlobUrl = function () {
  76033. var blobTextureURL;
  76034. if (blob) {
  76035. var URL = window.URL || window.webkitURL;
  76036. try {
  76037. blobTextureURL = URL.createObjectURL(blob);
  76038. }
  76039. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  76040. catch (ex) {
  76041. blobTextureURL = URL.createObjectURL(blob);
  76042. }
  76043. }
  76044. if (blobTextureURL) {
  76045. image.src = blobTextureURL;
  76046. }
  76047. };
  76048. if (Database.IsUASupportingBlobStorage) { // Create XHR
  76049. var xhr = new XMLHttpRequest(), blob;
  76050. xhr.open("GET", url, true);
  76051. xhr.responseType = "blob";
  76052. xhr.addEventListener("load", function () {
  76053. if (xhr.status === 200 && _this.db) {
  76054. // Blob as response (XHR2)
  76055. blob = xhr.response;
  76056. var transaction = _this.db.transaction(["textures"], "readwrite");
  76057. // the transaction could abort because of a QuotaExceededError error
  76058. transaction.onabort = function (event) {
  76059. try {
  76060. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76061. var srcElement = (event.srcElement || event.target);
  76062. var error = srcElement.error;
  76063. if (error && error.name === "QuotaExceededError") {
  76064. _this.hasReachedQuota = true;
  76065. }
  76066. }
  76067. catch (ex) { }
  76068. generateBlobUrl();
  76069. };
  76070. transaction.oncomplete = function (event) {
  76071. generateBlobUrl();
  76072. };
  76073. var newTexture = { textureUrl: url, data: blob };
  76074. try {
  76075. // Put the blob into the dabase
  76076. var addRequest = transaction.objectStore("textures").put(newTexture);
  76077. addRequest.onsuccess = function (event) {
  76078. };
  76079. addRequest.onerror = function (event) {
  76080. generateBlobUrl();
  76081. };
  76082. }
  76083. catch (ex) {
  76084. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  76085. if (ex.code === 25) {
  76086. Database.IsUASupportingBlobStorage = false;
  76087. }
  76088. image.src = url;
  76089. }
  76090. }
  76091. else {
  76092. image.src = url;
  76093. }
  76094. }, false);
  76095. xhr.addEventListener("error", function (event) {
  76096. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  76097. image.src = url;
  76098. }, false);
  76099. xhr.send();
  76100. }
  76101. else {
  76102. image.src = url;
  76103. }
  76104. }
  76105. else {
  76106. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76107. image.src = url;
  76108. }
  76109. };
  76110. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  76111. var _this = this;
  76112. var updateVersion = function () {
  76113. // the version is not yet in the DB or we need to update it
  76114. _this._saveVersionIntoDBAsync(url, versionLoaded);
  76115. };
  76116. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  76117. };
  76118. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  76119. var _this = this;
  76120. if (this.isSupported && this.db) {
  76121. var version;
  76122. try {
  76123. var transaction = this.db.transaction(["versions"]);
  76124. transaction.oncomplete = function (event) {
  76125. if (version) {
  76126. // If the version in the JSON file is different from the version in DB
  76127. if (_this.manifestVersionFound !== version.data) {
  76128. _this.mustUpdateRessources = true;
  76129. updateInDBCallback();
  76130. }
  76131. else {
  76132. callback(version.data);
  76133. }
  76134. }
  76135. // version was not found in DB
  76136. else {
  76137. _this.mustUpdateRessources = true;
  76138. updateInDBCallback();
  76139. }
  76140. };
  76141. transaction.onabort = function (event) {
  76142. callback(-1);
  76143. };
  76144. var getRequest = transaction.objectStore("versions").get(url);
  76145. getRequest.onsuccess = function (event) {
  76146. version = (event.target).result;
  76147. };
  76148. getRequest.onerror = function (event) {
  76149. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  76150. callback(-1);
  76151. };
  76152. }
  76153. catch (ex) {
  76154. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  76155. callback(-1);
  76156. }
  76157. }
  76158. else {
  76159. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76160. callback(-1);
  76161. }
  76162. };
  76163. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  76164. var _this = this;
  76165. if (this.isSupported && !this.hasReachedQuota && this.db) {
  76166. try {
  76167. // Open a transaction to the database
  76168. var transaction = this.db.transaction(["versions"], "readwrite");
  76169. // the transaction could abort because of a QuotaExceededError error
  76170. transaction.onabort = function (event) {
  76171. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76172. var error = event.srcElement['error'];
  76173. if (error && error.name === "QuotaExceededError") {
  76174. _this.hasReachedQuota = true;
  76175. }
  76176. }
  76177. catch (ex) { }
  76178. callback(-1);
  76179. };
  76180. transaction.oncomplete = function (event) {
  76181. callback(_this.manifestVersionFound);
  76182. };
  76183. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  76184. // Put the scene into the database
  76185. var addRequest = transaction.objectStore("versions").put(newVersion);
  76186. addRequest.onsuccess = function (event) {
  76187. };
  76188. addRequest.onerror = function (event) {
  76189. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  76190. };
  76191. }
  76192. catch (ex) {
  76193. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  76194. callback(-1);
  76195. }
  76196. }
  76197. else {
  76198. callback(-1);
  76199. }
  76200. };
  76201. /**
  76202. * Loads a file from database
  76203. * @param url defines the URL to load from
  76204. * @param sceneLoaded defines a callback to call on success
  76205. * @param progressCallBack defines a callback to call when progress changed
  76206. * @param errorCallback defines a callback to call on error
  76207. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  76208. */
  76209. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  76210. var _this = this;
  76211. var completeUrl = Database._ReturnFullUrlLocation(url);
  76212. var saveAndLoadFile = function () {
  76213. // the scene is not yet in the DB, let's try to save it
  76214. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  76215. };
  76216. this._checkVersionFromDB(completeUrl, function (version) {
  76217. if (version !== -1) {
  76218. if (!_this.mustUpdateRessources) {
  76219. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  76220. }
  76221. else {
  76222. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  76223. }
  76224. }
  76225. else {
  76226. if (errorCallback) {
  76227. errorCallback();
  76228. }
  76229. }
  76230. });
  76231. };
  76232. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  76233. if (this.isSupported && this.db) {
  76234. var targetStore;
  76235. if (url.indexOf(".babylon") !== -1) {
  76236. targetStore = "scenes";
  76237. }
  76238. else {
  76239. targetStore = "textures";
  76240. }
  76241. var file;
  76242. var transaction = this.db.transaction([targetStore]);
  76243. transaction.oncomplete = function (event) {
  76244. if (file) {
  76245. callback(file.data);
  76246. }
  76247. // file was not found in DB
  76248. else {
  76249. notInDBCallback();
  76250. }
  76251. };
  76252. transaction.onabort = function (event) {
  76253. notInDBCallback();
  76254. };
  76255. var getRequest = transaction.objectStore(targetStore).get(url);
  76256. getRequest.onsuccess = function (event) {
  76257. file = (event.target).result;
  76258. };
  76259. getRequest.onerror = function (event) {
  76260. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  76261. notInDBCallback();
  76262. };
  76263. }
  76264. else {
  76265. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76266. callback();
  76267. }
  76268. };
  76269. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  76270. var _this = this;
  76271. if (this.isSupported) {
  76272. var targetStore;
  76273. if (url.indexOf(".babylon") !== -1) {
  76274. targetStore = "scenes";
  76275. }
  76276. else {
  76277. targetStore = "textures";
  76278. }
  76279. // Create XHR
  76280. var xhr = new XMLHttpRequest();
  76281. var fileData;
  76282. xhr.open("GET", url + "?" + Date.now(), true);
  76283. if (useArrayBuffer) {
  76284. xhr.responseType = "arraybuffer";
  76285. }
  76286. if (progressCallback) {
  76287. xhr.onprogress = progressCallback;
  76288. }
  76289. xhr.addEventListener("load", function () {
  76290. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  76291. // Blob as response (XHR2)
  76292. //fileData = xhr.responseText;
  76293. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  76294. if (!_this.hasReachedQuota && _this.db) {
  76295. // Open a transaction to the database
  76296. var transaction = _this.db.transaction([targetStore], "readwrite");
  76297. // the transaction could abort because of a QuotaExceededError error
  76298. transaction.onabort = function (event) {
  76299. try {
  76300. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76301. var error = event.srcElement['error'];
  76302. if (error && error.name === "QuotaExceededError") {
  76303. _this.hasReachedQuota = true;
  76304. }
  76305. }
  76306. catch (ex) { }
  76307. callback(fileData);
  76308. };
  76309. transaction.oncomplete = function (event) {
  76310. callback(fileData);
  76311. };
  76312. var newFile;
  76313. if (targetStore === "scenes") {
  76314. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  76315. }
  76316. else {
  76317. newFile = { textureUrl: url, data: fileData };
  76318. }
  76319. try {
  76320. // Put the scene into the database
  76321. var addRequest = transaction.objectStore(targetStore).put(newFile);
  76322. addRequest.onsuccess = function (event) {
  76323. };
  76324. addRequest.onerror = function (event) {
  76325. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  76326. };
  76327. }
  76328. catch (ex) {
  76329. callback(fileData);
  76330. }
  76331. }
  76332. else {
  76333. callback(fileData);
  76334. }
  76335. }
  76336. else {
  76337. if (xhr.status >= 400 && errorCallback) {
  76338. errorCallback(xhr);
  76339. }
  76340. else {
  76341. callback();
  76342. }
  76343. }
  76344. }, false);
  76345. xhr.addEventListener("error", function (event) {
  76346. BABYLON.Tools.Error("error on XHR request.");
  76347. callback();
  76348. }, false);
  76349. xhr.send();
  76350. }
  76351. else {
  76352. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76353. callback();
  76354. }
  76355. };
  76356. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  76357. Database.IsUASupportingBlobStorage = true;
  76358. /** Gets a boolean indicating if Database storate is enabled */
  76359. Database.IDBStorageEnabled = true;
  76360. Database._ParseURL = function (url) {
  76361. var a = document.createElement('a');
  76362. a.href = url;
  76363. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  76364. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  76365. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  76366. return absLocation;
  76367. };
  76368. Database._ReturnFullUrlLocation = function (url) {
  76369. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  76370. return (Database._ParseURL(window.location.href) + url);
  76371. }
  76372. else {
  76373. return url;
  76374. }
  76375. };
  76376. return Database;
  76377. }());
  76378. BABYLON.Database = Database;
  76379. })(BABYLON || (BABYLON = {}));
  76380. //# sourceMappingURL=babylon.database.js.map
  76381. var BABYLON;
  76382. (function (BABYLON) {
  76383. var FresnelParameters = /** @class */ (function () {
  76384. function FresnelParameters() {
  76385. this._isEnabled = true;
  76386. this.leftColor = BABYLON.Color3.White();
  76387. this.rightColor = BABYLON.Color3.Black();
  76388. this.bias = 0;
  76389. this.power = 1;
  76390. }
  76391. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  76392. get: function () {
  76393. return this._isEnabled;
  76394. },
  76395. set: function (value) {
  76396. if (this._isEnabled === value) {
  76397. return;
  76398. }
  76399. this._isEnabled = value;
  76400. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  76401. },
  76402. enumerable: true,
  76403. configurable: true
  76404. });
  76405. FresnelParameters.prototype.clone = function () {
  76406. var newFresnelParameters = new FresnelParameters();
  76407. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  76408. return newFresnelParameters;
  76409. };
  76410. FresnelParameters.prototype.serialize = function () {
  76411. var serializationObject = {};
  76412. serializationObject.isEnabled = this.isEnabled;
  76413. serializationObject.leftColor = this.leftColor.asArray();
  76414. serializationObject.rightColor = this.rightColor.asArray();
  76415. serializationObject.bias = this.bias;
  76416. serializationObject.power = this.power;
  76417. return serializationObject;
  76418. };
  76419. FresnelParameters.Parse = function (parsedFresnelParameters) {
  76420. var fresnelParameters = new FresnelParameters();
  76421. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  76422. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  76423. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  76424. fresnelParameters.bias = parsedFresnelParameters.bias;
  76425. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  76426. return fresnelParameters;
  76427. };
  76428. return FresnelParameters;
  76429. }());
  76430. BABYLON.FresnelParameters = FresnelParameters;
  76431. })(BABYLON || (BABYLON = {}));
  76432. //# sourceMappingURL=babylon.fresnelParameters.js.map
  76433. var BABYLON;
  76434. (function (BABYLON) {
  76435. var MultiMaterial = /** @class */ (function (_super) {
  76436. __extends(MultiMaterial, _super);
  76437. function MultiMaterial(name, scene) {
  76438. var _this = _super.call(this, name, scene, true) || this;
  76439. scene.multiMaterials.push(_this);
  76440. _this.subMaterials = new Array();
  76441. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  76442. return _this;
  76443. }
  76444. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  76445. get: function () {
  76446. return this._subMaterials;
  76447. },
  76448. set: function (value) {
  76449. this._subMaterials = value;
  76450. this._hookArray(value);
  76451. },
  76452. enumerable: true,
  76453. configurable: true
  76454. });
  76455. MultiMaterial.prototype._hookArray = function (array) {
  76456. var _this = this;
  76457. var oldPush = array.push;
  76458. array.push = function () {
  76459. var items = [];
  76460. for (var _i = 0; _i < arguments.length; _i++) {
  76461. items[_i] = arguments[_i];
  76462. }
  76463. var result = oldPush.apply(array, items);
  76464. _this._markAllSubMeshesAsTexturesDirty();
  76465. return result;
  76466. };
  76467. var oldSplice = array.splice;
  76468. array.splice = function (index, deleteCount) {
  76469. var deleted = oldSplice.apply(array, [index, deleteCount]);
  76470. _this._markAllSubMeshesAsTexturesDirty();
  76471. return deleted;
  76472. };
  76473. };
  76474. // Properties
  76475. MultiMaterial.prototype.getSubMaterial = function (index) {
  76476. if (index < 0 || index >= this.subMaterials.length) {
  76477. return this.getScene().defaultMaterial;
  76478. }
  76479. return this.subMaterials[index];
  76480. };
  76481. MultiMaterial.prototype.getActiveTextures = function () {
  76482. var _a;
  76483. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  76484. if (subMaterial) {
  76485. return subMaterial.getActiveTextures();
  76486. }
  76487. else {
  76488. return [];
  76489. }
  76490. }));
  76491. };
  76492. // Methods
  76493. MultiMaterial.prototype.getClassName = function () {
  76494. return "MultiMaterial";
  76495. };
  76496. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76497. for (var index = 0; index < this.subMaterials.length; index++) {
  76498. var subMaterial = this.subMaterials[index];
  76499. if (subMaterial) {
  76500. if (subMaterial.storeEffectOnSubMeshes) {
  76501. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  76502. return false;
  76503. }
  76504. continue;
  76505. }
  76506. if (!subMaterial.isReady(mesh)) {
  76507. return false;
  76508. }
  76509. }
  76510. }
  76511. return true;
  76512. };
  76513. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  76514. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  76515. for (var index = 0; index < this.subMaterials.length; index++) {
  76516. var subMaterial = null;
  76517. var current = this.subMaterials[index];
  76518. if (cloneChildren && current) {
  76519. subMaterial = current.clone(name + "-" + current.name);
  76520. }
  76521. else {
  76522. subMaterial = this.subMaterials[index];
  76523. }
  76524. newMultiMaterial.subMaterials.push(subMaterial);
  76525. }
  76526. return newMultiMaterial;
  76527. };
  76528. MultiMaterial.prototype.serialize = function () {
  76529. var serializationObject = {};
  76530. serializationObject.name = this.name;
  76531. serializationObject.id = this.id;
  76532. if (BABYLON.Tags) {
  76533. serializationObject.tags = BABYLON.Tags.GetTags(this);
  76534. }
  76535. serializationObject.materials = [];
  76536. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  76537. var subMat = this.subMaterials[matIndex];
  76538. if (subMat) {
  76539. serializationObject.materials.push(subMat.id);
  76540. }
  76541. else {
  76542. serializationObject.materials.push(null);
  76543. }
  76544. }
  76545. return serializationObject;
  76546. };
  76547. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  76548. var scene = this.getScene();
  76549. if (!scene) {
  76550. return;
  76551. }
  76552. var index = scene.multiMaterials.indexOf(this);
  76553. if (index >= 0) {
  76554. scene.multiMaterials.splice(index, 1);
  76555. }
  76556. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  76557. };
  76558. return MultiMaterial;
  76559. }(BABYLON.Material));
  76560. BABYLON.MultiMaterial = MultiMaterial;
  76561. })(BABYLON || (BABYLON = {}));
  76562. //# sourceMappingURL=babylon.multiMaterial.js.map
  76563. var BABYLON;
  76564. (function (BABYLON) {
  76565. /**
  76566. * Manage the touch inputs to control the movement of a free camera.
  76567. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76568. */
  76569. var FreeCameraTouchInput = /** @class */ (function () {
  76570. function FreeCameraTouchInput() {
  76571. /**
  76572. * Defines the touch sensibility for rotation.
  76573. * The higher the faster.
  76574. */
  76575. this.touchAngularSensibility = 200000.0;
  76576. /**
  76577. * Defines the touch sensibility for move.
  76578. * The higher the faster.
  76579. */
  76580. this.touchMoveSensibility = 250.0;
  76581. this._offsetX = null;
  76582. this._offsetY = null;
  76583. this._pointerPressed = new Array();
  76584. }
  76585. /**
  76586. * Attach the input controls to a specific dom element to get the input from.
  76587. * @param element Defines the element the controls should be listened from
  76588. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76589. */
  76590. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  76591. var _this = this;
  76592. var previousPosition = null;
  76593. if (this._pointerInput === undefined) {
  76594. this._onLostFocus = function (evt) {
  76595. _this._offsetX = null;
  76596. _this._offsetY = null;
  76597. };
  76598. this._pointerInput = function (p, s) {
  76599. var evt = p.event;
  76600. if (evt.pointerType === "mouse") {
  76601. return;
  76602. }
  76603. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76604. if (!noPreventDefault) {
  76605. evt.preventDefault();
  76606. }
  76607. _this._pointerPressed.push(evt.pointerId);
  76608. if (_this._pointerPressed.length !== 1) {
  76609. return;
  76610. }
  76611. previousPosition = {
  76612. x: evt.clientX,
  76613. y: evt.clientY
  76614. };
  76615. }
  76616. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  76617. if (!noPreventDefault) {
  76618. evt.preventDefault();
  76619. }
  76620. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76621. if (index === -1) {
  76622. return;
  76623. }
  76624. _this._pointerPressed.splice(index, 1);
  76625. if (index != 0) {
  76626. return;
  76627. }
  76628. previousPosition = null;
  76629. _this._offsetX = null;
  76630. _this._offsetY = null;
  76631. }
  76632. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  76633. if (!noPreventDefault) {
  76634. evt.preventDefault();
  76635. }
  76636. if (!previousPosition) {
  76637. return;
  76638. }
  76639. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76640. if (index != 0) {
  76641. return;
  76642. }
  76643. _this._offsetX = evt.clientX - previousPosition.x;
  76644. _this._offsetY = -(evt.clientY - previousPosition.y);
  76645. }
  76646. };
  76647. }
  76648. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  76649. if (this._onLostFocus) {
  76650. element.addEventListener("blur", this._onLostFocus);
  76651. }
  76652. };
  76653. /**
  76654. * Detach the current controls from the specified dom element.
  76655. * @param element Defines the element to stop listening the inputs from
  76656. */
  76657. FreeCameraTouchInput.prototype.detachControl = function (element) {
  76658. if (this._pointerInput && element) {
  76659. if (this._observer) {
  76660. this.camera.getScene().onPointerObservable.remove(this._observer);
  76661. this._observer = null;
  76662. }
  76663. if (this._onLostFocus) {
  76664. element.removeEventListener("blur", this._onLostFocus);
  76665. this._onLostFocus = null;
  76666. }
  76667. this._pointerPressed = [];
  76668. this._offsetX = null;
  76669. this._offsetY = null;
  76670. }
  76671. };
  76672. /**
  76673. * Update the current camera state depending on the inputs that have been used this frame.
  76674. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76675. */
  76676. FreeCameraTouchInput.prototype.checkInputs = function () {
  76677. if (this._offsetX && this._offsetY) {
  76678. var camera = this.camera;
  76679. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  76680. if (this._pointerPressed.length > 1) {
  76681. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  76682. }
  76683. else {
  76684. var speed = camera._computeLocalCameraSpeed();
  76685. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  76686. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  76687. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  76688. }
  76689. }
  76690. };
  76691. /**
  76692. * Gets the class name of the current intput.
  76693. * @returns the class name
  76694. */
  76695. FreeCameraTouchInput.prototype.getClassName = function () {
  76696. return "FreeCameraTouchInput";
  76697. };
  76698. /**
  76699. * Get the friendly name associated with the input class.
  76700. * @returns the input friendly name
  76701. */
  76702. FreeCameraTouchInput.prototype.getSimpleName = function () {
  76703. return "touch";
  76704. };
  76705. __decorate([
  76706. BABYLON.serialize()
  76707. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  76708. __decorate([
  76709. BABYLON.serialize()
  76710. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  76711. return FreeCameraTouchInput;
  76712. }());
  76713. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  76714. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  76715. })(BABYLON || (BABYLON = {}));
  76716. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  76717. var BABYLON;
  76718. (function (BABYLON) {
  76719. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  76720. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  76721. });
  76722. /**
  76723. * This represents a FPS type of camera controlled by touch.
  76724. * This is like a universal camera minus the Gamepad controls.
  76725. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76726. */
  76727. var TouchCamera = /** @class */ (function (_super) {
  76728. __extends(TouchCamera, _super);
  76729. /**
  76730. * Instantiates a new touch camera.
  76731. * This represents a FPS type of camera controlled by touch.
  76732. * This is like a universal camera minus the Gamepad controls.
  76733. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76734. * @param name Define the name of the camera in the scene
  76735. * @param position Define the start position of the camera in the scene
  76736. * @param scene Define the scene the camera belongs to
  76737. */
  76738. function TouchCamera(name, position, scene) {
  76739. var _this = _super.call(this, name, position, scene) || this;
  76740. _this.inputs.addTouch();
  76741. _this._setupInputs();
  76742. return _this;
  76743. }
  76744. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  76745. /**
  76746. * Defines the touch sensibility for rotation.
  76747. * The higher the faster.
  76748. */
  76749. get: function () {
  76750. var touch = this.inputs.attached["touch"];
  76751. if (touch)
  76752. return touch.touchAngularSensibility;
  76753. return 0;
  76754. },
  76755. set: function (value) {
  76756. var touch = this.inputs.attached["touch"];
  76757. if (touch)
  76758. touch.touchAngularSensibility = value;
  76759. },
  76760. enumerable: true,
  76761. configurable: true
  76762. });
  76763. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  76764. /**
  76765. * Defines the touch sensibility for move.
  76766. * The higher the faster.
  76767. */
  76768. get: function () {
  76769. var touch = this.inputs.attached["touch"];
  76770. if (touch)
  76771. return touch.touchMoveSensibility;
  76772. return 0;
  76773. },
  76774. set: function (value) {
  76775. var touch = this.inputs.attached["touch"];
  76776. if (touch)
  76777. touch.touchMoveSensibility = value;
  76778. },
  76779. enumerable: true,
  76780. configurable: true
  76781. });
  76782. /**
  76783. * Gets the current object class name.
  76784. * @return the class name
  76785. */
  76786. TouchCamera.prototype.getClassName = function () {
  76787. return "TouchCamera";
  76788. };
  76789. /** @hidden */
  76790. TouchCamera.prototype._setupInputs = function () {
  76791. var mouse = this.inputs.attached["mouse"];
  76792. if (mouse) {
  76793. mouse.touchEnabled = false;
  76794. }
  76795. };
  76796. return TouchCamera;
  76797. }(BABYLON.FreeCamera));
  76798. BABYLON.TouchCamera = TouchCamera;
  76799. })(BABYLON || (BABYLON = {}));
  76800. //# sourceMappingURL=babylon.touchCamera.js.map
  76801. var BABYLON;
  76802. (function (BABYLON) {
  76803. var ProceduralTexture = /** @class */ (function (_super) {
  76804. __extends(ProceduralTexture, _super);
  76805. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  76806. if (fallbackTexture === void 0) { fallbackTexture = null; }
  76807. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76808. if (isCube === void 0) { isCube = false; }
  76809. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  76810. _this.isCube = isCube;
  76811. _this.isEnabled = true;
  76812. _this._currentRefreshId = -1;
  76813. _this._refreshRate = 1;
  76814. /**
  76815. * Event raised when the texture is generated
  76816. */
  76817. _this.onGeneratedObservable = new BABYLON.Observable();
  76818. _this._vertexBuffers = {};
  76819. _this._uniforms = new Array();
  76820. _this._samplers = new Array();
  76821. /** @hidden */
  76822. _this._textures = {};
  76823. _this._floats = {};
  76824. _this._ints = {};
  76825. _this._floatsArrays = {};
  76826. _this._colors3 = {};
  76827. _this._colors4 = {};
  76828. _this._vectors2 = {};
  76829. _this._vectors3 = {};
  76830. _this._matrices = {};
  76831. _this._fallbackTextureUsed = false;
  76832. _this._cachedDefines = "";
  76833. _this._contentUpdateId = -1;
  76834. scene = _this.getScene();
  76835. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  76836. if (!component) {
  76837. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  76838. scene._addComponent(component);
  76839. }
  76840. scene.proceduralTextures.push(_this);
  76841. _this._engine = scene.getEngine();
  76842. _this.name = name;
  76843. _this.isRenderTarget = true;
  76844. _this._size = size;
  76845. _this._generateMipMaps = generateMipMaps;
  76846. _this.setFragment(fragment);
  76847. _this._fallbackTexture = fallbackTexture;
  76848. if (isCube) {
  76849. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  76850. _this.setFloat("face", 0);
  76851. }
  76852. else {
  76853. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  76854. }
  76855. // VBO
  76856. var vertices = [];
  76857. vertices.push(1, 1);
  76858. vertices.push(-1, 1);
  76859. vertices.push(-1, -1);
  76860. vertices.push(1, -1);
  76861. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76862. _this._createIndexBuffer();
  76863. return _this;
  76864. }
  76865. /**
  76866. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  76867. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  76868. */
  76869. ProceduralTexture.prototype.getContent = function () {
  76870. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  76871. return this._contentData;
  76872. }
  76873. this._contentData = this.readPixels(0, 0, this._contentData);
  76874. this._contentUpdateId = this._currentRefreshId;
  76875. return this._contentData;
  76876. };
  76877. ProceduralTexture.prototype._createIndexBuffer = function () {
  76878. var engine = this._engine;
  76879. // Indices
  76880. var indices = [];
  76881. indices.push(0);
  76882. indices.push(1);
  76883. indices.push(2);
  76884. indices.push(0);
  76885. indices.push(2);
  76886. indices.push(3);
  76887. this._indexBuffer = engine.createIndexBuffer(indices);
  76888. };
  76889. /** @hidden */
  76890. ProceduralTexture.prototype._rebuild = function () {
  76891. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76892. if (vb) {
  76893. vb._rebuild();
  76894. }
  76895. this._createIndexBuffer();
  76896. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  76897. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  76898. }
  76899. };
  76900. ProceduralTexture.prototype.reset = function () {
  76901. if (this._effect === undefined) {
  76902. return;
  76903. }
  76904. var engine = this._engine;
  76905. engine._releaseEffect(this._effect);
  76906. };
  76907. ProceduralTexture.prototype._getDefines = function () {
  76908. return "";
  76909. };
  76910. ProceduralTexture.prototype.isReady = function () {
  76911. var _this = this;
  76912. var engine = this._engine;
  76913. var shaders;
  76914. if (!this._fragment) {
  76915. return false;
  76916. }
  76917. if (this._fallbackTextureUsed) {
  76918. return true;
  76919. }
  76920. var defines = this._getDefines();
  76921. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  76922. return true;
  76923. }
  76924. if (this._fragment.fragmentElement !== undefined) {
  76925. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  76926. }
  76927. else {
  76928. shaders = { vertex: "procedural", fragment: this._fragment };
  76929. }
  76930. this._cachedDefines = defines;
  76931. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  76932. _this.releaseInternalTexture();
  76933. if (_this._fallbackTexture) {
  76934. _this._texture = _this._fallbackTexture._texture;
  76935. if (_this._texture) {
  76936. _this._texture.incrementReferences();
  76937. }
  76938. }
  76939. _this._fallbackTextureUsed = true;
  76940. });
  76941. return this._effect.isReady();
  76942. };
  76943. ProceduralTexture.prototype.resetRefreshCounter = function () {
  76944. this._currentRefreshId = -1;
  76945. };
  76946. ProceduralTexture.prototype.setFragment = function (fragment) {
  76947. this._fragment = fragment;
  76948. };
  76949. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  76950. get: function () {
  76951. return this._refreshRate;
  76952. },
  76953. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  76954. set: function (value) {
  76955. this._refreshRate = value;
  76956. this.resetRefreshCounter();
  76957. },
  76958. enumerable: true,
  76959. configurable: true
  76960. });
  76961. /** @hidden */
  76962. ProceduralTexture.prototype._shouldRender = function () {
  76963. if (!this.isEnabled || !this.isReady() || !this._texture) {
  76964. if (this._texture) {
  76965. this._texture.isReady = false;
  76966. }
  76967. return false;
  76968. }
  76969. if (this._fallbackTextureUsed) {
  76970. return false;
  76971. }
  76972. if (this._currentRefreshId === -1) { // At least render once
  76973. this._currentRefreshId = 1;
  76974. return true;
  76975. }
  76976. if (this.refreshRate === this._currentRefreshId) {
  76977. this._currentRefreshId = 1;
  76978. return true;
  76979. }
  76980. this._currentRefreshId++;
  76981. return false;
  76982. };
  76983. ProceduralTexture.prototype.getRenderSize = function () {
  76984. return this._size;
  76985. };
  76986. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  76987. if (this._fallbackTextureUsed) {
  76988. return;
  76989. }
  76990. this.releaseInternalTexture();
  76991. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  76992. // Update properties
  76993. this._size = size;
  76994. this._generateMipMaps = generateMipMaps;
  76995. };
  76996. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  76997. if (this._uniforms.indexOf(uniformName) === -1) {
  76998. this._uniforms.push(uniformName);
  76999. }
  77000. };
  77001. ProceduralTexture.prototype.setTexture = function (name, texture) {
  77002. if (this._samplers.indexOf(name) === -1) {
  77003. this._samplers.push(name);
  77004. }
  77005. this._textures[name] = texture;
  77006. return this;
  77007. };
  77008. ProceduralTexture.prototype.setFloat = function (name, value) {
  77009. this._checkUniform(name);
  77010. this._floats[name] = value;
  77011. return this;
  77012. };
  77013. /**
  77014. * Set the value of an uniform to an integer value
  77015. * @param name defines the name of the uniform
  77016. * @param value defines the value to set
  77017. * @returns the current procedural texture
  77018. */
  77019. ProceduralTexture.prototype.setInt = function (name, value) {
  77020. this._checkUniform(name);
  77021. this._ints[name] = value;
  77022. return this;
  77023. };
  77024. ProceduralTexture.prototype.setFloats = function (name, value) {
  77025. this._checkUniform(name);
  77026. this._floatsArrays[name] = value;
  77027. return this;
  77028. };
  77029. ProceduralTexture.prototype.setColor3 = function (name, value) {
  77030. this._checkUniform(name);
  77031. this._colors3[name] = value;
  77032. return this;
  77033. };
  77034. ProceduralTexture.prototype.setColor4 = function (name, value) {
  77035. this._checkUniform(name);
  77036. this._colors4[name] = value;
  77037. return this;
  77038. };
  77039. ProceduralTexture.prototype.setVector2 = function (name, value) {
  77040. this._checkUniform(name);
  77041. this._vectors2[name] = value;
  77042. return this;
  77043. };
  77044. ProceduralTexture.prototype.setVector3 = function (name, value) {
  77045. this._checkUniform(name);
  77046. this._vectors3[name] = value;
  77047. return this;
  77048. };
  77049. ProceduralTexture.prototype.setMatrix = function (name, value) {
  77050. this._checkUniform(name);
  77051. this._matrices[name] = value;
  77052. return this;
  77053. };
  77054. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  77055. var scene = this.getScene();
  77056. if (!scene) {
  77057. return;
  77058. }
  77059. var engine = this._engine;
  77060. // Render
  77061. engine.enableEffect(this._effect);
  77062. engine.setState(false);
  77063. // Texture
  77064. for (var name in this._textures) {
  77065. this._effect.setTexture(name, this._textures[name]);
  77066. }
  77067. // Float
  77068. for (name in this._ints) {
  77069. this._effect.setInt(name, this._ints[name]);
  77070. }
  77071. // Float
  77072. for (name in this._floats) {
  77073. this._effect.setFloat(name, this._floats[name]);
  77074. }
  77075. // Floats
  77076. for (name in this._floatsArrays) {
  77077. this._effect.setArray(name, this._floatsArrays[name]);
  77078. }
  77079. // Color3
  77080. for (name in this._colors3) {
  77081. this._effect.setColor3(name, this._colors3[name]);
  77082. }
  77083. // Color4
  77084. for (name in this._colors4) {
  77085. var color = this._colors4[name];
  77086. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  77087. }
  77088. // Vector2
  77089. for (name in this._vectors2) {
  77090. this._effect.setVector2(name, this._vectors2[name]);
  77091. }
  77092. // Vector3
  77093. for (name in this._vectors3) {
  77094. this._effect.setVector3(name, this._vectors3[name]);
  77095. }
  77096. // Matrix
  77097. for (name in this._matrices) {
  77098. this._effect.setMatrix(name, this._matrices[name]);
  77099. }
  77100. if (!this._texture) {
  77101. return;
  77102. }
  77103. if (this.isCube) {
  77104. for (var face = 0; face < 6; face++) {
  77105. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  77106. // VBOs
  77107. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77108. this._effect.setFloat("face", face);
  77109. // Clear
  77110. engine.clear(scene.clearColor, true, true, true);
  77111. // Draw order
  77112. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77113. // Mipmaps
  77114. if (face === 5) {
  77115. engine.generateMipMapsForCubemap(this._texture);
  77116. }
  77117. }
  77118. }
  77119. else {
  77120. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  77121. // VBOs
  77122. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77123. // Clear
  77124. engine.clear(scene.clearColor, true, true, true);
  77125. // Draw order
  77126. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77127. }
  77128. // Unbind
  77129. engine.unBindFramebuffer(this._texture, this.isCube);
  77130. if (this.onGenerated) {
  77131. this.onGenerated();
  77132. }
  77133. this.onGeneratedObservable.notifyObservers(this);
  77134. };
  77135. ProceduralTexture.prototype.clone = function () {
  77136. var textureSize = this.getSize();
  77137. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  77138. // Base texture
  77139. newTexture.hasAlpha = this.hasAlpha;
  77140. newTexture.level = this.level;
  77141. // RenderTarget Texture
  77142. newTexture.coordinatesMode = this.coordinatesMode;
  77143. return newTexture;
  77144. };
  77145. ProceduralTexture.prototype.dispose = function () {
  77146. var scene = this.getScene();
  77147. if (!scene) {
  77148. return;
  77149. }
  77150. var index = scene.proceduralTextures.indexOf(this);
  77151. if (index >= 0) {
  77152. scene.proceduralTextures.splice(index, 1);
  77153. }
  77154. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77155. if (vertexBuffer) {
  77156. vertexBuffer.dispose();
  77157. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77158. }
  77159. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  77160. this._indexBuffer = null;
  77161. }
  77162. _super.prototype.dispose.call(this);
  77163. };
  77164. __decorate([
  77165. BABYLON.serialize()
  77166. ], ProceduralTexture.prototype, "_size", void 0);
  77167. __decorate([
  77168. BABYLON.serialize()
  77169. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  77170. __decorate([
  77171. BABYLON.serialize()
  77172. ], ProceduralTexture.prototype, "isEnabled", void 0);
  77173. __decorate([
  77174. BABYLON.serialize()
  77175. ], ProceduralTexture.prototype, "refreshRate", null);
  77176. return ProceduralTexture;
  77177. }(BABYLON.Texture));
  77178. BABYLON.ProceduralTexture = ProceduralTexture;
  77179. })(BABYLON || (BABYLON = {}));
  77180. //# sourceMappingURL=babylon.proceduralTexture.js.map
  77181. var BABYLON;
  77182. (function (BABYLON) {
  77183. /**
  77184. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  77185. * in a given scene.
  77186. */
  77187. var ProceduralTextureSceneComponent = /** @class */ (function () {
  77188. /**
  77189. * Creates a new instance of the component for the given scene
  77190. * @param scene Defines the scene to register the component in
  77191. */
  77192. function ProceduralTextureSceneComponent(scene) {
  77193. /**
  77194. * The component name helpfull to identify the component in the list of scene components.
  77195. */
  77196. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  77197. this.scene = scene;
  77198. this.scene.proceduralTextures = new Array();
  77199. scene.layers = new Array();
  77200. }
  77201. /**
  77202. * Registers the component in a given scene
  77203. */
  77204. ProceduralTextureSceneComponent.prototype.register = function () {
  77205. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  77206. };
  77207. /**
  77208. * Rebuilds the elements related to this component in case of
  77209. * context lost for instance.
  77210. */
  77211. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  77212. // Nothing to do here.
  77213. };
  77214. /**
  77215. * Disposes the component and the associated ressources.
  77216. */
  77217. ProceduralTextureSceneComponent.prototype.dispose = function () {
  77218. // Nothing to do here.
  77219. };
  77220. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  77221. if (this.scene.proceduralTexturesEnabled) {
  77222. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  77223. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  77224. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  77225. if (proceduralTexture._shouldRender()) {
  77226. proceduralTexture.render();
  77227. }
  77228. }
  77229. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  77230. }
  77231. };
  77232. return ProceduralTextureSceneComponent;
  77233. }());
  77234. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  77235. })(BABYLON || (BABYLON = {}));
  77236. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  77237. var BABYLON;
  77238. (function (BABYLON) {
  77239. var CustomProceduralTexture = /** @class */ (function (_super) {
  77240. __extends(CustomProceduralTexture, _super);
  77241. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  77242. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  77243. _this._animate = true;
  77244. _this._time = 0;
  77245. _this._texturePath = texturePath;
  77246. //Try to load json
  77247. _this.loadJson(texturePath);
  77248. _this.refreshRate = 1;
  77249. return _this;
  77250. }
  77251. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  77252. var _this = this;
  77253. var noConfigFile = function () {
  77254. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  77255. try {
  77256. _this.setFragment(_this._texturePath);
  77257. }
  77258. catch (ex) {
  77259. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  77260. }
  77261. };
  77262. var configFileUrl = jsonUrl + "/config.json";
  77263. var xhr = new XMLHttpRequest();
  77264. xhr.open("GET", configFileUrl, true);
  77265. xhr.addEventListener("load", function () {
  77266. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  77267. try {
  77268. _this._config = JSON.parse(xhr.response);
  77269. _this.updateShaderUniforms();
  77270. _this.updateTextures();
  77271. _this.setFragment(_this._texturePath + "/custom");
  77272. _this._animate = _this._config.animate;
  77273. _this.refreshRate = _this._config.refreshrate;
  77274. }
  77275. catch (ex) {
  77276. noConfigFile();
  77277. }
  77278. }
  77279. else {
  77280. noConfigFile();
  77281. }
  77282. }, false);
  77283. xhr.addEventListener("error", function () {
  77284. noConfigFile();
  77285. }, false);
  77286. try {
  77287. xhr.send();
  77288. }
  77289. catch (ex) {
  77290. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  77291. }
  77292. };
  77293. CustomProceduralTexture.prototype.isReady = function () {
  77294. if (!_super.prototype.isReady.call(this)) {
  77295. return false;
  77296. }
  77297. for (var name in this._textures) {
  77298. var texture = this._textures[name];
  77299. if (!texture.isReady()) {
  77300. return false;
  77301. }
  77302. }
  77303. return true;
  77304. };
  77305. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  77306. var scene = this.getScene();
  77307. if (this._animate && scene) {
  77308. this._time += scene.getAnimationRatio() * 0.03;
  77309. this.updateShaderUniforms();
  77310. }
  77311. _super.prototype.render.call(this, useCameraPostProcess);
  77312. };
  77313. CustomProceduralTexture.prototype.updateTextures = function () {
  77314. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  77315. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  77316. }
  77317. };
  77318. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  77319. if (this._config) {
  77320. for (var j = 0; j < this._config.uniforms.length; j++) {
  77321. var uniform = this._config.uniforms[j];
  77322. switch (uniform.type) {
  77323. case "float":
  77324. this.setFloat(uniform.name, uniform.value);
  77325. break;
  77326. case "color3":
  77327. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  77328. break;
  77329. case "color4":
  77330. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  77331. break;
  77332. case "vector2":
  77333. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  77334. break;
  77335. case "vector3":
  77336. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  77337. break;
  77338. }
  77339. }
  77340. }
  77341. this.setFloat("time", this._time);
  77342. };
  77343. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  77344. get: function () {
  77345. return this._animate;
  77346. },
  77347. set: function (value) {
  77348. this._animate = value;
  77349. },
  77350. enumerable: true,
  77351. configurable: true
  77352. });
  77353. return CustomProceduralTexture;
  77354. }(BABYLON.ProceduralTexture));
  77355. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  77356. })(BABYLON || (BABYLON = {}));
  77357. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  77358. var BABYLON;
  77359. (function (BABYLON) {
  77360. /**
  77361. * Manage the gamepad inputs to control a free camera.
  77362. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77363. */
  77364. var FreeCameraGamepadInput = /** @class */ (function () {
  77365. function FreeCameraGamepadInput() {
  77366. /**
  77367. * Defines the gamepad rotation sensiblity.
  77368. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77369. */
  77370. this.gamepadAngularSensibility = 200;
  77371. /**
  77372. * Defines the gamepad move sensiblity.
  77373. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77374. */
  77375. this.gamepadMoveSensibility = 40;
  77376. this._cameraTransform = BABYLON.Matrix.Identity();
  77377. this._deltaTransform = BABYLON.Vector3.Zero();
  77378. this._vector3 = BABYLON.Vector3.Zero();
  77379. this._vector2 = BABYLON.Vector2.Zero();
  77380. }
  77381. /**
  77382. * Attach the input controls to a specific dom element to get the input from.
  77383. * @param element Defines the element the controls should be listened from
  77384. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77385. */
  77386. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77387. var _this = this;
  77388. var manager = this.camera.getScene().gamepadManager;
  77389. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77390. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77391. // prioritize XBOX gamepads.
  77392. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77393. _this.gamepad = gamepad;
  77394. }
  77395. }
  77396. });
  77397. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77398. if (_this.gamepad === gamepad) {
  77399. _this.gamepad = null;
  77400. }
  77401. });
  77402. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77403. };
  77404. /**
  77405. * Detach the current controls from the specified dom element.
  77406. * @param element Defines the element to stop listening the inputs from
  77407. */
  77408. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  77409. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77410. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77411. this.gamepad = null;
  77412. };
  77413. /**
  77414. * Update the current camera state depending on the inputs that have been used this frame.
  77415. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77416. */
  77417. FreeCameraGamepadInput.prototype.checkInputs = function () {
  77418. if (this.gamepad && this.gamepad.leftStick) {
  77419. var camera = this.camera;
  77420. var LSValues = this.gamepad.leftStick;
  77421. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  77422. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77423. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  77424. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  77425. var RSValues = this.gamepad.rightStick;
  77426. if (RSValues) {
  77427. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  77428. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  77429. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  77430. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  77431. }
  77432. else {
  77433. RSValues = { x: 0, y: 0 };
  77434. }
  77435. if (!camera.rotationQuaternion) {
  77436. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  77437. }
  77438. else {
  77439. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  77440. }
  77441. var speed = camera._computeLocalCameraSpeed() * 50.0;
  77442. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  77443. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  77444. camera.cameraDirection.addInPlace(this._deltaTransform);
  77445. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  77446. camera.cameraRotation.addInPlace(this._vector2);
  77447. }
  77448. };
  77449. /**
  77450. * Gets the class name of the current intput.
  77451. * @returns the class name
  77452. */
  77453. FreeCameraGamepadInput.prototype.getClassName = function () {
  77454. return "FreeCameraGamepadInput";
  77455. };
  77456. /**
  77457. * Get the friendly name associated with the input class.
  77458. * @returns the input friendly name
  77459. */
  77460. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  77461. return "gamepad";
  77462. };
  77463. __decorate([
  77464. BABYLON.serialize()
  77465. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  77466. __decorate([
  77467. BABYLON.serialize()
  77468. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77469. return FreeCameraGamepadInput;
  77470. }());
  77471. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  77472. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  77473. })(BABYLON || (BABYLON = {}));
  77474. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  77475. var BABYLON;
  77476. (function (BABYLON) {
  77477. /**
  77478. * Manage the gamepad inputs to control an arc rotate camera.
  77479. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77480. */
  77481. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  77482. function ArcRotateCameraGamepadInput() {
  77483. /**
  77484. * Defines the gamepad rotation sensiblity.
  77485. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77486. */
  77487. this.gamepadRotationSensibility = 80;
  77488. /**
  77489. * Defines the gamepad move sensiblity.
  77490. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77491. */
  77492. this.gamepadMoveSensibility = 40;
  77493. }
  77494. /**
  77495. * Attach the input controls to a specific dom element to get the input from.
  77496. * @param element Defines the element the controls should be listened from
  77497. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77498. */
  77499. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77500. var _this = this;
  77501. var manager = this.camera.getScene().gamepadManager;
  77502. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77503. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77504. // prioritize XBOX gamepads.
  77505. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77506. _this.gamepad = gamepad;
  77507. }
  77508. }
  77509. });
  77510. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77511. if (_this.gamepad === gamepad) {
  77512. _this.gamepad = null;
  77513. }
  77514. });
  77515. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77516. };
  77517. /**
  77518. * Detach the current controls from the specified dom element.
  77519. * @param element Defines the element to stop listening the inputs from
  77520. */
  77521. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  77522. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77523. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77524. this.gamepad = null;
  77525. };
  77526. /**
  77527. * Update the current camera state depending on the inputs that have been used this frame.
  77528. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77529. */
  77530. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  77531. if (this.gamepad) {
  77532. var camera = this.camera;
  77533. var RSValues = this.gamepad.rightStick;
  77534. if (RSValues) {
  77535. if (RSValues.x != 0) {
  77536. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  77537. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  77538. camera.inertialAlphaOffset += normalizedRX;
  77539. }
  77540. }
  77541. if (RSValues.y != 0) {
  77542. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  77543. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  77544. camera.inertialBetaOffset += normalizedRY;
  77545. }
  77546. }
  77547. }
  77548. var LSValues = this.gamepad.leftStick;
  77549. if (LSValues && LSValues.y != 0) {
  77550. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77551. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  77552. this.camera.inertialRadiusOffset -= normalizedLY;
  77553. }
  77554. }
  77555. }
  77556. };
  77557. /**
  77558. * Gets the class name of the current intput.
  77559. * @returns the class name
  77560. */
  77561. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  77562. return "ArcRotateCameraGamepadInput";
  77563. };
  77564. /**
  77565. * Get the friendly name associated with the input class.
  77566. * @returns the input friendly name
  77567. */
  77568. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  77569. return "gamepad";
  77570. };
  77571. __decorate([
  77572. BABYLON.serialize()
  77573. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  77574. __decorate([
  77575. BABYLON.serialize()
  77576. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77577. return ArcRotateCameraGamepadInput;
  77578. }());
  77579. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  77580. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  77581. })(BABYLON || (BABYLON = {}));
  77582. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  77583. var BABYLON;
  77584. (function (BABYLON) {
  77585. /**
  77586. * Manager for handling gamepads
  77587. */
  77588. var GamepadManager = /** @class */ (function () {
  77589. /**
  77590. * Initializes the gamepad manager
  77591. * @param _scene BabylonJS scene
  77592. */
  77593. function GamepadManager(_scene) {
  77594. var _this = this;
  77595. this._scene = _scene;
  77596. this._babylonGamepads = [];
  77597. this._oneGamepadConnected = false;
  77598. /** @hidden */
  77599. this._isMonitoring = false;
  77600. /**
  77601. * observable to be triggered when the gamepad controller has been disconnected
  77602. */
  77603. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  77604. if (!BABYLON.Tools.IsWindowObjectExist()) {
  77605. this._gamepadEventSupported = false;
  77606. }
  77607. else {
  77608. this._gamepadEventSupported = 'GamepadEvent' in window;
  77609. this._gamepadSupport = (navigator.getGamepads ||
  77610. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  77611. }
  77612. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  77613. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  77614. for (var i in _this._babylonGamepads) {
  77615. var gamepad = _this._babylonGamepads[i];
  77616. if (gamepad && gamepad._isConnected) {
  77617. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  77618. }
  77619. }
  77620. });
  77621. this._onGamepadConnectedEvent = function (evt) {
  77622. var gamepad = evt.gamepad;
  77623. if (gamepad.index in _this._babylonGamepads) {
  77624. if (_this._babylonGamepads[gamepad.index].isConnected) {
  77625. return;
  77626. }
  77627. }
  77628. var newGamepad;
  77629. if (_this._babylonGamepads[gamepad.index]) {
  77630. newGamepad = _this._babylonGamepads[gamepad.index];
  77631. newGamepad.browserGamepad = gamepad;
  77632. newGamepad._isConnected = true;
  77633. }
  77634. else {
  77635. newGamepad = _this._addNewGamepad(gamepad);
  77636. }
  77637. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77638. _this._startMonitoringGamepads();
  77639. };
  77640. this._onGamepadDisconnectedEvent = function (evt) {
  77641. var gamepad = evt.gamepad;
  77642. // Remove the gamepad from the list of gamepads to monitor.
  77643. for (var i in _this._babylonGamepads) {
  77644. if (_this._babylonGamepads[i].index === gamepad.index) {
  77645. var disconnectedGamepad = _this._babylonGamepads[i];
  77646. disconnectedGamepad._isConnected = false;
  77647. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  77648. break;
  77649. }
  77650. }
  77651. };
  77652. if (this._gamepadSupport) {
  77653. //first add already-connected gamepads
  77654. this._updateGamepadObjects();
  77655. if (this._babylonGamepads.length) {
  77656. this._startMonitoringGamepads();
  77657. }
  77658. // Checking if the gamepad connected event is supported (like in Firefox)
  77659. if (this._gamepadEventSupported) {
  77660. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  77661. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  77662. }
  77663. else {
  77664. this._startMonitoringGamepads();
  77665. }
  77666. }
  77667. }
  77668. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  77669. /**
  77670. * The gamepads in the game pad manager
  77671. */
  77672. get: function () {
  77673. return this._babylonGamepads;
  77674. },
  77675. enumerable: true,
  77676. configurable: true
  77677. });
  77678. /**
  77679. * Get the gamepad controllers based on type
  77680. * @param type The type of gamepad controller
  77681. * @returns Nullable gamepad
  77682. */
  77683. GamepadManager.prototype.getGamepadByType = function (type) {
  77684. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  77685. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  77686. var gamepad = _a[_i];
  77687. if (gamepad && gamepad.type === type) {
  77688. return gamepad;
  77689. }
  77690. }
  77691. return null;
  77692. };
  77693. /**
  77694. * Disposes the gamepad manager
  77695. */
  77696. GamepadManager.prototype.dispose = function () {
  77697. if (this._gamepadEventSupported) {
  77698. if (this._onGamepadConnectedEvent) {
  77699. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  77700. }
  77701. if (this._onGamepadDisconnectedEvent) {
  77702. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  77703. }
  77704. this._onGamepadConnectedEvent = null;
  77705. this._onGamepadDisconnectedEvent = null;
  77706. }
  77707. this._babylonGamepads.forEach(function (gamepad) {
  77708. gamepad.dispose();
  77709. });
  77710. this.onGamepadConnectedObservable.clear();
  77711. this.onGamepadDisconnectedObservable.clear();
  77712. this._oneGamepadConnected = false;
  77713. this._stopMonitoringGamepads();
  77714. this._babylonGamepads = [];
  77715. };
  77716. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  77717. if (!this._oneGamepadConnected) {
  77718. this._oneGamepadConnected = true;
  77719. }
  77720. var newGamepad;
  77721. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  77722. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  77723. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  77724. }
  77725. // if pose is supported, use the (WebVR) pose enabled controller
  77726. else if (gamepad.pose) {
  77727. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  77728. }
  77729. else {
  77730. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  77731. }
  77732. this._babylonGamepads[newGamepad.index] = newGamepad;
  77733. return newGamepad;
  77734. };
  77735. GamepadManager.prototype._startMonitoringGamepads = function () {
  77736. if (!this._isMonitoring) {
  77737. this._isMonitoring = true;
  77738. //back-comp
  77739. if (!this._scene) {
  77740. this._checkGamepadsStatus();
  77741. }
  77742. }
  77743. };
  77744. GamepadManager.prototype._stopMonitoringGamepads = function () {
  77745. this._isMonitoring = false;
  77746. };
  77747. /** @hidden */
  77748. GamepadManager.prototype._checkGamepadsStatus = function () {
  77749. var _this = this;
  77750. // Hack to be compatible Chrome
  77751. this._updateGamepadObjects();
  77752. for (var i in this._babylonGamepads) {
  77753. var gamepad = this._babylonGamepads[i];
  77754. if (!gamepad || !gamepad.isConnected) {
  77755. continue;
  77756. }
  77757. gamepad.update();
  77758. }
  77759. if (this._isMonitoring && !this._scene) {
  77760. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  77761. }
  77762. };
  77763. // This function is called only on Chrome, which does not properly support
  77764. // connection/disconnection events and forces you to recopy again the gamepad object
  77765. GamepadManager.prototype._updateGamepadObjects = function () {
  77766. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  77767. for (var i = 0; i < gamepads.length; i++) {
  77768. var gamepad = gamepads[i];
  77769. if (gamepad) {
  77770. if (!this._babylonGamepads[gamepad.index]) {
  77771. var newGamepad = this._addNewGamepad(gamepad);
  77772. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77773. }
  77774. else {
  77775. // Forced to copy again this object for Chrome for unknown reason
  77776. this._babylonGamepads[i].browserGamepad = gamepad;
  77777. if (!this._babylonGamepads[i].isConnected) {
  77778. this._babylonGamepads[i]._isConnected = true;
  77779. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  77780. }
  77781. }
  77782. }
  77783. }
  77784. };
  77785. return GamepadManager;
  77786. }());
  77787. BABYLON.GamepadManager = GamepadManager;
  77788. })(BABYLON || (BABYLON = {}));
  77789. //# sourceMappingURL=babylon.gamepadManager.js.map
  77790. var BABYLON;
  77791. (function (BABYLON) {
  77792. /**
  77793. * Represents a gamepad control stick position
  77794. */
  77795. var StickValues = /** @class */ (function () {
  77796. /**
  77797. * Initializes the gamepad x and y control stick values
  77798. * @param x The x component of the gamepad control stick value
  77799. * @param y The y component of the gamepad control stick value
  77800. */
  77801. function StickValues(
  77802. /**
  77803. * The x component of the control stick
  77804. */
  77805. x,
  77806. /**
  77807. * The y component of the control stick
  77808. */
  77809. y) {
  77810. this.x = x;
  77811. this.y = y;
  77812. }
  77813. return StickValues;
  77814. }());
  77815. BABYLON.StickValues = StickValues;
  77816. /**
  77817. * Represents a gamepad
  77818. */
  77819. var Gamepad = /** @class */ (function () {
  77820. /**
  77821. * Initializes the gamepad
  77822. * @param id The id of the gamepad
  77823. * @param index The index of the gamepad
  77824. * @param browserGamepad The browser gamepad
  77825. * @param leftStickX The x component of the left joystick
  77826. * @param leftStickY The y component of the left joystick
  77827. * @param rightStickX The x component of the right joystick
  77828. * @param rightStickY The y component of the right joystick
  77829. */
  77830. function Gamepad(
  77831. /**
  77832. * The id of the gamepad
  77833. */
  77834. id,
  77835. /**
  77836. * The index of the gamepad
  77837. */
  77838. index,
  77839. /**
  77840. * The browser gamepad
  77841. */
  77842. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  77843. if (leftStickX === void 0) { leftStickX = 0; }
  77844. if (leftStickY === void 0) { leftStickY = 1; }
  77845. if (rightStickX === void 0) { rightStickX = 2; }
  77846. if (rightStickY === void 0) { rightStickY = 3; }
  77847. this.id = id;
  77848. this.index = index;
  77849. this.browserGamepad = browserGamepad;
  77850. this._leftStick = { x: 0, y: 0 };
  77851. this._rightStick = { x: 0, y: 0 };
  77852. /** @hidden */
  77853. this._isConnected = true;
  77854. /**
  77855. * Specifies whether the left control stick should be Y-inverted
  77856. */
  77857. this._invertLeftStickY = false;
  77858. this.type = Gamepad.GAMEPAD;
  77859. this._leftStickAxisX = leftStickX;
  77860. this._leftStickAxisY = leftStickY;
  77861. this._rightStickAxisX = rightStickX;
  77862. this._rightStickAxisY = rightStickY;
  77863. if (this.browserGamepad.axes.length >= 2) {
  77864. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77865. }
  77866. if (this.browserGamepad.axes.length >= 4) {
  77867. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77868. }
  77869. }
  77870. Object.defineProperty(Gamepad.prototype, "isConnected", {
  77871. /**
  77872. * Specifies if the gamepad has been connected
  77873. */
  77874. get: function () {
  77875. return this._isConnected;
  77876. },
  77877. enumerable: true,
  77878. configurable: true
  77879. });
  77880. /**
  77881. * Callback triggered when the left joystick has changed
  77882. * @param callback
  77883. */
  77884. Gamepad.prototype.onleftstickchanged = function (callback) {
  77885. this._onleftstickchanged = callback;
  77886. };
  77887. /**
  77888. * Callback triggered when the right joystick has changed
  77889. * @param callback
  77890. */
  77891. Gamepad.prototype.onrightstickchanged = function (callback) {
  77892. this._onrightstickchanged = callback;
  77893. };
  77894. Object.defineProperty(Gamepad.prototype, "leftStick", {
  77895. /**
  77896. * Gets the left joystick
  77897. */
  77898. get: function () {
  77899. return this._leftStick;
  77900. },
  77901. /**
  77902. * Sets the left joystick values
  77903. */
  77904. set: function (newValues) {
  77905. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  77906. this._onleftstickchanged(newValues);
  77907. }
  77908. this._leftStick = newValues;
  77909. },
  77910. enumerable: true,
  77911. configurable: true
  77912. });
  77913. Object.defineProperty(Gamepad.prototype, "rightStick", {
  77914. /**
  77915. * Gets the right joystick
  77916. */
  77917. get: function () {
  77918. return this._rightStick;
  77919. },
  77920. /**
  77921. * Sets the right joystick value
  77922. */
  77923. set: function (newValues) {
  77924. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  77925. this._onrightstickchanged(newValues);
  77926. }
  77927. this._rightStick = newValues;
  77928. },
  77929. enumerable: true,
  77930. configurable: true
  77931. });
  77932. /**
  77933. * Updates the gamepad joystick positions
  77934. */
  77935. Gamepad.prototype.update = function () {
  77936. if (this._leftStick) {
  77937. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77938. if (this._invertLeftStickY) {
  77939. this.leftStick.y *= -1;
  77940. }
  77941. }
  77942. if (this._rightStick) {
  77943. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77944. }
  77945. };
  77946. /**
  77947. * Disposes the gamepad
  77948. */
  77949. Gamepad.prototype.dispose = function () {
  77950. };
  77951. /**
  77952. * Represents a gamepad controller
  77953. */
  77954. Gamepad.GAMEPAD = 0;
  77955. /**
  77956. * Represents a generic controller
  77957. */
  77958. Gamepad.GENERIC = 1;
  77959. /**
  77960. * Represents an XBox controller
  77961. */
  77962. Gamepad.XBOX = 2;
  77963. /**
  77964. * Represents a pose-enabled controller
  77965. */
  77966. Gamepad.POSE_ENABLED = 3;
  77967. return Gamepad;
  77968. }());
  77969. BABYLON.Gamepad = Gamepad;
  77970. /**
  77971. * Represents a generic gamepad
  77972. */
  77973. var GenericPad = /** @class */ (function (_super) {
  77974. __extends(GenericPad, _super);
  77975. /**
  77976. * Initializes the generic gamepad
  77977. * @param id The id of the generic gamepad
  77978. * @param index The index of the generic gamepad
  77979. * @param browserGamepad The browser gamepad
  77980. */
  77981. function GenericPad(id, index, browserGamepad) {
  77982. var _this = _super.call(this, id, index, browserGamepad) || this;
  77983. /**
  77984. * Observable triggered when a button has been pressed
  77985. */
  77986. _this.onButtonDownObservable = new BABYLON.Observable();
  77987. /**
  77988. * Observable triggered when a button has been released
  77989. */
  77990. _this.onButtonUpObservable = new BABYLON.Observable();
  77991. _this.type = Gamepad.GENERIC;
  77992. _this._buttons = new Array(browserGamepad.buttons.length);
  77993. return _this;
  77994. }
  77995. /**
  77996. * Callback triggered when a button has been pressed
  77997. * @param callback Called when a button has been pressed
  77998. */
  77999. GenericPad.prototype.onbuttondown = function (callback) {
  78000. this._onbuttondown = callback;
  78001. };
  78002. /**
  78003. * Callback triggered when a button has been released
  78004. * @param callback Called when a button has been released
  78005. */
  78006. GenericPad.prototype.onbuttonup = function (callback) {
  78007. this._onbuttonup = callback;
  78008. };
  78009. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  78010. if (newValue !== currentValue) {
  78011. if (newValue === 1) {
  78012. if (this._onbuttondown) {
  78013. this._onbuttondown(buttonIndex);
  78014. }
  78015. this.onButtonDownObservable.notifyObservers(buttonIndex);
  78016. }
  78017. if (newValue === 0) {
  78018. if (this._onbuttonup) {
  78019. this._onbuttonup(buttonIndex);
  78020. }
  78021. this.onButtonUpObservable.notifyObservers(buttonIndex);
  78022. }
  78023. }
  78024. return newValue;
  78025. };
  78026. /**
  78027. * Updates the generic gamepad
  78028. */
  78029. GenericPad.prototype.update = function () {
  78030. _super.prototype.update.call(this);
  78031. for (var index = 0; index < this._buttons.length; index++) {
  78032. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  78033. }
  78034. };
  78035. /**
  78036. * Disposes the generic gamepad
  78037. */
  78038. GenericPad.prototype.dispose = function () {
  78039. _super.prototype.dispose.call(this);
  78040. this.onButtonDownObservable.clear();
  78041. this.onButtonUpObservable.clear();
  78042. };
  78043. return GenericPad;
  78044. }(Gamepad));
  78045. BABYLON.GenericPad = GenericPad;
  78046. })(BABYLON || (BABYLON = {}));
  78047. //# sourceMappingURL=babylon.gamepad.js.map
  78048. var BABYLON;
  78049. (function (BABYLON) {
  78050. /**
  78051. * Defines supported buttons for XBox360 compatible gamepads
  78052. */
  78053. var Xbox360Button;
  78054. (function (Xbox360Button) {
  78055. /** A */
  78056. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  78057. /** B */
  78058. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  78059. /** X */
  78060. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  78061. /** Y */
  78062. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  78063. /** Start */
  78064. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  78065. /** Back */
  78066. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  78067. /** Left button */
  78068. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  78069. /** Right button */
  78070. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  78071. /** Left stick */
  78072. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  78073. /** Right stick */
  78074. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  78075. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  78076. /** Defines values for XBox360 DPad */
  78077. var Xbox360Dpad;
  78078. (function (Xbox360Dpad) {
  78079. /** Up */
  78080. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  78081. /** Down */
  78082. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  78083. /** Left */
  78084. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  78085. /** Right */
  78086. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  78087. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  78088. /**
  78089. * Defines a XBox360 gamepad
  78090. */
  78091. var Xbox360Pad = /** @class */ (function (_super) {
  78092. __extends(Xbox360Pad, _super);
  78093. /**
  78094. * Creates a new XBox360 gamepad object
  78095. * @param id defines the id of this gamepad
  78096. * @param index defines its index
  78097. * @param gamepad defines the internal HTML gamepad object
  78098. * @param xboxOne defines if it is a XBox One gamepad
  78099. */
  78100. function Xbox360Pad(id, index, gamepad, xboxOne) {
  78101. if (xboxOne === void 0) { xboxOne = false; }
  78102. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  78103. _this._leftTrigger = 0;
  78104. _this._rightTrigger = 0;
  78105. /** Observable raised when a button is pressed */
  78106. _this.onButtonDownObservable = new BABYLON.Observable();
  78107. /** Observable raised when a button is released */
  78108. _this.onButtonUpObservable = new BABYLON.Observable();
  78109. /** Observable raised when a pad is pressed */
  78110. _this.onPadDownObservable = new BABYLON.Observable();
  78111. /** Observable raised when a pad is released */
  78112. _this.onPadUpObservable = new BABYLON.Observable();
  78113. _this._buttonA = 0;
  78114. _this._buttonB = 0;
  78115. _this._buttonX = 0;
  78116. _this._buttonY = 0;
  78117. _this._buttonBack = 0;
  78118. _this._buttonStart = 0;
  78119. _this._buttonLB = 0;
  78120. _this._buttonRB = 0;
  78121. _this._buttonLeftStick = 0;
  78122. _this._buttonRightStick = 0;
  78123. _this._dPadUp = 0;
  78124. _this._dPadDown = 0;
  78125. _this._dPadLeft = 0;
  78126. _this._dPadRight = 0;
  78127. _this._isXboxOnePad = false;
  78128. _this.type = BABYLON.Gamepad.XBOX;
  78129. _this._isXboxOnePad = xboxOne;
  78130. return _this;
  78131. }
  78132. /**
  78133. * Defines the callback to call when left trigger is pressed
  78134. * @param callback defines the callback to use
  78135. */
  78136. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  78137. this._onlefttriggerchanged = callback;
  78138. };
  78139. /**
  78140. * Defines the callback to call when right trigger is pressed
  78141. * @param callback defines the callback to use
  78142. */
  78143. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  78144. this._onrighttriggerchanged = callback;
  78145. };
  78146. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  78147. /**
  78148. * Gets the left trigger value
  78149. */
  78150. get: function () {
  78151. return this._leftTrigger;
  78152. },
  78153. /**
  78154. * Sets the left trigger value
  78155. */
  78156. set: function (newValue) {
  78157. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  78158. this._onlefttriggerchanged(newValue);
  78159. }
  78160. this._leftTrigger = newValue;
  78161. },
  78162. enumerable: true,
  78163. configurable: true
  78164. });
  78165. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  78166. /**
  78167. * Gets the right trigger value
  78168. */
  78169. get: function () {
  78170. return this._rightTrigger;
  78171. },
  78172. /**
  78173. * Sets the right trigger value
  78174. */
  78175. set: function (newValue) {
  78176. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  78177. this._onrighttriggerchanged(newValue);
  78178. }
  78179. this._rightTrigger = newValue;
  78180. },
  78181. enumerable: true,
  78182. configurable: true
  78183. });
  78184. /**
  78185. * Defines the callback to call when a button is pressed
  78186. * @param callback defines the callback to use
  78187. */
  78188. Xbox360Pad.prototype.onbuttondown = function (callback) {
  78189. this._onbuttondown = callback;
  78190. };
  78191. /**
  78192. * Defines the callback to call when a button is released
  78193. * @param callback defines the callback to use
  78194. */
  78195. Xbox360Pad.prototype.onbuttonup = function (callback) {
  78196. this._onbuttonup = callback;
  78197. };
  78198. /**
  78199. * Defines the callback to call when a pad is pressed
  78200. * @param callback defines the callback to use
  78201. */
  78202. Xbox360Pad.prototype.ondpaddown = function (callback) {
  78203. this._ondpaddown = callback;
  78204. };
  78205. /**
  78206. * Defines the callback to call when a pad is released
  78207. * @param callback defines the callback to use
  78208. */
  78209. Xbox360Pad.prototype.ondpadup = function (callback) {
  78210. this._ondpadup = callback;
  78211. };
  78212. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  78213. if (newValue !== currentValue) {
  78214. if (newValue === 1) {
  78215. if (this._onbuttondown) {
  78216. this._onbuttondown(buttonType);
  78217. }
  78218. this.onButtonDownObservable.notifyObservers(buttonType);
  78219. }
  78220. if (newValue === 0) {
  78221. if (this._onbuttonup) {
  78222. this._onbuttonup(buttonType);
  78223. }
  78224. this.onButtonUpObservable.notifyObservers(buttonType);
  78225. }
  78226. }
  78227. return newValue;
  78228. };
  78229. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  78230. if (newValue !== currentValue) {
  78231. if (newValue === 1) {
  78232. if (this._ondpaddown) {
  78233. this._ondpaddown(buttonType);
  78234. }
  78235. this.onPadDownObservable.notifyObservers(buttonType);
  78236. }
  78237. if (newValue === 0) {
  78238. if (this._ondpadup) {
  78239. this._ondpadup(buttonType);
  78240. }
  78241. this.onPadUpObservable.notifyObservers(buttonType);
  78242. }
  78243. }
  78244. return newValue;
  78245. };
  78246. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  78247. /**
  78248. * Gets the value of the `A` button
  78249. */
  78250. get: function () {
  78251. return this._buttonA;
  78252. },
  78253. /**
  78254. * Sets the value of the `A` button
  78255. */
  78256. set: function (value) {
  78257. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  78258. },
  78259. enumerable: true,
  78260. configurable: true
  78261. });
  78262. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  78263. /**
  78264. * Gets the value of the `B` button
  78265. */
  78266. get: function () {
  78267. return this._buttonB;
  78268. },
  78269. /**
  78270. * Sets the value of the `B` button
  78271. */
  78272. set: function (value) {
  78273. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  78274. },
  78275. enumerable: true,
  78276. configurable: true
  78277. });
  78278. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  78279. /**
  78280. * Gets the value of the `X` button
  78281. */
  78282. get: function () {
  78283. return this._buttonX;
  78284. },
  78285. /**
  78286. * Sets the value of the `X` button
  78287. */
  78288. set: function (value) {
  78289. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  78290. },
  78291. enumerable: true,
  78292. configurable: true
  78293. });
  78294. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  78295. /**
  78296. * Gets the value of the `Y` button
  78297. */
  78298. get: function () {
  78299. return this._buttonY;
  78300. },
  78301. /**
  78302. * Sets the value of the `Y` button
  78303. */
  78304. set: function (value) {
  78305. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  78306. },
  78307. enumerable: true,
  78308. configurable: true
  78309. });
  78310. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  78311. /**
  78312. * Gets the value of the `Start` button
  78313. */
  78314. get: function () {
  78315. return this._buttonStart;
  78316. },
  78317. /**
  78318. * Sets the value of the `Start` button
  78319. */
  78320. set: function (value) {
  78321. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  78322. },
  78323. enumerable: true,
  78324. configurable: true
  78325. });
  78326. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  78327. /**
  78328. * Gets the value of the `Back` button
  78329. */
  78330. get: function () {
  78331. return this._buttonBack;
  78332. },
  78333. /**
  78334. * Sets the value of the `Back` button
  78335. */
  78336. set: function (value) {
  78337. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  78338. },
  78339. enumerable: true,
  78340. configurable: true
  78341. });
  78342. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  78343. /**
  78344. * Gets the value of the `Left` button
  78345. */
  78346. get: function () {
  78347. return this._buttonLB;
  78348. },
  78349. /**
  78350. * Sets the value of the `Left` button
  78351. */
  78352. set: function (value) {
  78353. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  78354. },
  78355. enumerable: true,
  78356. configurable: true
  78357. });
  78358. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  78359. /**
  78360. * Gets the value of the `Right` button
  78361. */
  78362. get: function () {
  78363. return this._buttonRB;
  78364. },
  78365. /**
  78366. * Sets the value of the `Right` button
  78367. */
  78368. set: function (value) {
  78369. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  78370. },
  78371. enumerable: true,
  78372. configurable: true
  78373. });
  78374. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  78375. /**
  78376. * Gets the value of the Left joystick
  78377. */
  78378. get: function () {
  78379. return this._buttonLeftStick;
  78380. },
  78381. /**
  78382. * Sets the value of the Left joystick
  78383. */
  78384. set: function (value) {
  78385. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  78386. },
  78387. enumerable: true,
  78388. configurable: true
  78389. });
  78390. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  78391. /**
  78392. * Gets the value of the Right joystick
  78393. */
  78394. get: function () {
  78395. return this._buttonRightStick;
  78396. },
  78397. /**
  78398. * Sets the value of the Right joystick
  78399. */
  78400. set: function (value) {
  78401. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  78402. },
  78403. enumerable: true,
  78404. configurable: true
  78405. });
  78406. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  78407. /**
  78408. * Gets the value of D-pad up
  78409. */
  78410. get: function () {
  78411. return this._dPadUp;
  78412. },
  78413. /**
  78414. * Sets the value of D-pad up
  78415. */
  78416. set: function (value) {
  78417. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  78418. },
  78419. enumerable: true,
  78420. configurable: true
  78421. });
  78422. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  78423. /**
  78424. * Gets the value of D-pad down
  78425. */
  78426. get: function () {
  78427. return this._dPadDown;
  78428. },
  78429. /**
  78430. * Sets the value of D-pad down
  78431. */
  78432. set: function (value) {
  78433. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  78434. },
  78435. enumerable: true,
  78436. configurable: true
  78437. });
  78438. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  78439. /**
  78440. * Gets the value of D-pad left
  78441. */
  78442. get: function () {
  78443. return this._dPadLeft;
  78444. },
  78445. /**
  78446. * Sets the value of D-pad left
  78447. */
  78448. set: function (value) {
  78449. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  78450. },
  78451. enumerable: true,
  78452. configurable: true
  78453. });
  78454. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  78455. /**
  78456. * Gets the value of D-pad right
  78457. */
  78458. get: function () {
  78459. return this._dPadRight;
  78460. },
  78461. /**
  78462. * Sets the value of D-pad right
  78463. */
  78464. set: function (value) {
  78465. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  78466. },
  78467. enumerable: true,
  78468. configurable: true
  78469. });
  78470. /**
  78471. * Force the gamepad to synchronize with device values
  78472. */
  78473. Xbox360Pad.prototype.update = function () {
  78474. _super.prototype.update.call(this);
  78475. if (this._isXboxOnePad) {
  78476. this.buttonA = this.browserGamepad.buttons[0].value;
  78477. this.buttonB = this.browserGamepad.buttons[1].value;
  78478. this.buttonX = this.browserGamepad.buttons[2].value;
  78479. this.buttonY = this.browserGamepad.buttons[3].value;
  78480. this.buttonLB = this.browserGamepad.buttons[4].value;
  78481. this.buttonRB = this.browserGamepad.buttons[5].value;
  78482. this.leftTrigger = this.browserGamepad.axes[2];
  78483. this.rightTrigger = this.browserGamepad.axes[5];
  78484. this.buttonBack = this.browserGamepad.buttons[9].value;
  78485. this.buttonStart = this.browserGamepad.buttons[8].value;
  78486. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  78487. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  78488. this.dPadUp = this.browserGamepad.buttons[11].value;
  78489. this.dPadDown = this.browserGamepad.buttons[12].value;
  78490. this.dPadLeft = this.browserGamepad.buttons[13].value;
  78491. this.dPadRight = this.browserGamepad.buttons[14].value;
  78492. }
  78493. else {
  78494. this.buttonA = this.browserGamepad.buttons[0].value;
  78495. this.buttonB = this.browserGamepad.buttons[1].value;
  78496. this.buttonX = this.browserGamepad.buttons[2].value;
  78497. this.buttonY = this.browserGamepad.buttons[3].value;
  78498. this.buttonLB = this.browserGamepad.buttons[4].value;
  78499. this.buttonRB = this.browserGamepad.buttons[5].value;
  78500. this.leftTrigger = this.browserGamepad.buttons[6].value;
  78501. this.rightTrigger = this.browserGamepad.buttons[7].value;
  78502. this.buttonBack = this.browserGamepad.buttons[8].value;
  78503. this.buttonStart = this.browserGamepad.buttons[9].value;
  78504. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  78505. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  78506. this.dPadUp = this.browserGamepad.buttons[12].value;
  78507. this.dPadDown = this.browserGamepad.buttons[13].value;
  78508. this.dPadLeft = this.browserGamepad.buttons[14].value;
  78509. this.dPadRight = this.browserGamepad.buttons[15].value;
  78510. }
  78511. };
  78512. /**
  78513. * Disposes the gamepad
  78514. */
  78515. Xbox360Pad.prototype.dispose = function () {
  78516. _super.prototype.dispose.call(this);
  78517. this.onButtonDownObservable.clear();
  78518. this.onButtonUpObservable.clear();
  78519. this.onPadDownObservable.clear();
  78520. this.onPadUpObservable.clear();
  78521. };
  78522. return Xbox360Pad;
  78523. }(BABYLON.Gamepad));
  78524. BABYLON.Xbox360Pad = Xbox360Pad;
  78525. })(BABYLON || (BABYLON = {}));
  78526. //# sourceMappingURL=babylon.xboxGamepad.js.map
  78527. var BABYLON;
  78528. (function (BABYLON) {
  78529. /**
  78530. * Defines the types of pose enabled controllers that are supported
  78531. */
  78532. var PoseEnabledControllerType;
  78533. (function (PoseEnabledControllerType) {
  78534. /**
  78535. * HTC Vive
  78536. */
  78537. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  78538. /**
  78539. * Oculus Rift
  78540. */
  78541. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  78542. /**
  78543. * Windows mixed reality
  78544. */
  78545. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  78546. /**
  78547. * Samsung gear VR
  78548. */
  78549. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  78550. /**
  78551. * Google Daydream
  78552. */
  78553. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  78554. /**
  78555. * Generic
  78556. */
  78557. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  78558. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  78559. /**
  78560. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78561. */
  78562. var PoseEnabledControllerHelper = /** @class */ (function () {
  78563. function PoseEnabledControllerHelper() {
  78564. }
  78565. /**
  78566. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78567. * @param vrGamepad the gamepad to initialized
  78568. * @returns a vr controller of the type the gamepad identified as
  78569. */
  78570. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  78571. // Oculus Touch
  78572. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  78573. return new BABYLON.OculusTouchController(vrGamepad);
  78574. }
  78575. // Windows Mixed Reality controllers
  78576. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  78577. return new BABYLON.WindowsMotionController(vrGamepad);
  78578. }
  78579. // HTC Vive
  78580. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  78581. return new BABYLON.ViveController(vrGamepad);
  78582. }
  78583. // Samsung/Oculus Gear VR or Oculus Go
  78584. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  78585. return new BABYLON.GearVRController(vrGamepad);
  78586. }
  78587. // Google Daydream
  78588. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  78589. return new BABYLON.DaydreamController(vrGamepad);
  78590. }
  78591. // Generic
  78592. else {
  78593. return new BABYLON.GenericController(vrGamepad);
  78594. }
  78595. };
  78596. return PoseEnabledControllerHelper;
  78597. }());
  78598. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  78599. /**
  78600. * Defines the PoseEnabledController object that contains state of a vr capable controller
  78601. */
  78602. var PoseEnabledController = /** @class */ (function (_super) {
  78603. __extends(PoseEnabledController, _super);
  78604. /**
  78605. * Creates a new PoseEnabledController from a gamepad
  78606. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  78607. */
  78608. function PoseEnabledController(browserGamepad) {
  78609. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  78610. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78611. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78612. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  78613. /**
  78614. * The device position in babylon space
  78615. */
  78616. _this.devicePosition = BABYLON.Vector3.Zero();
  78617. /**
  78618. * The device rotation in babylon space
  78619. */
  78620. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  78621. /**
  78622. * The scale factor of the device in babylon space
  78623. */
  78624. _this.deviceScaleFactor = 1;
  78625. // Used to convert 6dof controllers to 3dof
  78626. _this._trackPosition = true;
  78627. _this._maxRotationDistFromHeadset = Math.PI / 5;
  78628. _this._draggedRoomRotation = 0;
  78629. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  78630. /**
  78631. * Internal, matrix used to convert room space to babylon space
  78632. * @hidden
  78633. */
  78634. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78635. /**
  78636. * Node to be used when casting a ray from the controller
  78637. * @hidden
  78638. */
  78639. _this._pointingPoseNode = null;
  78640. _this._workingMatrix = BABYLON.Matrix.Identity();
  78641. /**
  78642. * @hidden
  78643. */
  78644. _this._meshAttachedObservable = new BABYLON.Observable();
  78645. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  78646. _this.controllerType = PoseEnabledControllerType.GENERIC;
  78647. _this.position = BABYLON.Vector3.Zero();
  78648. _this.rotationQuaternion = new BABYLON.Quaternion();
  78649. _this._calculatedPosition = BABYLON.Vector3.Zero();
  78650. _this._calculatedRotation = new BABYLON.Quaternion();
  78651. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  78652. return _this;
  78653. }
  78654. /**
  78655. * @hidden
  78656. */
  78657. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  78658. if (this._trackPosition) {
  78659. this._calculatedPosition.copyFrom(fixedPosition);
  78660. this._trackPosition = false;
  78661. }
  78662. };
  78663. /**
  78664. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  78665. */
  78666. PoseEnabledController.prototype.update = function () {
  78667. _super.prototype.update.call(this);
  78668. this._updatePoseAndMesh();
  78669. };
  78670. /**
  78671. * Updates only the pose device and mesh without doing any button event checking
  78672. */
  78673. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  78674. var pose = this.browserGamepad.pose;
  78675. this.updateFromDevice(pose);
  78676. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  78677. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  78678. camera._computeDevicePosition();
  78679. this._deviceToWorld.setTranslation(camera.devicePosition);
  78680. if (camera.deviceRotationQuaternion) {
  78681. var camera = camera;
  78682. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  78683. // Find the radian distance away that the headset is from the controllers rotation
  78684. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  78685. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  78686. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  78687. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  78688. this._draggedRoomRotation += rotationAmount;
  78689. // Rotate controller around headset
  78690. var sin = Math.sin(-rotationAmount);
  78691. var cos = Math.cos(-rotationAmount);
  78692. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  78693. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  78694. }
  78695. }
  78696. }
  78697. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  78698. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  78699. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78700. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  78701. if (this._mesh) {
  78702. this._mesh.position.copyFrom(this.devicePosition);
  78703. if (this._mesh.rotationQuaternion) {
  78704. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  78705. }
  78706. }
  78707. };
  78708. /**
  78709. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  78710. * @param poseData raw pose fromthe device
  78711. */
  78712. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  78713. if (poseData) {
  78714. this.rawPose = poseData;
  78715. if (poseData.position) {
  78716. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  78717. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  78718. this._deviceRoomPosition.z *= -1;
  78719. }
  78720. if (this._trackPosition) {
  78721. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  78722. }
  78723. this._calculatedPosition.addInPlace(this.position);
  78724. }
  78725. var pose = this.rawPose;
  78726. if (poseData.orientation && pose.orientation) {
  78727. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  78728. if (this._mesh) {
  78729. if (this._mesh.getScene().useRightHandedSystem) {
  78730. this._deviceRoomRotationQuaternion.z *= -1;
  78731. this._deviceRoomRotationQuaternion.w *= -1;
  78732. }
  78733. else {
  78734. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  78735. }
  78736. }
  78737. // if the camera is set, rotate to the camera's rotation
  78738. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  78739. }
  78740. }
  78741. };
  78742. /**
  78743. * Attaches a mesh to the controller
  78744. * @param mesh the mesh to be attached
  78745. */
  78746. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  78747. if (this._mesh) {
  78748. this._mesh.parent = null;
  78749. }
  78750. this._mesh = mesh;
  78751. if (this._poseControlledCamera) {
  78752. this._mesh.parent = this._poseControlledCamera;
  78753. }
  78754. if (!this._mesh.rotationQuaternion) {
  78755. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  78756. }
  78757. // 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
  78758. this._updatePoseAndMesh();
  78759. if (this._pointingPoseNode) {
  78760. var parents = [];
  78761. var obj = this._pointingPoseNode;
  78762. while (obj.parent) {
  78763. parents.push(obj.parent);
  78764. obj = obj.parent;
  78765. }
  78766. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  78767. }
  78768. this._meshAttachedObservable.notifyObservers(mesh);
  78769. };
  78770. /**
  78771. * Attaches the controllers mesh to a camera
  78772. * @param camera the camera the mesh should be attached to
  78773. */
  78774. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  78775. this._poseControlledCamera = camera;
  78776. if (this._mesh) {
  78777. this._mesh.parent = this._poseControlledCamera;
  78778. }
  78779. };
  78780. /**
  78781. * Disposes of the controller
  78782. */
  78783. PoseEnabledController.prototype.dispose = function () {
  78784. if (this._mesh) {
  78785. this._mesh.dispose();
  78786. }
  78787. this._mesh = null;
  78788. _super.prototype.dispose.call(this);
  78789. };
  78790. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  78791. /**
  78792. * The mesh that is attached to the controller
  78793. */
  78794. get: function () {
  78795. return this._mesh;
  78796. },
  78797. enumerable: true,
  78798. configurable: true
  78799. });
  78800. /**
  78801. * Gets the ray of the controller in the direction the controller is pointing
  78802. * @param length the length the resulting ray should be
  78803. * @returns a ray in the direction the controller is pointing
  78804. */
  78805. PoseEnabledController.prototype.getForwardRay = function (length) {
  78806. if (length === void 0) { length = 100; }
  78807. if (!this.mesh) {
  78808. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  78809. }
  78810. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  78811. var origin = m.getTranslation();
  78812. var forward = new BABYLON.Vector3(0, 0, -1);
  78813. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  78814. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  78815. return new BABYLON.Ray(origin, direction, length);
  78816. };
  78817. /**
  78818. * Name of the child mesh that can be used to cast a ray from the controller
  78819. */
  78820. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  78821. return PoseEnabledController;
  78822. }(BABYLON.Gamepad));
  78823. BABYLON.PoseEnabledController = PoseEnabledController;
  78824. })(BABYLON || (BABYLON = {}));
  78825. //# sourceMappingURL=babylon.poseEnabledController.js.map
  78826. var BABYLON;
  78827. (function (BABYLON) {
  78828. /**
  78829. * Defines the WebVRController object that represents controllers tracked in 3D space
  78830. */
  78831. var WebVRController = /** @class */ (function (_super) {
  78832. __extends(WebVRController, _super);
  78833. /**
  78834. * Creates a new WebVRController from a gamepad
  78835. * @param vrGamepad the gamepad that the WebVRController should be created from
  78836. */
  78837. function WebVRController(vrGamepad) {
  78838. var _this = _super.call(this, vrGamepad) || this;
  78839. // Observables
  78840. /**
  78841. * Fired when the trigger state has changed
  78842. */
  78843. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  78844. /**
  78845. * Fired when the main button state has changed
  78846. */
  78847. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  78848. /**
  78849. * Fired when the secondary button state has changed
  78850. */
  78851. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  78852. /**
  78853. * Fired when the pad state has changed
  78854. */
  78855. _this.onPadStateChangedObservable = new BABYLON.Observable();
  78856. /**
  78857. * Fired when controllers stick values have changed
  78858. */
  78859. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  78860. /**
  78861. * X and Y axis corrisponding to the controllers joystick
  78862. */
  78863. _this.pad = { x: 0, y: 0 };
  78864. // avoid GC, store state in a tmp object
  78865. _this._changes = {
  78866. pressChanged: false,
  78867. touchChanged: false,
  78868. valueChanged: false,
  78869. changed: false
  78870. };
  78871. _this._buttons = new Array(vrGamepad.buttons.length);
  78872. _this.hand = vrGamepad.hand;
  78873. return _this;
  78874. }
  78875. /**
  78876. * Fired when a controller button's state has changed
  78877. * @param callback the callback containing the button that was modified
  78878. */
  78879. WebVRController.prototype.onButtonStateChange = function (callback) {
  78880. this._onButtonStateChange = callback;
  78881. };
  78882. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  78883. /**
  78884. * The default controller model for the controller
  78885. */
  78886. get: function () {
  78887. return this._defaultModel;
  78888. },
  78889. enumerable: true,
  78890. configurable: true
  78891. });
  78892. /**
  78893. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  78894. */
  78895. WebVRController.prototype.update = function () {
  78896. _super.prototype.update.call(this);
  78897. for (var index = 0; index < this._buttons.length; index++) {
  78898. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  78899. }
  78900. ;
  78901. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  78902. this.pad.x = this.leftStick.x;
  78903. this.pad.y = this.leftStick.y;
  78904. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  78905. }
  78906. };
  78907. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  78908. if (!newState) {
  78909. newState = {
  78910. pressed: false,
  78911. touched: false,
  78912. value: 0
  78913. };
  78914. }
  78915. if (!currentState) {
  78916. this._buttons[buttonIndex] = {
  78917. pressed: newState.pressed,
  78918. touched: newState.touched,
  78919. value: newState.value
  78920. };
  78921. return;
  78922. }
  78923. this._checkChanges(newState, currentState);
  78924. if (this._changes.changed) {
  78925. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  78926. this._handleButtonChange(buttonIndex, newState, this._changes);
  78927. }
  78928. this._buttons[buttonIndex].pressed = newState.pressed;
  78929. this._buttons[buttonIndex].touched = newState.touched;
  78930. // oculus triggers are never 0, thou not touched.
  78931. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  78932. };
  78933. WebVRController.prototype._checkChanges = function (newState, currentState) {
  78934. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  78935. this._changes.touchChanged = newState.touched !== currentState.touched;
  78936. this._changes.valueChanged = newState.value !== currentState.value;
  78937. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  78938. return this._changes;
  78939. };
  78940. /**
  78941. * Disposes of th webVRCOntroller
  78942. */
  78943. WebVRController.prototype.dispose = function () {
  78944. _super.prototype.dispose.call(this);
  78945. this.onTriggerStateChangedObservable.clear();
  78946. this.onMainButtonStateChangedObservable.clear();
  78947. this.onSecondaryButtonStateChangedObservable.clear();
  78948. this.onPadStateChangedObservable.clear();
  78949. this.onPadValuesChangedObservable.clear();
  78950. };
  78951. return WebVRController;
  78952. }(BABYLON.PoseEnabledController));
  78953. BABYLON.WebVRController = WebVRController;
  78954. })(BABYLON || (BABYLON = {}));
  78955. //# sourceMappingURL=babylon.webVRController.js.map
  78956. var BABYLON;
  78957. (function (BABYLON) {
  78958. /**
  78959. * Oculus Touch Controller
  78960. */
  78961. var OculusTouchController = /** @class */ (function (_super) {
  78962. __extends(OculusTouchController, _super);
  78963. /**
  78964. * Creates a new OculusTouchController from a gamepad
  78965. * @param vrGamepad the gamepad that the controller should be created from
  78966. */
  78967. function OculusTouchController(vrGamepad) {
  78968. var _this = _super.call(this, vrGamepad) || this;
  78969. /**
  78970. * Fired when the secondary trigger on this controller is modified
  78971. */
  78972. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  78973. /**
  78974. * Fired when the thumb rest on this controller is modified
  78975. */
  78976. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  78977. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  78978. return _this;
  78979. }
  78980. /**
  78981. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78982. * @param scene scene in which to add meshes
  78983. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78984. */
  78985. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78986. var _this = this;
  78987. var meshName;
  78988. // Hand
  78989. if (this.hand === 'left') {
  78990. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  78991. }
  78992. else { // Right is the default if no hand is specified
  78993. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  78994. }
  78995. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  78996. /*
  78997. Parent Mesh name: oculus_touch_left
  78998. - body
  78999. - trigger
  79000. - thumbstick
  79001. - grip
  79002. - button_y
  79003. - button_x
  79004. - button_enter
  79005. */
  79006. _this._defaultModel = newMeshes[1];
  79007. _this.attachToMesh(_this._defaultModel);
  79008. if (meshLoaded) {
  79009. meshLoaded(_this._defaultModel);
  79010. }
  79011. });
  79012. };
  79013. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  79014. /**
  79015. * Fired when the A button on this controller is modified
  79016. */
  79017. get: function () {
  79018. if (this.hand === 'right') {
  79019. return this.onMainButtonStateChangedObservable;
  79020. }
  79021. else {
  79022. throw new Error('No A button on left hand');
  79023. }
  79024. },
  79025. enumerable: true,
  79026. configurable: true
  79027. });
  79028. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  79029. /**
  79030. * Fired when the B button on this controller is modified
  79031. */
  79032. get: function () {
  79033. if (this.hand === 'right') {
  79034. return this.onSecondaryButtonStateChangedObservable;
  79035. }
  79036. else {
  79037. throw new Error('No B button on left hand');
  79038. }
  79039. },
  79040. enumerable: true,
  79041. configurable: true
  79042. });
  79043. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  79044. /**
  79045. * Fired when the X button on this controller is modified
  79046. */
  79047. get: function () {
  79048. if (this.hand === 'left') {
  79049. return this.onMainButtonStateChangedObservable;
  79050. }
  79051. else {
  79052. throw new Error('No X button on right hand');
  79053. }
  79054. },
  79055. enumerable: true,
  79056. configurable: true
  79057. });
  79058. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  79059. /**
  79060. * Fired when the Y button on this controller is modified
  79061. */
  79062. get: function () {
  79063. if (this.hand === 'left') {
  79064. return this.onSecondaryButtonStateChangedObservable;
  79065. }
  79066. else {
  79067. throw new Error('No Y button on right hand');
  79068. }
  79069. },
  79070. enumerable: true,
  79071. configurable: true
  79072. });
  79073. /**
  79074. * Called once for each button that changed state since the last frame
  79075. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  79076. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  79077. * 2) secondary trigger (same)
  79078. * 3) A (right) X (left), touch, pressed = value
  79079. * 4) B / Y
  79080. * 5) thumb rest
  79081. * @param buttonIdx Which button index changed
  79082. * @param state New state of the button
  79083. * @param changes Which properties on the state changed since last frame
  79084. */
  79085. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79086. var notifyObject = state; //{ state: state, changes: changes };
  79087. var triggerDirection = this.hand === 'right' ? -1 : 1;
  79088. switch (buttonIdx) {
  79089. case 0:
  79090. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  79091. return;
  79092. case 1: // index trigger
  79093. if (this._defaultModel) {
  79094. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  79095. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  79096. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  79097. }
  79098. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  79099. return;
  79100. case 2: // secondary trigger
  79101. if (this._defaultModel) {
  79102. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  79103. }
  79104. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  79105. return;
  79106. case 3:
  79107. if (this._defaultModel) {
  79108. if (notifyObject.pressed) {
  79109. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  79110. }
  79111. else {
  79112. (this._defaultModel.getChildren()[1]).position.y = 0;
  79113. }
  79114. }
  79115. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  79116. return;
  79117. case 4:
  79118. if (this._defaultModel) {
  79119. if (notifyObject.pressed) {
  79120. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  79121. }
  79122. else {
  79123. (this._defaultModel.getChildren()[2]).position.y = 0;
  79124. }
  79125. }
  79126. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  79127. return;
  79128. case 5:
  79129. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  79130. return;
  79131. }
  79132. };
  79133. /**
  79134. * Base Url for the controller model.
  79135. */
  79136. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  79137. /**
  79138. * File name for the left controller model.
  79139. */
  79140. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  79141. /**
  79142. * File name for the right controller model.
  79143. */
  79144. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  79145. return OculusTouchController;
  79146. }(BABYLON.WebVRController));
  79147. BABYLON.OculusTouchController = OculusTouchController;
  79148. })(BABYLON || (BABYLON = {}));
  79149. //# sourceMappingURL=babylon.oculusTouchController.js.map
  79150. var BABYLON;
  79151. (function (BABYLON) {
  79152. /**
  79153. * Vive Controller
  79154. */
  79155. var ViveController = /** @class */ (function (_super) {
  79156. __extends(ViveController, _super);
  79157. /**
  79158. * Creates a new ViveController from a gamepad
  79159. * @param vrGamepad the gamepad that the controller should be created from
  79160. */
  79161. function ViveController(vrGamepad) {
  79162. var _this = _super.call(this, vrGamepad) || this;
  79163. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  79164. _this._invertLeftStickY = true;
  79165. return _this;
  79166. }
  79167. /**
  79168. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79169. * @param scene scene in which to add meshes
  79170. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79171. */
  79172. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79173. var _this = this;
  79174. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  79175. /*
  79176. Parent Mesh name: ViveWand
  79177. - body
  79178. - r_gripper
  79179. - l_gripper
  79180. - menu_button
  79181. - system_button
  79182. - trackpad
  79183. - trigger
  79184. - LED
  79185. */
  79186. _this._defaultModel = newMeshes[1];
  79187. _this.attachToMesh(_this._defaultModel);
  79188. if (meshLoaded) {
  79189. meshLoaded(_this._defaultModel);
  79190. }
  79191. });
  79192. };
  79193. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  79194. /**
  79195. * Fired when the left button on this controller is modified
  79196. */
  79197. get: function () {
  79198. return this.onMainButtonStateChangedObservable;
  79199. },
  79200. enumerable: true,
  79201. configurable: true
  79202. });
  79203. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  79204. /**
  79205. * Fired when the right button on this controller is modified
  79206. */
  79207. get: function () {
  79208. return this.onMainButtonStateChangedObservable;
  79209. },
  79210. enumerable: true,
  79211. configurable: true
  79212. });
  79213. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  79214. /**
  79215. * Fired when the menu button on this controller is modified
  79216. */
  79217. get: function () {
  79218. return this.onSecondaryButtonStateChangedObservable;
  79219. },
  79220. enumerable: true,
  79221. configurable: true
  79222. });
  79223. /**
  79224. * Called once for each button that changed state since the last frame
  79225. * Vive mapping:
  79226. * 0: touchpad
  79227. * 1: trigger
  79228. * 2: left AND right buttons
  79229. * 3: menu button
  79230. * @param buttonIdx Which button index changed
  79231. * @param state New state of the button
  79232. * @param changes Which properties on the state changed since last frame
  79233. */
  79234. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79235. var notifyObject = state; //{ state: state, changes: changes };
  79236. switch (buttonIdx) {
  79237. case 0:
  79238. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  79239. return;
  79240. case 1: // index trigger
  79241. if (this._defaultModel) {
  79242. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  79243. }
  79244. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  79245. return;
  79246. case 2: // left AND right button
  79247. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  79248. return;
  79249. case 3:
  79250. if (this._defaultModel) {
  79251. if (notifyObject.pressed) {
  79252. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  79253. }
  79254. else {
  79255. (this._defaultModel.getChildren()[2]).position.y = 0;
  79256. }
  79257. }
  79258. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  79259. return;
  79260. }
  79261. };
  79262. /**
  79263. * Base Url for the controller model.
  79264. */
  79265. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  79266. /**
  79267. * File name for the controller model.
  79268. */
  79269. ViveController.MODEL_FILENAME = 'wand.babylon';
  79270. return ViveController;
  79271. }(BABYLON.WebVRController));
  79272. BABYLON.ViveController = ViveController;
  79273. })(BABYLON || (BABYLON = {}));
  79274. //# sourceMappingURL=babylon.viveController.js.map
  79275. var BABYLON;
  79276. (function (BABYLON) {
  79277. /**
  79278. * Generic Controller
  79279. */
  79280. var GenericController = /** @class */ (function (_super) {
  79281. __extends(GenericController, _super);
  79282. /**
  79283. * Creates a new GenericController from a gamepad
  79284. * @param vrGamepad the gamepad that the controller should be created from
  79285. */
  79286. function GenericController(vrGamepad) {
  79287. return _super.call(this, vrGamepad) || this;
  79288. }
  79289. /**
  79290. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79291. * @param scene scene in which to add meshes
  79292. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79293. */
  79294. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79295. var _this = this;
  79296. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  79297. _this._defaultModel = newMeshes[1];
  79298. _this.attachToMesh(_this._defaultModel);
  79299. if (meshLoaded) {
  79300. meshLoaded(_this._defaultModel);
  79301. }
  79302. });
  79303. };
  79304. /**
  79305. * Called once for each button that changed state since the last frame
  79306. * @param buttonIdx Which button index changed
  79307. * @param state New state of the button
  79308. * @param changes Which properties on the state changed since last frame
  79309. */
  79310. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79311. console.log("Button id: " + buttonIdx + "state: ");
  79312. console.dir(state);
  79313. };
  79314. /**
  79315. * Base Url for the controller model.
  79316. */
  79317. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79318. /**
  79319. * File name for the controller model.
  79320. */
  79321. GenericController.MODEL_FILENAME = 'generic.babylon';
  79322. return GenericController;
  79323. }(BABYLON.WebVRController));
  79324. BABYLON.GenericController = GenericController;
  79325. })(BABYLON || (BABYLON = {}));
  79326. //# sourceMappingURL=babylon.genericController.js.map
  79327. var BABYLON;
  79328. (function (BABYLON) {
  79329. /**
  79330. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  79331. */
  79332. var LoadedMeshInfo = /** @class */ (function () {
  79333. function LoadedMeshInfo() {
  79334. /**
  79335. * Map of the button meshes contained in the controller
  79336. */
  79337. this.buttonMeshes = {};
  79338. /**
  79339. * Map of the axis meshes contained in the controller
  79340. */
  79341. this.axisMeshes = {};
  79342. }
  79343. return LoadedMeshInfo;
  79344. }());
  79345. /**
  79346. * Defines the WindowsMotionController object that the state of the windows motion controller
  79347. */
  79348. var WindowsMotionController = /** @class */ (function (_super) {
  79349. __extends(WindowsMotionController, _super);
  79350. /**
  79351. * Creates a new WindowsMotionController from a gamepad
  79352. * @param vrGamepad the gamepad that the controller should be created from
  79353. */
  79354. function WindowsMotionController(vrGamepad) {
  79355. var _this = _super.call(this, vrGamepad) || this;
  79356. _this._mapping = {
  79357. // Semantic button names
  79358. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  79359. // A mapping of the button name to glTF model node name
  79360. // that should be transformed by button value.
  79361. buttonMeshNames: {
  79362. 'trigger': 'SELECT',
  79363. 'menu': 'MENU',
  79364. 'grip': 'GRASP',
  79365. 'thumbstick': 'THUMBSTICK_PRESS',
  79366. 'trackpad': 'TOUCHPAD_PRESS'
  79367. },
  79368. // This mapping is used to translate from the Motion Controller to Babylon semantics
  79369. buttonObservableNames: {
  79370. 'trigger': 'onTriggerStateChangedObservable',
  79371. 'menu': 'onSecondaryButtonStateChangedObservable',
  79372. 'grip': 'onMainButtonStateChangedObservable',
  79373. 'thumbstick': 'onPadStateChangedObservable',
  79374. 'trackpad': 'onTrackpadChangedObservable'
  79375. },
  79376. // A mapping of the axis name to glTF model node name
  79377. // that should be transformed by axis value.
  79378. // This array mirrors the browserGamepad.axes array, such that
  79379. // the mesh corresponding to axis 0 is in this array index 0.
  79380. axisMeshNames: [
  79381. 'THUMBSTICK_X',
  79382. 'THUMBSTICK_Y',
  79383. 'TOUCHPAD_TOUCH_X',
  79384. 'TOUCHPAD_TOUCH_Y'
  79385. ],
  79386. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  79387. };
  79388. /**
  79389. * Fired when the trackpad on this controller is clicked
  79390. */
  79391. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  79392. /**
  79393. * Fired when the trackpad on this controller is modified
  79394. */
  79395. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  79396. /**
  79397. * The current x and y values of this controller's trackpad
  79398. */
  79399. _this.trackpad = { x: 0, y: 0 };
  79400. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  79401. _this._loadedMeshInfo = null;
  79402. return _this;
  79403. }
  79404. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  79405. /**
  79406. * Fired when the trigger on this controller is modified
  79407. */
  79408. get: function () {
  79409. return this.onTriggerStateChangedObservable;
  79410. },
  79411. enumerable: true,
  79412. configurable: true
  79413. });
  79414. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  79415. /**
  79416. * Fired when the menu button on this controller is modified
  79417. */
  79418. get: function () {
  79419. return this.onSecondaryButtonStateChangedObservable;
  79420. },
  79421. enumerable: true,
  79422. configurable: true
  79423. });
  79424. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  79425. /**
  79426. * Fired when the grip button on this controller is modified
  79427. */
  79428. get: function () {
  79429. return this.onMainButtonStateChangedObservable;
  79430. },
  79431. enumerable: true,
  79432. configurable: true
  79433. });
  79434. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  79435. /**
  79436. * Fired when the thumbstick button on this controller is modified
  79437. */
  79438. get: function () {
  79439. return this.onPadStateChangedObservable;
  79440. },
  79441. enumerable: true,
  79442. configurable: true
  79443. });
  79444. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  79445. /**
  79446. * Fired when the touchpad button on this controller is modified
  79447. */
  79448. get: function () {
  79449. return this.onTrackpadChangedObservable;
  79450. },
  79451. enumerable: true,
  79452. configurable: true
  79453. });
  79454. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  79455. /**
  79456. * Fired when the touchpad values on this controller are modified
  79457. */
  79458. get: function () {
  79459. return this.onTrackpadValuesChangedObservable;
  79460. },
  79461. enumerable: true,
  79462. configurable: true
  79463. });
  79464. WindowsMotionController.prototype._updateTrackpad = function () {
  79465. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  79466. this.trackpad.x = this.browserGamepad["axes"][2];
  79467. this.trackpad.y = this.browserGamepad["axes"][3];
  79468. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  79469. }
  79470. };
  79471. /**
  79472. * Called once per frame by the engine.
  79473. */
  79474. WindowsMotionController.prototype.update = function () {
  79475. _super.prototype.update.call(this);
  79476. if (this.browserGamepad.axes) {
  79477. this._updateTrackpad();
  79478. // Only need to animate axes if there is a loaded mesh
  79479. if (this._loadedMeshInfo) {
  79480. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  79481. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  79482. }
  79483. }
  79484. }
  79485. };
  79486. /**
  79487. * Called once for each button that changed state since the last frame
  79488. * @param buttonIdx Which button index changed
  79489. * @param state New state of the button
  79490. * @param changes Which properties on the state changed since last frame
  79491. */
  79492. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79493. var buttonName = this._mapping.buttons[buttonIdx];
  79494. if (!buttonName) {
  79495. return;
  79496. }
  79497. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  79498. this._updateTrackpad();
  79499. // Only emit events for buttons that we know how to map from index to name
  79500. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  79501. if (observable) {
  79502. observable.notifyObservers(state);
  79503. }
  79504. this._lerpButtonTransform(buttonName, state.value);
  79505. };
  79506. /**
  79507. * Moves the buttons on the controller mesh based on their current state
  79508. * @param buttonName the name of the button to move
  79509. * @param buttonValue the value of the button which determines the buttons new position
  79510. */
  79511. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  79512. // If there is no loaded mesh, there is nothing to transform.
  79513. if (!this._loadedMeshInfo) {
  79514. return;
  79515. }
  79516. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  79517. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79518. return;
  79519. }
  79520. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  79521. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  79522. };
  79523. /**
  79524. * Moves the axis on the controller mesh based on its current state
  79525. * @param axis the index of the axis
  79526. * @param axisValue the value of the axis which determines the meshes new position
  79527. * @hidden
  79528. */
  79529. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  79530. if (!this._loadedMeshInfo) {
  79531. return;
  79532. }
  79533. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  79534. if (!meshInfo) {
  79535. return;
  79536. }
  79537. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79538. return;
  79539. }
  79540. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  79541. var lerpValue = axisValue * 0.5 + 0.5;
  79542. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  79543. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  79544. };
  79545. /**
  79546. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79547. * @param scene scene in which to add meshes
  79548. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79549. */
  79550. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  79551. var _this = this;
  79552. if (forceDefault === void 0) { forceDefault = false; }
  79553. var path;
  79554. var filename;
  79555. // Checking if GLB loader is present
  79556. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  79557. // Determine the device specific folder based on the ID suffix
  79558. var device = 'default';
  79559. if (this.id && !forceDefault) {
  79560. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  79561. device = ((match && match[0]) || device);
  79562. }
  79563. // Hand
  79564. if (this.hand === 'left') {
  79565. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  79566. }
  79567. else { // Right is the default if no hand is specified
  79568. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  79569. }
  79570. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  79571. }
  79572. else {
  79573. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  79574. path = BABYLON.GenericController.MODEL_BASE_URL;
  79575. filename = BABYLON.GenericController.MODEL_FILENAME;
  79576. }
  79577. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  79578. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  79579. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  79580. if (!_this._loadedMeshInfo) {
  79581. return;
  79582. }
  79583. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  79584. _this.attachToMesh(_this._defaultModel);
  79585. if (meshLoaded) {
  79586. meshLoaded(_this._defaultModel);
  79587. }
  79588. }, null, function (scene, message) {
  79589. BABYLON.Tools.Log(message);
  79590. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  79591. if (!forceDefault) {
  79592. _this.initControllerMesh(scene, meshLoaded, true);
  79593. }
  79594. });
  79595. };
  79596. /**
  79597. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  79598. * can be transformed by button presses and axes values, based on this._mapping.
  79599. *
  79600. * @param scene scene in which the meshes exist
  79601. * @param meshes list of meshes that make up the controller model to process
  79602. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  79603. */
  79604. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  79605. var loadedMeshInfo = null;
  79606. // Create a new mesh to contain the glTF hierarchy
  79607. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  79608. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  79609. var childMesh = null;
  79610. for (var i = 0; i < meshes.length; i++) {
  79611. var mesh = meshes[i];
  79612. if (!mesh.parent) {
  79613. // Exclude controller meshes from picking results
  79614. mesh.isPickable = false;
  79615. // Handle root node, attach to the new parentMesh
  79616. childMesh = mesh;
  79617. break;
  79618. }
  79619. }
  79620. if (childMesh) {
  79621. childMesh.setParent(parentMesh);
  79622. // Create our mesh info. Note that this method will always return non-null.
  79623. loadedMeshInfo = this.createMeshInfo(parentMesh);
  79624. }
  79625. else {
  79626. BABYLON.Tools.Warn('Could not find root node in model file.');
  79627. }
  79628. return loadedMeshInfo;
  79629. };
  79630. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  79631. var loadedMeshInfo = new LoadedMeshInfo();
  79632. var i;
  79633. loadedMeshInfo.rootNode = rootNode;
  79634. // Reset the caches
  79635. loadedMeshInfo.buttonMeshes = {};
  79636. loadedMeshInfo.axisMeshes = {};
  79637. // Button Meshes
  79638. for (i = 0; i < this._mapping.buttons.length; i++) {
  79639. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  79640. if (!buttonMeshName) {
  79641. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  79642. continue;
  79643. }
  79644. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  79645. if (!buttonMesh) {
  79646. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  79647. continue;
  79648. }
  79649. var buttonMeshInfo = {
  79650. index: i,
  79651. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  79652. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  79653. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  79654. };
  79655. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  79656. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  79657. }
  79658. else {
  79659. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  79660. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  79661. '(VALUE: ' + !!buttonMeshInfo.value +
  79662. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  79663. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  79664. ')');
  79665. }
  79666. }
  79667. // Axis Meshes
  79668. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  79669. var axisMeshName = this._mapping.axisMeshNames[i];
  79670. if (!axisMeshName) {
  79671. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  79672. continue;
  79673. }
  79674. var axisMesh = getChildByName(rootNode, axisMeshName);
  79675. if (!axisMesh) {
  79676. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  79677. continue;
  79678. }
  79679. var axisMeshInfo = {
  79680. index: i,
  79681. value: getImmediateChildByName(axisMesh, 'VALUE'),
  79682. min: getImmediateChildByName(axisMesh, 'MIN'),
  79683. max: getImmediateChildByName(axisMesh, 'MAX')
  79684. };
  79685. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  79686. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  79687. }
  79688. else {
  79689. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  79690. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  79691. '(VALUE: ' + !!axisMeshInfo.value +
  79692. ', MIN: ' + !!axisMeshInfo.min +
  79693. ', MAX:' + !!axisMeshInfo.max +
  79694. ')');
  79695. }
  79696. }
  79697. // Pointing Ray
  79698. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  79699. if (!loadedMeshInfo.pointingPoseNode) {
  79700. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  79701. }
  79702. else {
  79703. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  79704. }
  79705. return loadedMeshInfo;
  79706. // Look through all children recursively. This will return null if no mesh exists with the given name.
  79707. function getChildByName(node, name) {
  79708. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  79709. }
  79710. // Look through only immediate children. This will return null if no mesh exists with the given name.
  79711. function getImmediateChildByName(node, name) {
  79712. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  79713. }
  79714. };
  79715. /**
  79716. * Gets the ray of the controller in the direction the controller is pointing
  79717. * @param length the length the resulting ray should be
  79718. * @returns a ray in the direction the controller is pointing
  79719. */
  79720. WindowsMotionController.prototype.getForwardRay = function (length) {
  79721. if (length === void 0) { length = 100; }
  79722. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  79723. return _super.prototype.getForwardRay.call(this, length);
  79724. }
  79725. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  79726. var origin = m.getTranslation();
  79727. var forward = new BABYLON.Vector3(0, 0, -1);
  79728. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  79729. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  79730. return new BABYLON.Ray(origin, direction, length);
  79731. };
  79732. /**
  79733. * Disposes of the controller
  79734. */
  79735. WindowsMotionController.prototype.dispose = function () {
  79736. _super.prototype.dispose.call(this);
  79737. this.onTrackpadChangedObservable.clear();
  79738. };
  79739. /**
  79740. * The base url used to load the left and right controller models
  79741. */
  79742. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  79743. /**
  79744. * The name of the left controller model file
  79745. */
  79746. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  79747. /**
  79748. * The name of the right controller model file
  79749. */
  79750. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  79751. /**
  79752. * The controller name prefix for this controller type
  79753. */
  79754. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  79755. /**
  79756. * The controller id pattern for this controller type
  79757. */
  79758. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  79759. return WindowsMotionController;
  79760. }(BABYLON.WebVRController));
  79761. BABYLON.WindowsMotionController = WindowsMotionController;
  79762. })(BABYLON || (BABYLON = {}));
  79763. //# sourceMappingURL=babylon.windowsMotionController.js.map
  79764. var BABYLON;
  79765. (function (BABYLON) {
  79766. /**
  79767. * Gear VR Controller
  79768. */
  79769. var GearVRController = /** @class */ (function (_super) {
  79770. __extends(GearVRController, _super);
  79771. /**
  79772. * Creates a new GearVRController from a gamepad
  79773. * @param vrGamepad the gamepad that the controller should be created from
  79774. */
  79775. function GearVRController(vrGamepad) {
  79776. var _this = _super.call(this, vrGamepad) || this;
  79777. _this._buttonIndexToObservableNameMap = [
  79778. 'onTrackpadChangedObservable',
  79779. 'onTriggerStateChangedObservable' // Trigger
  79780. ];
  79781. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  79782. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  79783. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  79784. _this._disableTrackPosition(_this._calculatedPosition);
  79785. return _this;
  79786. }
  79787. /**
  79788. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79789. * @param scene scene in which to add meshes
  79790. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79791. */
  79792. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79793. var _this = this;
  79794. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  79795. // Offset the controller so it will rotate around the users wrist
  79796. var mesh = new BABYLON.Mesh("", scene);
  79797. newMeshes[1].parent = mesh;
  79798. newMeshes[1].position.z = -0.15;
  79799. _this._defaultModel = mesh;
  79800. _this.attachToMesh(_this._defaultModel);
  79801. if (meshLoaded) {
  79802. meshLoaded(_this._defaultModel);
  79803. }
  79804. });
  79805. };
  79806. /**
  79807. * Called once for each button that changed state since the last frame
  79808. * @param buttonIdx Which button index changed
  79809. * @param state New state of the button
  79810. * @param changes Which properties on the state changed since last frame
  79811. */
  79812. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79813. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  79814. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  79815. // Only emit events for buttons that we know how to map from index to observable
  79816. var observable = this[observableName];
  79817. if (observable) {
  79818. observable.notifyObservers(state);
  79819. }
  79820. }
  79821. };
  79822. /**
  79823. * Base Url for the controller model.
  79824. */
  79825. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79826. /**
  79827. * File name for the controller model.
  79828. */
  79829. GearVRController.MODEL_FILENAME = 'generic.babylon';
  79830. /**
  79831. * Gamepad Id prefix used to identify this controller.
  79832. */
  79833. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  79834. return GearVRController;
  79835. }(BABYLON.WebVRController));
  79836. BABYLON.GearVRController = GearVRController;
  79837. })(BABYLON || (BABYLON = {}));
  79838. //# sourceMappingURL=babylon.gearVRController.js.map
  79839. var BABYLON;
  79840. (function (BABYLON) {
  79841. /**
  79842. * Google Daydream controller
  79843. */
  79844. var DaydreamController = /** @class */ (function (_super) {
  79845. __extends(DaydreamController, _super);
  79846. /**
  79847. * Creates a new DaydreamController from a gamepad
  79848. * @param vrGamepad the gamepad that the controller should be created from
  79849. */
  79850. function DaydreamController(vrGamepad) {
  79851. var _this = _super.call(this, vrGamepad) || this;
  79852. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  79853. return _this;
  79854. }
  79855. /**
  79856. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79857. * @param scene scene in which to add meshes
  79858. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79859. */
  79860. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79861. var _this = this;
  79862. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  79863. _this._defaultModel = newMeshes[1];
  79864. _this.attachToMesh(_this._defaultModel);
  79865. if (meshLoaded) {
  79866. meshLoaded(_this._defaultModel);
  79867. }
  79868. });
  79869. };
  79870. /**
  79871. * Called once for each button that changed state since the last frame
  79872. * @param buttonIdx Which button index changed
  79873. * @param state New state of the button
  79874. * @param changes Which properties on the state changed since last frame
  79875. */
  79876. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79877. // Daydream controller only has 1 GamepadButton (on the trackpad).
  79878. if (buttonIdx === 0) {
  79879. var observable = this.onTriggerStateChangedObservable;
  79880. if (observable) {
  79881. observable.notifyObservers(state);
  79882. }
  79883. }
  79884. else {
  79885. // If the app or home buttons are ever made available
  79886. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  79887. }
  79888. };
  79889. /**
  79890. * Base Url for the controller model.
  79891. */
  79892. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79893. /**
  79894. * File name for the controller model.
  79895. */
  79896. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  79897. /**
  79898. * Gamepad Id prefix used to identify Daydream Controller.
  79899. */
  79900. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  79901. return DaydreamController;
  79902. }(BABYLON.WebVRController));
  79903. BABYLON.DaydreamController = DaydreamController;
  79904. })(BABYLON || (BABYLON = {}));
  79905. //# sourceMappingURL=babylon.daydreamController.js.map
  79906. var BABYLON;
  79907. (function (BABYLON) {
  79908. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  79909. get: function () {
  79910. if (!this._gamepadManager) {
  79911. this._gamepadManager = new BABYLON.GamepadManager(this);
  79912. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  79913. if (!component) {
  79914. component = new GamepadSystemSceneComponent(this);
  79915. this._addComponent(component);
  79916. }
  79917. }
  79918. return this._gamepadManager;
  79919. },
  79920. enumerable: true,
  79921. configurable: true
  79922. });
  79923. /**
  79924. * Adds a gamepad to the free camera inputs manager
  79925. */
  79926. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  79927. this.add(new BABYLON.FreeCameraGamepadInput());
  79928. return this;
  79929. };
  79930. /**
  79931. * Adds a gamepad to the arc rotate camera inputs manager
  79932. */
  79933. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  79934. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  79935. return this;
  79936. };
  79937. /**
  79938. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  79939. */
  79940. var GamepadSystemSceneComponent = /** @class */ (function () {
  79941. /**
  79942. * Creates a new instance of the component for the given scene
  79943. * @param scene Defines the scene to register the component in
  79944. */
  79945. function GamepadSystemSceneComponent(scene) {
  79946. /**
  79947. * The component name helpfull to identify the component in the list of scene components.
  79948. */
  79949. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  79950. this.scene = scene;
  79951. }
  79952. /**
  79953. * Registers the component in a given scene
  79954. */
  79955. GamepadSystemSceneComponent.prototype.register = function () {
  79956. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  79957. };
  79958. /**
  79959. * Rebuilds the elements related to this component in case of
  79960. * context lost for instance.
  79961. */
  79962. GamepadSystemSceneComponent.prototype.rebuild = function () {
  79963. // Nothing to do for gamepads
  79964. };
  79965. /**
  79966. * Disposes the component and the associated ressources
  79967. */
  79968. GamepadSystemSceneComponent.prototype.dispose = function () {
  79969. var gamepadManager = this.scene._gamepadManager;
  79970. if (gamepadManager) {
  79971. gamepadManager.dispose();
  79972. this.scene._gamepadManager = null;
  79973. }
  79974. };
  79975. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  79976. var gamepadManager = this.scene._gamepadManager;
  79977. if (gamepadManager && gamepadManager._isMonitoring) {
  79978. gamepadManager._checkGamepadsStatus();
  79979. }
  79980. };
  79981. return GamepadSystemSceneComponent;
  79982. }());
  79983. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  79984. })(BABYLON || (BABYLON = {}));
  79985. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  79986. var BABYLON;
  79987. (function (BABYLON) {
  79988. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  79989. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  79990. });
  79991. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  79992. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  79993. });
  79994. /**
  79995. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  79996. * an arc rotate version arcFollowCamera are available.
  79997. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79998. */
  79999. var FollowCamera = /** @class */ (function (_super) {
  80000. __extends(FollowCamera, _super);
  80001. /**
  80002. * Instantiates the follow camera.
  80003. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80004. * @param name Define the name of the camera in the scene
  80005. * @param position Define the position of the camera
  80006. * @param scene Define the scene the camera belong to
  80007. * @param lockedTarget Define the target of the camera
  80008. */
  80009. function FollowCamera(name, position, scene, lockedTarget) {
  80010. if (lockedTarget === void 0) { lockedTarget = null; }
  80011. var _this = _super.call(this, name, position, scene) || this;
  80012. /**
  80013. * Distance the follow camera should follow an object at
  80014. */
  80015. _this.radius = 12;
  80016. /**
  80017. * Define a rotation offset between the camera and the object it follows
  80018. */
  80019. _this.rotationOffset = 0;
  80020. /**
  80021. * Define a height offset between the camera and the object it follows.
  80022. * It can help following an object from the top (like a car chaing a plane)
  80023. */
  80024. _this.heightOffset = 4;
  80025. /**
  80026. * Define how fast the camera can accelerate to follow it s target.
  80027. */
  80028. _this.cameraAcceleration = 0.05;
  80029. /**
  80030. * Define the speed limit of the camera following an object.
  80031. */
  80032. _this.maxCameraSpeed = 20;
  80033. _this.lockedTarget = lockedTarget;
  80034. return _this;
  80035. }
  80036. FollowCamera.prototype._follow = function (cameraTarget) {
  80037. if (!cameraTarget)
  80038. return;
  80039. var yRotation;
  80040. if (cameraTarget.rotationQuaternion) {
  80041. var rotMatrix = new BABYLON.Matrix();
  80042. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  80043. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  80044. }
  80045. else {
  80046. yRotation = cameraTarget.rotation.y;
  80047. }
  80048. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  80049. var targetPosition = cameraTarget.getAbsolutePosition();
  80050. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  80051. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  80052. var dx = targetX - this.position.x;
  80053. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  80054. var dz = (targetZ) - this.position.z;
  80055. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  80056. var vy = dy * this.cameraAcceleration;
  80057. var vz = dz * this.cameraAcceleration * 2;
  80058. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  80059. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80060. }
  80061. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  80062. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80063. }
  80064. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  80065. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80066. }
  80067. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  80068. this.setTarget(targetPosition);
  80069. };
  80070. /** @hidden */
  80071. FollowCamera.prototype._checkInputs = function () {
  80072. _super.prototype._checkInputs.call(this);
  80073. if (this.lockedTarget) {
  80074. this._follow(this.lockedTarget);
  80075. }
  80076. };
  80077. /**
  80078. * Gets the camera class name.
  80079. * @returns the class name
  80080. */
  80081. FollowCamera.prototype.getClassName = function () {
  80082. return "FollowCamera";
  80083. };
  80084. __decorate([
  80085. BABYLON.serialize()
  80086. ], FollowCamera.prototype, "radius", void 0);
  80087. __decorate([
  80088. BABYLON.serialize()
  80089. ], FollowCamera.prototype, "rotationOffset", void 0);
  80090. __decorate([
  80091. BABYLON.serialize()
  80092. ], FollowCamera.prototype, "heightOffset", void 0);
  80093. __decorate([
  80094. BABYLON.serialize()
  80095. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  80096. __decorate([
  80097. BABYLON.serialize()
  80098. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  80099. __decorate([
  80100. BABYLON.serializeAsMeshReference("lockedTargetId")
  80101. ], FollowCamera.prototype, "lockedTarget", void 0);
  80102. return FollowCamera;
  80103. }(BABYLON.TargetCamera));
  80104. BABYLON.FollowCamera = FollowCamera;
  80105. /**
  80106. * Arc Rotate version of the follow camera.
  80107. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  80108. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80109. */
  80110. var ArcFollowCamera = /** @class */ (function (_super) {
  80111. __extends(ArcFollowCamera, _super);
  80112. /**
  80113. * Instantiates a new ArcFollowCamera
  80114. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80115. * @param name Define the name of the camera
  80116. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  80117. * @param beta Define the rotation angle of the camera around the elevation axis
  80118. * @param radius Define the radius of the camera from its target point
  80119. * @param target Define the target of the camera
  80120. * @param scene Define the scene the camera belongs to
  80121. */
  80122. function ArcFollowCamera(name,
  80123. /** The longitudinal angle of the camera */
  80124. alpha,
  80125. /** The latitudinal angle of the camera */
  80126. beta,
  80127. /** The radius of the camera from its target */
  80128. radius,
  80129. /** Define the camera target (the messh it should follow) */
  80130. target, scene) {
  80131. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  80132. _this.alpha = alpha;
  80133. _this.beta = beta;
  80134. _this.radius = radius;
  80135. _this.target = target;
  80136. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  80137. _this._follow();
  80138. return _this;
  80139. }
  80140. ArcFollowCamera.prototype._follow = function () {
  80141. if (!this.target) {
  80142. return;
  80143. }
  80144. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  80145. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  80146. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  80147. var targetPosition = this.target.getAbsolutePosition();
  80148. this.position = targetPosition.add(this._cartesianCoordinates);
  80149. this.setTarget(targetPosition);
  80150. };
  80151. /** @hidden */
  80152. ArcFollowCamera.prototype._checkInputs = function () {
  80153. _super.prototype._checkInputs.call(this);
  80154. this._follow();
  80155. };
  80156. /**
  80157. * Returns the class name of the object.
  80158. * It is mostly used internally for serialization purposes.
  80159. */
  80160. ArcFollowCamera.prototype.getClassName = function () {
  80161. return "ArcFollowCamera";
  80162. };
  80163. return ArcFollowCamera;
  80164. }(BABYLON.TargetCamera));
  80165. BABYLON.ArcFollowCamera = ArcFollowCamera;
  80166. })(BABYLON || (BABYLON = {}));
  80167. //# sourceMappingURL=babylon.followCamera.js.map
  80168. var BABYLON;
  80169. (function (BABYLON) {
  80170. /**
  80171. * 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,
  80172. * which still works and will still be found in many Playgrounds.
  80173. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80174. */
  80175. var UniversalCamera = /** @class */ (function (_super) {
  80176. __extends(UniversalCamera, _super);
  80177. /**
  80178. * 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,
  80179. * which still works and will still be found in many Playgrounds.
  80180. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80181. * @param name Define the name of the camera in the scene
  80182. * @param position Define the start position of the camera in the scene
  80183. * @param scene Define the scene the camera belongs to
  80184. */
  80185. function UniversalCamera(name, position, scene) {
  80186. var _this = _super.call(this, name, position, scene) || this;
  80187. _this.inputs.addGamepad();
  80188. return _this;
  80189. }
  80190. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  80191. /**
  80192. * Defines the gamepad rotation sensiblity.
  80193. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  80194. */
  80195. get: function () {
  80196. var gamepad = this.inputs.attached["gamepad"];
  80197. if (gamepad)
  80198. return gamepad.gamepadAngularSensibility;
  80199. return 0;
  80200. },
  80201. set: function (value) {
  80202. var gamepad = this.inputs.attached["gamepad"];
  80203. if (gamepad)
  80204. gamepad.gamepadAngularSensibility = value;
  80205. },
  80206. enumerable: true,
  80207. configurable: true
  80208. });
  80209. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  80210. /**
  80211. * Defines the gamepad move sensiblity.
  80212. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  80213. */
  80214. get: function () {
  80215. var gamepad = this.inputs.attached["gamepad"];
  80216. if (gamepad)
  80217. return gamepad.gamepadMoveSensibility;
  80218. return 0;
  80219. },
  80220. set: function (value) {
  80221. var gamepad = this.inputs.attached["gamepad"];
  80222. if (gamepad)
  80223. gamepad.gamepadMoveSensibility = value;
  80224. },
  80225. enumerable: true,
  80226. configurable: true
  80227. });
  80228. /**
  80229. * Gets the current object class name.
  80230. * @return the class name
  80231. */
  80232. UniversalCamera.prototype.getClassName = function () {
  80233. return "UniversalCamera";
  80234. };
  80235. return UniversalCamera;
  80236. }(BABYLON.TouchCamera));
  80237. BABYLON.UniversalCamera = UniversalCamera;
  80238. })(BABYLON || (BABYLON = {}));
  80239. //# sourceMappingURL=babylon.universalCamera.js.map
  80240. var BABYLON;
  80241. (function (BABYLON) {
  80242. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  80243. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  80244. });
  80245. /**
  80246. * This represents a FPS type of camera. This is only here for back compat purpose.
  80247. * Please use the UniversalCamera instead as both are identical.
  80248. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80249. */
  80250. var GamepadCamera = /** @class */ (function (_super) {
  80251. __extends(GamepadCamera, _super);
  80252. /**
  80253. * Instantiates a new Gamepad Camera
  80254. * This represents a FPS type of camera. This is only here for back compat purpose.
  80255. * Please use the UniversalCamera instead as both are identical.
  80256. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80257. * @param name Define the name of the camera in the scene
  80258. * @param position Define the start position of the camera in the scene
  80259. * @param scene Define the scene the camera belongs to
  80260. */
  80261. function GamepadCamera(name, position, scene) {
  80262. return _super.call(this, name, position, scene) || this;
  80263. }
  80264. /**
  80265. * Gets the current object class name.
  80266. * @return the class name
  80267. */
  80268. GamepadCamera.prototype.getClassName = function () {
  80269. return "GamepadCamera";
  80270. };
  80271. return GamepadCamera;
  80272. }(BABYLON.UniversalCamera));
  80273. BABYLON.GamepadCamera = GamepadCamera;
  80274. })(BABYLON || (BABYLON = {}));
  80275. //# sourceMappingURL=babylon.gamepadCamera.js.map
  80276. var BABYLON;
  80277. (function (BABYLON) {
  80278. var PostProcessRenderPipelineManager = /** @class */ (function () {
  80279. function PostProcessRenderPipelineManager() {
  80280. this._renderPipelines = {};
  80281. }
  80282. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  80283. this._renderPipelines[renderPipeline._name] = renderPipeline;
  80284. };
  80285. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  80286. if (unique === void 0) { unique = false; }
  80287. var renderPipeline = this._renderPipelines[renderPipelineName];
  80288. if (!renderPipeline) {
  80289. return;
  80290. }
  80291. renderPipeline._attachCameras(cameras, unique);
  80292. };
  80293. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  80294. var renderPipeline = this._renderPipelines[renderPipelineName];
  80295. if (!renderPipeline) {
  80296. return;
  80297. }
  80298. renderPipeline._detachCameras(cameras);
  80299. };
  80300. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  80301. var renderPipeline = this._renderPipelines[renderPipelineName];
  80302. if (!renderPipeline) {
  80303. return;
  80304. }
  80305. renderPipeline._enableEffect(renderEffectName, cameras);
  80306. };
  80307. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  80308. var renderPipeline = this._renderPipelines[renderPipelineName];
  80309. if (!renderPipeline) {
  80310. return;
  80311. }
  80312. renderPipeline._disableEffect(renderEffectName, cameras);
  80313. };
  80314. PostProcessRenderPipelineManager.prototype.update = function () {
  80315. for (var renderPipelineName in this._renderPipelines) {
  80316. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  80317. var pipeline = this._renderPipelines[renderPipelineName];
  80318. if (!pipeline.isSupported) {
  80319. pipeline.dispose();
  80320. delete this._renderPipelines[renderPipelineName];
  80321. }
  80322. else {
  80323. pipeline._update();
  80324. }
  80325. }
  80326. }
  80327. };
  80328. /** @hidden */
  80329. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  80330. for (var renderPipelineName in this._renderPipelines) {
  80331. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  80332. var pipeline = this._renderPipelines[renderPipelineName];
  80333. pipeline._rebuild();
  80334. }
  80335. }
  80336. };
  80337. PostProcessRenderPipelineManager.prototype.dispose = function () {
  80338. for (var renderPipelineName in this._renderPipelines) {
  80339. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  80340. var pipeline = this._renderPipelines[renderPipelineName];
  80341. pipeline.dispose();
  80342. }
  80343. }
  80344. };
  80345. return PostProcessRenderPipelineManager;
  80346. }());
  80347. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  80348. })(BABYLON || (BABYLON = {}));
  80349. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  80350. var BABYLON;
  80351. (function (BABYLON) {
  80352. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  80353. get: function () {
  80354. if (!this._postProcessRenderPipelineManager) {
  80355. // Register the G Buffer component to the scene.
  80356. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  80357. if (!component) {
  80358. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  80359. this._addComponent(component);
  80360. }
  80361. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  80362. }
  80363. return this._postProcessRenderPipelineManager;
  80364. },
  80365. enumerable: true,
  80366. configurable: true
  80367. });
  80368. /**
  80369. * Defines the Render Pipeline scene component responsible to rendering pipelines
  80370. */
  80371. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  80372. /**
  80373. * Creates a new instance of the component for the given scene
  80374. * @param scene Defines the scene to register the component in
  80375. */
  80376. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  80377. /**
  80378. * The component name helpfull to identify the component in the list of scene components.
  80379. */
  80380. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  80381. this.scene = scene;
  80382. }
  80383. /**
  80384. * Registers the component in a given scene
  80385. */
  80386. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  80387. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  80388. };
  80389. /**
  80390. * Rebuilds the elements related to this component in case of
  80391. * context lost for instance.
  80392. */
  80393. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  80394. if (this.scene._postProcessRenderPipelineManager) {
  80395. this.scene._postProcessRenderPipelineManager._rebuild();
  80396. }
  80397. };
  80398. /**
  80399. * Disposes the component and the associated ressources
  80400. */
  80401. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  80402. if (this.scene._postProcessRenderPipelineManager) {
  80403. this.scene._postProcessRenderPipelineManager.dispose();
  80404. }
  80405. };
  80406. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80407. if (this.scene._postProcessRenderPipelineManager) {
  80408. this.scene._postProcessRenderPipelineManager.update();
  80409. }
  80410. };
  80411. return PostProcessRenderPipelineManagerSceneComponent;
  80412. }());
  80413. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  80414. })(BABYLON || (BABYLON = {}));
  80415. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  80416. var BABYLON;
  80417. (function (BABYLON) {
  80418. /**
  80419. * This represents a set of one or more post processes in Babylon.
  80420. * A post process can be used to apply a shader to a texture after it is rendered.
  80421. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  80422. */
  80423. var PostProcessRenderEffect = /** @class */ (function () {
  80424. /**
  80425. * Instantiates a post process render effect.
  80426. * A post process can be used to apply a shader to a texture after it is rendered.
  80427. * @param engine The engine the effect is tied to
  80428. * @param name The name of the effect
  80429. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  80430. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  80431. */
  80432. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  80433. this._name = name;
  80434. this._singleInstance = singleInstance || true;
  80435. this._getPostProcesses = getPostProcesses;
  80436. this._cameras = {};
  80437. this._indicesForCamera = {};
  80438. this._postProcesses = {};
  80439. }
  80440. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  80441. /**
  80442. * Checks if all the post processes in the effect are supported.
  80443. */
  80444. get: function () {
  80445. for (var index in this._postProcesses) {
  80446. if (this._postProcesses.hasOwnProperty(index)) {
  80447. var pps = this._postProcesses[index];
  80448. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  80449. if (!pps[ppIndex].isSupported) {
  80450. return false;
  80451. }
  80452. }
  80453. }
  80454. }
  80455. return true;
  80456. },
  80457. enumerable: true,
  80458. configurable: true
  80459. });
  80460. /**
  80461. * Updates the current state of the effect
  80462. * @hidden
  80463. */
  80464. PostProcessRenderEffect.prototype._update = function () {
  80465. };
  80466. /**
  80467. * Attaches the effect on cameras
  80468. * @param cameras The camera to attach to.
  80469. * @hidden
  80470. */
  80471. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  80472. var _this = this;
  80473. var cameraKey;
  80474. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80475. if (!cams) {
  80476. return;
  80477. }
  80478. for (var i = 0; i < cams.length; i++) {
  80479. var camera = cams[i];
  80480. var cameraName = camera.name;
  80481. if (this._singleInstance) {
  80482. cameraKey = 0;
  80483. }
  80484. else {
  80485. cameraKey = cameraName;
  80486. }
  80487. if (!this._postProcesses[cameraKey]) {
  80488. var postProcess = this._getPostProcesses();
  80489. if (postProcess) {
  80490. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  80491. }
  80492. }
  80493. if (!this._indicesForCamera[cameraName]) {
  80494. this._indicesForCamera[cameraName] = [];
  80495. }
  80496. this._postProcesses[cameraKey].forEach(function (postProcess) {
  80497. var index = camera.attachPostProcess(postProcess);
  80498. _this._indicesForCamera[cameraName].push(index);
  80499. });
  80500. if (!this._cameras[cameraName]) {
  80501. this._cameras[cameraName] = camera;
  80502. }
  80503. }
  80504. };
  80505. /**
  80506. * Detatches the effect on cameras
  80507. * @param cameras The camera to detatch from.
  80508. * @hidden
  80509. */
  80510. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  80511. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80512. if (!cams) {
  80513. return;
  80514. }
  80515. for (var i = 0; i < cams.length; i++) {
  80516. var camera = cams[i];
  80517. var cameraName = camera.name;
  80518. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80519. camera.detachPostProcess(postProcess);
  80520. });
  80521. if (this._cameras[cameraName]) {
  80522. //this._indicesForCamera.splice(index, 1);
  80523. this._cameras[cameraName] = null;
  80524. }
  80525. }
  80526. };
  80527. /**
  80528. * Enables the effect on given cameras
  80529. * @param cameras The camera to enable.
  80530. * @hidden
  80531. */
  80532. PostProcessRenderEffect.prototype._enable = function (cameras) {
  80533. var _this = this;
  80534. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80535. if (!cams) {
  80536. return;
  80537. }
  80538. for (var i = 0; i < cams.length; i++) {
  80539. var camera = cams[i];
  80540. var cameraName = camera.name;
  80541. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  80542. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  80543. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80544. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  80545. });
  80546. }
  80547. }
  80548. }
  80549. };
  80550. /**
  80551. * Disables the effect on the given cameras
  80552. * @param cameras The camera to disable.
  80553. * @hidden
  80554. */
  80555. PostProcessRenderEffect.prototype._disable = function (cameras) {
  80556. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80557. if (!cams) {
  80558. return;
  80559. }
  80560. for (var i = 0; i < cams.length; i++) {
  80561. var camera = cams[i];
  80562. var cameraName = camera.name;
  80563. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80564. camera.detachPostProcess(postProcess);
  80565. });
  80566. }
  80567. };
  80568. /**
  80569. * Gets a list of the post processes contained in the effect.
  80570. * @param camera The camera to get the post processes on.
  80571. * @returns The list of the post processes in the effect.
  80572. */
  80573. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  80574. if (this._singleInstance) {
  80575. return this._postProcesses[0];
  80576. }
  80577. else {
  80578. if (!camera) {
  80579. return null;
  80580. }
  80581. return this._postProcesses[camera.name];
  80582. }
  80583. };
  80584. return PostProcessRenderEffect;
  80585. }());
  80586. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  80587. })(BABYLON || (BABYLON = {}));
  80588. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  80589. var BABYLON;
  80590. (function (BABYLON) {
  80591. var PostProcessRenderPipeline = /** @class */ (function () {
  80592. function PostProcessRenderPipeline(engine, name) {
  80593. this.engine = engine;
  80594. this._name = name;
  80595. this._renderEffects = {};
  80596. this._renderEffectsForIsolatedPass = new Array();
  80597. this._cameras = [];
  80598. }
  80599. PostProcessRenderPipeline.prototype.getClassName = function () {
  80600. return "PostProcessRenderPipeline";
  80601. };
  80602. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  80603. get: function () {
  80604. for (var renderEffectName in this._renderEffects) {
  80605. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80606. if (!this._renderEffects[renderEffectName].isSupported) {
  80607. return false;
  80608. }
  80609. }
  80610. }
  80611. return true;
  80612. },
  80613. enumerable: true,
  80614. configurable: true
  80615. });
  80616. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  80617. this._renderEffects[renderEffect._name] = renderEffect;
  80618. };
  80619. // private
  80620. /** @hidden */
  80621. PostProcessRenderPipeline.prototype._rebuild = function () {
  80622. };
  80623. /** @hidden */
  80624. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  80625. var renderEffects = this._renderEffects[renderEffectName];
  80626. if (!renderEffects) {
  80627. return;
  80628. }
  80629. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80630. };
  80631. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  80632. var renderEffects = this._renderEffects[renderEffectName];
  80633. if (!renderEffects) {
  80634. return;
  80635. }
  80636. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80637. };
  80638. /** @hidden */
  80639. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  80640. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80641. if (!cams) {
  80642. return;
  80643. }
  80644. var indicesToDelete = [];
  80645. var i;
  80646. for (i = 0; i < cams.length; i++) {
  80647. var camera = cams[i];
  80648. var cameraName = camera.name;
  80649. if (this._cameras.indexOf(camera) === -1) {
  80650. this._cameras[cameraName] = camera;
  80651. }
  80652. else if (unique) {
  80653. indicesToDelete.push(i);
  80654. }
  80655. }
  80656. for (i = 0; i < indicesToDelete.length; i++) {
  80657. cameras.splice(indicesToDelete[i], 1);
  80658. }
  80659. for (var renderEffectName in this._renderEffects) {
  80660. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80661. this._renderEffects[renderEffectName]._attachCameras(cams);
  80662. }
  80663. }
  80664. };
  80665. /** @hidden */
  80666. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  80667. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80668. if (!cams) {
  80669. return;
  80670. }
  80671. for (var renderEffectName in this._renderEffects) {
  80672. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80673. this._renderEffects[renderEffectName]._detachCameras(cams);
  80674. }
  80675. }
  80676. for (var i = 0; i < cams.length; i++) {
  80677. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  80678. }
  80679. };
  80680. /** @hidden */
  80681. PostProcessRenderPipeline.prototype._update = function () {
  80682. for (var renderEffectName in this._renderEffects) {
  80683. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80684. this._renderEffects[renderEffectName]._update();
  80685. }
  80686. }
  80687. for (var i = 0; i < this._cameras.length; i++) {
  80688. var cameraName = this._cameras[i].name;
  80689. if (this._renderEffectsForIsolatedPass[cameraName]) {
  80690. this._renderEffectsForIsolatedPass[cameraName]._update();
  80691. }
  80692. }
  80693. };
  80694. /** @hidden */
  80695. PostProcessRenderPipeline.prototype._reset = function () {
  80696. this._renderEffects = {};
  80697. this._renderEffectsForIsolatedPass = new Array();
  80698. };
  80699. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  80700. // 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)
  80701. var effectKeys = Object.keys(this._renderEffects);
  80702. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  80703. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  80704. if (postProcesses) {
  80705. postProcesses[0].samples = sampleCount;
  80706. return true;
  80707. }
  80708. }
  80709. return false;
  80710. };
  80711. PostProcessRenderPipeline.prototype.dispose = function () {
  80712. // Must be implemented by children
  80713. };
  80714. __decorate([
  80715. BABYLON.serialize()
  80716. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  80717. return PostProcessRenderPipeline;
  80718. }());
  80719. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  80720. })(BABYLON || (BABYLON = {}));
  80721. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  80722. var BABYLON;
  80723. (function (BABYLON) {
  80724. /**
  80725. * This represents a depth renderer in Babylon.
  80726. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  80727. */
  80728. var DepthRenderer = /** @class */ (function () {
  80729. /**
  80730. * Instantiates a depth renderer
  80731. * @param scene The scene the renderer belongs to
  80732. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  80733. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  80734. */
  80735. function DepthRenderer(scene, type, camera) {
  80736. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  80737. if (camera === void 0) { camera = null; }
  80738. var _this = this;
  80739. /**
  80740. * Specifiess that the depth renderer will only be used within
  80741. * the camera it is created for.
  80742. * This can help forcing its rendering during the camera processing.
  80743. */
  80744. this.useOnlyInActiveCamera = false;
  80745. this._scene = scene;
  80746. // Register the G Buffer component to the scene.
  80747. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  80748. if (!component) {
  80749. component = new BABYLON.DepthRendererSceneComponent(scene);
  80750. scene._addComponent(component);
  80751. }
  80752. this._camera = camera;
  80753. var engine = scene.getEngine();
  80754. // Render target
  80755. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  80756. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80757. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80758. this._depthMap.refreshRate = 1;
  80759. this._depthMap.renderParticles = false;
  80760. this._depthMap.renderList = null;
  80761. // Camera to get depth map from to support multiple concurrent cameras
  80762. this._depthMap.activeCamera = this._camera;
  80763. this._depthMap.ignoreCameraViewport = true;
  80764. this._depthMap.useCameraPostProcesses = false;
  80765. // set default depth value to 1.0 (far away)
  80766. this._depthMap.onClearObservable.add(function (engine) {
  80767. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  80768. });
  80769. // Custom render function
  80770. var renderSubMesh = function (subMesh) {
  80771. var mesh = subMesh.getRenderingMesh();
  80772. var scene = _this._scene;
  80773. var engine = scene.getEngine();
  80774. var material = subMesh.getMaterial();
  80775. if (!material) {
  80776. return;
  80777. }
  80778. // Culling and reverse (right handed system)
  80779. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80780. // Managing instances
  80781. var batch = mesh._getInstancesRenderList(subMesh._id);
  80782. if (batch.mustReturn) {
  80783. return;
  80784. }
  80785. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80786. var camera = _this._camera || scene.activeCamera;
  80787. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  80788. engine.enableEffect(_this._effect);
  80789. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80790. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80791. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  80792. // Alpha test
  80793. if (material && material.needAlphaTesting()) {
  80794. var alphaTexture = material.getAlphaTestTexture();
  80795. if (alphaTexture) {
  80796. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80797. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80798. }
  80799. }
  80800. // Bones
  80801. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80802. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80803. }
  80804. // Draw
  80805. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80806. }
  80807. };
  80808. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80809. var index;
  80810. if (depthOnlySubMeshes.length) {
  80811. engine.setColorWrite(false);
  80812. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80813. renderSubMesh(depthOnlySubMeshes.data[index]);
  80814. }
  80815. engine.setColorWrite(true);
  80816. }
  80817. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80818. renderSubMesh(opaqueSubMeshes.data[index]);
  80819. }
  80820. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80821. renderSubMesh(alphaTestSubMeshes.data[index]);
  80822. }
  80823. };
  80824. }
  80825. /**
  80826. * Creates the depth rendering effect and checks if the effect is ready.
  80827. * @param subMesh The submesh to be used to render the depth map of
  80828. * @param useInstances If multiple world instances should be used
  80829. * @returns if the depth renderer is ready to render the depth map
  80830. */
  80831. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  80832. var material = subMesh.getMaterial();
  80833. if (material.disableDepthWrite) {
  80834. return false;
  80835. }
  80836. var defines = [];
  80837. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80838. var mesh = subMesh.getMesh();
  80839. // Alpha test
  80840. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  80841. defines.push("#define ALPHATEST");
  80842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80843. attribs.push(BABYLON.VertexBuffer.UVKind);
  80844. defines.push("#define UV1");
  80845. }
  80846. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80847. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80848. defines.push("#define UV2");
  80849. }
  80850. }
  80851. // Bones
  80852. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80853. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80854. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80855. if (mesh.numBoneInfluencers > 4) {
  80856. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80857. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80858. }
  80859. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80860. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80861. }
  80862. else {
  80863. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80864. }
  80865. // Instances
  80866. if (useInstances) {
  80867. defines.push("#define INSTANCES");
  80868. attribs.push("world0");
  80869. attribs.push("world1");
  80870. attribs.push("world2");
  80871. attribs.push("world3");
  80872. }
  80873. // Get correct effect
  80874. var join = defines.join("\n");
  80875. if (this._cachedDefines !== join) {
  80876. this._cachedDefines = join;
  80877. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  80878. }
  80879. return this._effect.isReady();
  80880. };
  80881. /**
  80882. * Gets the texture which the depth map will be written to.
  80883. * @returns The depth map texture
  80884. */
  80885. DepthRenderer.prototype.getDepthMap = function () {
  80886. return this._depthMap;
  80887. };
  80888. /**
  80889. * Disposes of the depth renderer.
  80890. */
  80891. DepthRenderer.prototype.dispose = function () {
  80892. this._depthMap.dispose();
  80893. };
  80894. return DepthRenderer;
  80895. }());
  80896. BABYLON.DepthRenderer = DepthRenderer;
  80897. })(BABYLON || (BABYLON = {}));
  80898. //# sourceMappingURL=babylon.depthRenderer.js.map
  80899. var BABYLON;
  80900. (function (BABYLON) {
  80901. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  80902. camera = camera || this.activeCamera;
  80903. if (!camera) {
  80904. throw "No camera available to enable depth renderer";
  80905. }
  80906. if (!this._depthRenderer) {
  80907. this._depthRenderer = {};
  80908. }
  80909. if (!this._depthRenderer[camera.id]) {
  80910. var textureType = 0;
  80911. if (this.getEngine().getCaps().textureHalfFloatRender) {
  80912. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80913. }
  80914. else if (this.getEngine().getCaps().textureFloatRender) {
  80915. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80916. }
  80917. else {
  80918. throw "Depth renderer does not support int texture type";
  80919. }
  80920. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  80921. }
  80922. return this._depthRenderer[camera.id];
  80923. };
  80924. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  80925. camera = camera || this.activeCamera;
  80926. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  80927. return;
  80928. }
  80929. this._depthRenderer[camera.id].dispose();
  80930. delete this._depthRenderer[camera.id];
  80931. };
  80932. /**
  80933. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  80934. * in several rendering techniques.
  80935. */
  80936. var DepthRendererSceneComponent = /** @class */ (function () {
  80937. /**
  80938. * Creates a new instance of the component for the given scene
  80939. * @param scene Defines the scene to register the component in
  80940. */
  80941. function DepthRendererSceneComponent(scene) {
  80942. /**
  80943. * The component name helpfull to identify the component in the list of scene components.
  80944. */
  80945. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  80946. this.scene = scene;
  80947. }
  80948. /**
  80949. * Registers the component in a given scene
  80950. */
  80951. DepthRendererSceneComponent.prototype.register = function () {
  80952. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  80953. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  80954. };
  80955. /**
  80956. * Rebuilds the elements related to this component in case of
  80957. * context lost for instance.
  80958. */
  80959. DepthRendererSceneComponent.prototype.rebuild = function () {
  80960. // Nothing to do for this component
  80961. };
  80962. /**
  80963. * Disposes the component and the associated ressources
  80964. */
  80965. DepthRendererSceneComponent.prototype.dispose = function () {
  80966. for (var key in this.scene._depthRenderer) {
  80967. this.scene._depthRenderer[key].dispose();
  80968. }
  80969. };
  80970. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80971. if (this.scene._depthRenderer) {
  80972. for (var key in this.scene._depthRenderer) {
  80973. var depthRenderer = this.scene._depthRenderer[key];
  80974. if (!depthRenderer.useOnlyInActiveCamera) {
  80975. renderTargets.push(depthRenderer.getDepthMap());
  80976. }
  80977. }
  80978. }
  80979. };
  80980. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  80981. if (this.scene._depthRenderer) {
  80982. for (var key in this.scene._depthRenderer) {
  80983. var depthRenderer = this.scene._depthRenderer[key];
  80984. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  80985. renderTargets.push(depthRenderer.getDepthMap());
  80986. }
  80987. }
  80988. }
  80989. };
  80990. return DepthRendererSceneComponent;
  80991. }());
  80992. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  80993. })(BABYLON || (BABYLON = {}));
  80994. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  80995. var BABYLON;
  80996. (function (BABYLON) {
  80997. /**
  80998. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  80999. */
  81000. var GeometryBufferRenderer = /** @class */ (function () {
  81001. /**
  81002. * Creates a new G Buffer for the scene
  81003. * @param scene The scene the buffer belongs to
  81004. * @param ratio How big is the buffer related to the main canvas.
  81005. */
  81006. function GeometryBufferRenderer(scene, ratio) {
  81007. if (ratio === void 0) { ratio = 1; }
  81008. this._enablePosition = false;
  81009. this._scene = scene;
  81010. this._ratio = ratio;
  81011. // Register the G Buffer component to the scene.
  81012. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  81013. if (!component) {
  81014. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  81015. scene._addComponent(component);
  81016. }
  81017. // Render target
  81018. this._createRenderTargets();
  81019. }
  81020. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  81021. /**
  81022. * Set the render list (meshes to be rendered) used in the G buffer.
  81023. */
  81024. set: function (meshes) {
  81025. this._multiRenderTarget.renderList = meshes;
  81026. },
  81027. enumerable: true,
  81028. configurable: true
  81029. });
  81030. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  81031. /**
  81032. * Gets wether or not G buffer are supported by the running hardware.
  81033. * This requires draw buffer supports
  81034. */
  81035. get: function () {
  81036. return this._multiRenderTarget.isSupported;
  81037. },
  81038. enumerable: true,
  81039. configurable: true
  81040. });
  81041. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  81042. /**
  81043. * Gets wether or not position are enabled for the G buffer.
  81044. */
  81045. get: function () {
  81046. return this._enablePosition;
  81047. },
  81048. /**
  81049. * Sets wether or not position are enabled for the G buffer.
  81050. */
  81051. set: function (enable) {
  81052. this._enablePosition = enable;
  81053. this.dispose();
  81054. this._createRenderTargets();
  81055. },
  81056. enumerable: true,
  81057. configurable: true
  81058. });
  81059. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  81060. /**
  81061. * Gets the scene associated with the buffer.
  81062. */
  81063. get: function () {
  81064. return this._scene;
  81065. },
  81066. enumerable: true,
  81067. configurable: true
  81068. });
  81069. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  81070. /**
  81071. * Gets the ratio used by the buffer during its creation.
  81072. * How big is the buffer related to the main canvas.
  81073. */
  81074. get: function () {
  81075. return this._ratio;
  81076. },
  81077. enumerable: true,
  81078. configurable: true
  81079. });
  81080. /**
  81081. * Checks wether everything is ready to render a submesh to the G buffer.
  81082. * @param subMesh the submesh to check readiness for
  81083. * @param useInstances is the mesh drawn using instance or not
  81084. * @returns true if ready otherwise false
  81085. */
  81086. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  81087. var material = subMesh.getMaterial();
  81088. if (material && material.disableDepthWrite) {
  81089. return false;
  81090. }
  81091. var defines = [];
  81092. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81093. var mesh = subMesh.getMesh();
  81094. // Alpha test
  81095. if (material && material.needAlphaTesting()) {
  81096. defines.push("#define ALPHATEST");
  81097. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81098. attribs.push(BABYLON.VertexBuffer.UVKind);
  81099. defines.push("#define UV1");
  81100. }
  81101. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81102. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81103. defines.push("#define UV2");
  81104. }
  81105. }
  81106. // Buffers
  81107. if (this._enablePosition) {
  81108. defines.push("#define POSITION");
  81109. }
  81110. // Bones
  81111. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81112. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81113. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81114. if (mesh.numBoneInfluencers > 4) {
  81115. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81116. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81117. }
  81118. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81119. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81120. }
  81121. else {
  81122. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81123. }
  81124. // Instances
  81125. if (useInstances) {
  81126. defines.push("#define INSTANCES");
  81127. attribs.push("world0");
  81128. attribs.push("world1");
  81129. attribs.push("world2");
  81130. attribs.push("world3");
  81131. }
  81132. // Get correct effect
  81133. var join = defines.join("\n");
  81134. if (this._cachedDefines !== join) {
  81135. this._cachedDefines = join;
  81136. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  81137. }
  81138. return this._effect.isReady();
  81139. };
  81140. /**
  81141. * Gets the current underlying G Buffer.
  81142. * @returns the buffer
  81143. */
  81144. GeometryBufferRenderer.prototype.getGBuffer = function () {
  81145. return this._multiRenderTarget;
  81146. };
  81147. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  81148. /**
  81149. * Gets the number of samples used to render the buffer (anti aliasing).
  81150. */
  81151. get: function () {
  81152. return this._multiRenderTarget.samples;
  81153. },
  81154. /**
  81155. * Sets the number of samples used to render the buffer (anti aliasing).
  81156. */
  81157. set: function (value) {
  81158. this._multiRenderTarget.samples = value;
  81159. },
  81160. enumerable: true,
  81161. configurable: true
  81162. });
  81163. /**
  81164. * Disposes the renderer and frees up associated resources.
  81165. */
  81166. GeometryBufferRenderer.prototype.dispose = function () {
  81167. this.getGBuffer().dispose();
  81168. };
  81169. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  81170. var _this = this;
  81171. var engine = this._scene.getEngine();
  81172. var count = this._enablePosition ? 3 : 2;
  81173. 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 });
  81174. if (!this.isSupported) {
  81175. return;
  81176. }
  81177. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81178. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81179. this._multiRenderTarget.refreshRate = 1;
  81180. this._multiRenderTarget.renderParticles = false;
  81181. this._multiRenderTarget.renderList = null;
  81182. // set default depth value to 1.0 (far away)
  81183. this._multiRenderTarget.onClearObservable.add(function (engine) {
  81184. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  81185. });
  81186. // Custom render function
  81187. var renderSubMesh = function (subMesh) {
  81188. var mesh = subMesh.getRenderingMesh();
  81189. var scene = _this._scene;
  81190. var engine = scene.getEngine();
  81191. var material = subMesh.getMaterial();
  81192. if (!material) {
  81193. return;
  81194. }
  81195. // Culling
  81196. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  81197. // Managing instances
  81198. var batch = mesh._getInstancesRenderList(subMesh._id);
  81199. if (batch.mustReturn) {
  81200. return;
  81201. }
  81202. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81203. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  81204. engine.enableEffect(_this._effect);
  81205. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  81206. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81207. _this._effect.setMatrix("view", scene.getViewMatrix());
  81208. // Alpha test
  81209. if (material && material.needAlphaTesting()) {
  81210. var alphaTexture = material.getAlphaTestTexture();
  81211. if (alphaTexture) {
  81212. _this._effect.setTexture("diffuseSampler", alphaTexture);
  81213. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81214. }
  81215. }
  81216. // Bones
  81217. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81218. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81219. }
  81220. // Draw
  81221. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  81222. }
  81223. };
  81224. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81225. var index;
  81226. if (depthOnlySubMeshes.length) {
  81227. engine.setColorWrite(false);
  81228. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81229. renderSubMesh(depthOnlySubMeshes.data[index]);
  81230. }
  81231. engine.setColorWrite(true);
  81232. }
  81233. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81234. renderSubMesh(opaqueSubMeshes.data[index]);
  81235. }
  81236. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  81237. renderSubMesh(alphaTestSubMeshes.data[index]);
  81238. }
  81239. };
  81240. };
  81241. return GeometryBufferRenderer;
  81242. }());
  81243. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  81244. })(BABYLON || (BABYLON = {}));
  81245. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  81246. var BABYLON;
  81247. (function (BABYLON) {
  81248. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  81249. get: function () {
  81250. this._geometryBufferRenderer;
  81251. },
  81252. set: function (value) {
  81253. if (value && value.isSupported) {
  81254. this._geometryBufferRenderer = value;
  81255. }
  81256. ;
  81257. },
  81258. enumerable: true,
  81259. configurable: true
  81260. });
  81261. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  81262. if (ratio === void 0) { ratio = 1; }
  81263. if (this._geometryBufferRenderer) {
  81264. return this._geometryBufferRenderer;
  81265. }
  81266. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  81267. if (!this._geometryBufferRenderer.isSupported) {
  81268. this._geometryBufferRenderer = null;
  81269. }
  81270. return this._geometryBufferRenderer;
  81271. };
  81272. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  81273. if (!this._geometryBufferRenderer) {
  81274. return;
  81275. }
  81276. this._geometryBufferRenderer.dispose();
  81277. this._geometryBufferRenderer = null;
  81278. };
  81279. /**
  81280. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  81281. * in several rendering techniques.
  81282. */
  81283. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  81284. /**
  81285. * Creates a new instance of the component for the given scene
  81286. * @param scene Defines the scene to register the component in
  81287. */
  81288. function GeometryBufferRendererSceneComponent(scene) {
  81289. /**
  81290. * The component name helpful to identify the component in the list of scene components.
  81291. */
  81292. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  81293. this.scene = scene;
  81294. }
  81295. /**
  81296. * Registers the component in a given scene
  81297. */
  81298. GeometryBufferRendererSceneComponent.prototype.register = function () {
  81299. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  81300. };
  81301. /**
  81302. * Rebuilds the elements related to this component in case of
  81303. * context lost for instance.
  81304. */
  81305. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  81306. // Nothing to do for this component
  81307. };
  81308. /**
  81309. * Disposes the component and the associated ressources
  81310. */
  81311. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  81312. // Nothing to do for this component
  81313. };
  81314. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  81315. if (this.scene._geometryBufferRenderer) {
  81316. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  81317. }
  81318. };
  81319. return GeometryBufferRendererSceneComponent;
  81320. }());
  81321. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  81322. })(BABYLON || (BABYLON = {}));
  81323. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  81324. var BABYLON;
  81325. (function (BABYLON) {
  81326. var SSAORenderingPipeline = /** @class */ (function (_super) {
  81327. __extends(SSAORenderingPipeline, _super);
  81328. /**
  81329. * @constructor
  81330. * @param {string} name - The rendering pipeline name
  81331. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81332. * @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 }
  81333. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81334. */
  81335. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  81336. var _this = _super.call(this, scene.getEngine(), name) || this;
  81337. // Members
  81338. /**
  81339. * The PassPostProcess id in the pipeline that contains the original scene color
  81340. */
  81341. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  81342. /**
  81343. * The SSAO PostProcess id in the pipeline
  81344. */
  81345. _this.SSAORenderEffect = "SSAORenderEffect";
  81346. /**
  81347. * The horizontal blur PostProcess id in the pipeline
  81348. */
  81349. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  81350. /**
  81351. * The vertical blur PostProcess id in the pipeline
  81352. */
  81353. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  81354. /**
  81355. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  81356. */
  81357. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  81358. /**
  81359. * The output strength of the SSAO post-process. Default value is 1.0.
  81360. */
  81361. _this.totalStrength = 1.0;
  81362. /**
  81363. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  81364. */
  81365. _this.radius = 0.0001;
  81366. /**
  81367. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  81368. * Must not be equal to fallOff and superior to fallOff.
  81369. * Default value is 0.975
  81370. */
  81371. _this.area = 0.0075;
  81372. /**
  81373. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  81374. * Must not be equal to area and inferior to area.
  81375. * Default value is 0.0
  81376. */
  81377. _this.fallOff = 0.000001;
  81378. /**
  81379. * The base color of the SSAO post-process
  81380. * The final result is "base + ssao" between [0, 1]
  81381. */
  81382. _this.base = 0.5;
  81383. _this._firstUpdate = true;
  81384. _this._scene = scene;
  81385. // Set up assets
  81386. _this._createRandomTexture();
  81387. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81388. var ssaoRatio = ratio.ssaoRatio || ratio;
  81389. var combineRatio = ratio.combineRatio || ratio;
  81390. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81391. _this._createSSAOPostProcess(ssaoRatio);
  81392. _this._createBlurPostProcess(ssaoRatio);
  81393. _this._createSSAOCombinePostProcess(combineRatio);
  81394. // Set up pipeline
  81395. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81396. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81397. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81398. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81399. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81400. // Finish
  81401. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81402. if (cameras)
  81403. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81404. return _this;
  81405. }
  81406. // Public Methods
  81407. /**
  81408. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81409. */
  81410. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81411. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81412. for (var i = 0; i < this._scene.cameras.length; i++) {
  81413. var camera = this._scene.cameras[i];
  81414. this._originalColorPostProcess.dispose(camera);
  81415. this._ssaoPostProcess.dispose(camera);
  81416. this._blurHPostProcess.dispose(camera);
  81417. this._blurVPostProcess.dispose(camera);
  81418. this._ssaoCombinePostProcess.dispose(camera);
  81419. }
  81420. this._randomTexture.dispose();
  81421. if (disableDepthRender)
  81422. this._scene.disableDepthRenderer();
  81423. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81424. _super.prototype.dispose.call(this);
  81425. };
  81426. // Private Methods
  81427. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  81428. var _this = this;
  81429. var size = 16;
  81430. 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);
  81431. 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);
  81432. this._blurHPostProcess.onActivateObservable.add(function () {
  81433. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  81434. _this._blurHPostProcess.kernel = size * dw;
  81435. });
  81436. this._blurVPostProcess.onActivateObservable.add(function () {
  81437. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  81438. _this._blurVPostProcess.kernel = size * dw;
  81439. });
  81440. };
  81441. /** @hidden */
  81442. SSAORenderingPipeline.prototype._rebuild = function () {
  81443. this._firstUpdate = true;
  81444. _super.prototype._rebuild.call(this);
  81445. };
  81446. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81447. var _this = this;
  81448. var numSamples = 16;
  81449. var sampleSphere = [
  81450. 0.5381, 0.1856, -0.4319,
  81451. 0.1379, 0.2486, 0.4430,
  81452. 0.3371, 0.5679, -0.0057,
  81453. -0.6999, -0.0451, -0.0019,
  81454. 0.0689, -0.1598, -0.8547,
  81455. 0.0560, 0.0069, -0.1843,
  81456. -0.0146, 0.1402, 0.0762,
  81457. 0.0100, -0.1924, -0.0344,
  81458. -0.3577, -0.5301, -0.4358,
  81459. -0.3169, 0.1063, 0.0158,
  81460. 0.0103, -0.5869, 0.0046,
  81461. -0.0897, -0.4940, 0.3287,
  81462. 0.7119, -0.0154, -0.0918,
  81463. -0.0533, 0.0596, -0.5411,
  81464. 0.0352, -0.0631, 0.5460,
  81465. -0.4776, 0.2847, -0.0271
  81466. ];
  81467. var samplesFactor = 1.0 / numSamples;
  81468. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  81469. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81470. "area", "fallOff", "base", "range", "viewport"
  81471. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81472. this._ssaoPostProcess.onApply = function (effect) {
  81473. if (_this._firstUpdate) {
  81474. effect.setArray3("sampleSphere", sampleSphere);
  81475. effect.setFloat("samplesFactor", samplesFactor);
  81476. effect.setFloat("randTextureTiles", 4.0);
  81477. }
  81478. effect.setFloat("totalStrength", _this.totalStrength);
  81479. effect.setFloat("radius", _this.radius);
  81480. effect.setFloat("area", _this.area);
  81481. effect.setFloat("fallOff", _this.fallOff);
  81482. effect.setFloat("base", _this.base);
  81483. effect.setTexture("textureSampler", _this._depthTexture);
  81484. effect.setTexture("randomSampler", _this._randomTexture);
  81485. };
  81486. };
  81487. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81488. var _this = this;
  81489. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81490. this._ssaoCombinePostProcess.onApply = function (effect) {
  81491. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  81492. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81493. };
  81494. };
  81495. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  81496. var size = 512;
  81497. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81498. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81499. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81500. var context = this._randomTexture.getContext();
  81501. var rand = function (min, max) {
  81502. return Math.random() * (max - min) + min;
  81503. };
  81504. var randVector = BABYLON.Vector3.Zero();
  81505. for (var x = 0; x < size; x++) {
  81506. for (var y = 0; y < size; y++) {
  81507. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  81508. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  81509. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  81510. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81511. context.fillRect(x, y, 1, 1);
  81512. }
  81513. }
  81514. this._randomTexture.update(false);
  81515. };
  81516. __decorate([
  81517. BABYLON.serialize()
  81518. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  81519. __decorate([
  81520. BABYLON.serialize()
  81521. ], SSAORenderingPipeline.prototype, "radius", void 0);
  81522. __decorate([
  81523. BABYLON.serialize()
  81524. ], SSAORenderingPipeline.prototype, "area", void 0);
  81525. __decorate([
  81526. BABYLON.serialize()
  81527. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  81528. __decorate([
  81529. BABYLON.serialize()
  81530. ], SSAORenderingPipeline.prototype, "base", void 0);
  81531. return SSAORenderingPipeline;
  81532. }(BABYLON.PostProcessRenderPipeline));
  81533. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  81534. })(BABYLON || (BABYLON = {}));
  81535. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  81536. var BABYLON;
  81537. (function (BABYLON) {
  81538. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  81539. __extends(SSAO2RenderingPipeline, _super);
  81540. /**
  81541. * @constructor
  81542. * @param {string} name - The rendering pipeline name
  81543. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81544. * @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 }
  81545. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81546. */
  81547. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  81548. var _this = _super.call(this, scene.getEngine(), name) || this;
  81549. // Members
  81550. /**
  81551. * The PassPostProcess id in the pipeline that contains the original scene color
  81552. */
  81553. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  81554. /**
  81555. * The SSAO PostProcess id in the pipeline
  81556. */
  81557. _this.SSAORenderEffect = "SSAORenderEffect";
  81558. /**
  81559. * The horizontal blur PostProcess id in the pipeline
  81560. */
  81561. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  81562. /**
  81563. * The vertical blur PostProcess id in the pipeline
  81564. */
  81565. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  81566. /**
  81567. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  81568. */
  81569. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  81570. /**
  81571. * The output strength of the SSAO post-process. Default value is 1.0.
  81572. */
  81573. _this.totalStrength = 1.0;
  81574. /**
  81575. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  81576. */
  81577. _this.maxZ = 100.0;
  81578. /**
  81579. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  81580. */
  81581. _this.minZAspect = 0.2;
  81582. _this._samples = 8;
  81583. _this._textureSamples = 1;
  81584. /**
  81585. * Are we using bilateral blur ?
  81586. */
  81587. _this._expensiveBlur = true;
  81588. /**
  81589. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  81590. */
  81591. _this.radius = 2.0;
  81592. /**
  81593. * The base color of the SSAO post-process
  81594. * The final result is "base + ssao" between [0, 1]
  81595. */
  81596. _this.base = 0;
  81597. _this._firstUpdate = true;
  81598. _this._bits = new Uint32Array(1);
  81599. _this._scene = scene;
  81600. _this._ratio = ratio;
  81601. if (!_this.isSupported) {
  81602. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  81603. return _this;
  81604. }
  81605. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  81606. var blurRatio = _this._ratio.blurRatio || ratio;
  81607. // Set up assets
  81608. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  81609. _this._createRandomTexture();
  81610. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  81611. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  81612. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81613. _this._originalColorPostProcess.samples = _this.textureSamples;
  81614. _this._createSSAOPostProcess(1.0);
  81615. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  81616. _this._createSSAOCombinePostProcess(blurRatio);
  81617. // Set up pipeline
  81618. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81619. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81620. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81621. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81622. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81623. // Finish
  81624. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81625. if (cameras)
  81626. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81627. return _this;
  81628. }
  81629. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  81630. get: function () {
  81631. return this._samples;
  81632. },
  81633. /**
  81634. * Number of samples used for the SSAO calculations. Default value is 8
  81635. */
  81636. set: function (n) {
  81637. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  81638. this._samples = n;
  81639. this._sampleSphere = this._generateHemisphere();
  81640. this._firstUpdate = true;
  81641. },
  81642. enumerable: true,
  81643. configurable: true
  81644. });
  81645. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  81646. get: function () {
  81647. return this._textureSamples;
  81648. },
  81649. /**
  81650. * Number of samples to use for antialiasing
  81651. */
  81652. set: function (n) {
  81653. this._textureSamples = n;
  81654. this._originalColorPostProcess.samples = n;
  81655. this._blurHPostProcess.samples = n;
  81656. this._blurVPostProcess.samples = n;
  81657. this._ssaoPostProcess.samples = n;
  81658. this._ssaoCombinePostProcess.samples = n;
  81659. },
  81660. enumerable: true,
  81661. configurable: true
  81662. });
  81663. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  81664. get: function () {
  81665. return this._expensiveBlur;
  81666. },
  81667. set: function (b) {
  81668. 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"]);
  81669. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  81670. this._expensiveBlur = b;
  81671. this._firstUpdate = true;
  81672. },
  81673. enumerable: true,
  81674. configurable: true
  81675. });
  81676. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  81677. /**
  81678. * Support test.
  81679. */
  81680. get: function () {
  81681. var engine = BABYLON.Engine.LastCreatedEngine;
  81682. if (!engine) {
  81683. return false;
  81684. }
  81685. return engine.getCaps().drawBuffersExtension;
  81686. },
  81687. enumerable: true,
  81688. configurable: true
  81689. });
  81690. // Public Methods
  81691. /**
  81692. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81693. */
  81694. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  81695. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  81696. for (var i = 0; i < this._scene.cameras.length; i++) {
  81697. var camera = this._scene.cameras[i];
  81698. this._originalColorPostProcess.dispose(camera);
  81699. this._ssaoPostProcess.dispose(camera);
  81700. this._blurHPostProcess.dispose(camera);
  81701. this._blurVPostProcess.dispose(camera);
  81702. this._ssaoCombinePostProcess.dispose(camera);
  81703. }
  81704. this._randomTexture.dispose();
  81705. if (disableGeometryBufferRenderer)
  81706. this._scene.disableGeometryBufferRenderer();
  81707. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81708. _super.prototype.dispose.call(this);
  81709. };
  81710. // Private Methods
  81711. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  81712. var _this = this;
  81713. this._samplerOffsets = [];
  81714. var expensive = this.expensiveBlur;
  81715. for (var i = -8; i < 8; i++) {
  81716. this._samplerOffsets.push(i * 2 + 0.5);
  81717. }
  81718. 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");
  81719. this._blurHPostProcess.onApply = function (effect) {
  81720. if (!_this._scene.activeCamera) {
  81721. return;
  81722. }
  81723. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  81724. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81725. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81726. effect.setFloat("radius", _this.radius);
  81727. effect.setTexture("depthSampler", _this._depthTexture);
  81728. if (_this._firstUpdate) {
  81729. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81730. }
  81731. };
  81732. 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");
  81733. this._blurVPostProcess.onApply = function (effect) {
  81734. if (!_this._scene.activeCamera) {
  81735. return;
  81736. }
  81737. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  81738. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81739. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81740. effect.setFloat("radius", _this.radius);
  81741. effect.setTexture("depthSampler", _this._depthTexture);
  81742. if (_this._firstUpdate) {
  81743. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81744. _this._firstUpdate = false;
  81745. }
  81746. };
  81747. this._blurHPostProcess.samples = this.textureSamples;
  81748. this._blurVPostProcess.samples = this.textureSamples;
  81749. };
  81750. /** @hidden */
  81751. SSAO2RenderingPipeline.prototype._rebuild = function () {
  81752. this._firstUpdate = true;
  81753. _super.prototype._rebuild.call(this);
  81754. };
  81755. //Van der Corput radical inverse
  81756. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  81757. this._bits[0] = i;
  81758. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  81759. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  81760. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  81761. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  81762. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  81763. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  81764. };
  81765. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  81766. return [i / n, this._radicalInverse_VdC(i)];
  81767. };
  81768. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  81769. var phi = v * 2.0 * Math.PI;
  81770. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  81771. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  81772. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  81773. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  81774. };
  81775. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  81776. var numSamples = this.samples;
  81777. var result = [];
  81778. var vector;
  81779. var i = 0;
  81780. while (i < numSamples) {
  81781. if (numSamples < 16) {
  81782. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  81783. }
  81784. else {
  81785. var rand = this._hammersley(i, numSamples);
  81786. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  81787. }
  81788. result.push(vector.x, vector.y, vector.z);
  81789. i++;
  81790. }
  81791. return result;
  81792. };
  81793. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81794. var _this = this;
  81795. var numSamples = this.samples;
  81796. this._sampleSphere = this._generateHemisphere();
  81797. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  81798. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81799. "base", "range", "projection", "near", "far", "texelSize",
  81800. "xViewport", "yViewport", "maxZ", "minZAspect"
  81801. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81802. this._ssaoPostProcess.onApply = function (effect) {
  81803. if (_this._firstUpdate) {
  81804. effect.setArray3("sampleSphere", _this._sampleSphere);
  81805. effect.setFloat("randTextureTiles", 32.0);
  81806. }
  81807. if (!_this._scene.activeCamera) {
  81808. return;
  81809. }
  81810. effect.setFloat("samplesFactor", 1 / _this.samples);
  81811. effect.setFloat("totalStrength", _this.totalStrength);
  81812. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  81813. effect.setFloat("radius", _this.radius);
  81814. effect.setFloat("maxZ", _this.maxZ);
  81815. effect.setFloat("minZAspect", _this.minZAspect);
  81816. effect.setFloat("base", _this.base);
  81817. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81818. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81819. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  81820. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  81821. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  81822. effect.setTexture("textureSampler", _this._depthTexture);
  81823. effect.setTexture("normalSampler", _this._normalTexture);
  81824. effect.setTexture("randomSampler", _this._randomTexture);
  81825. };
  81826. this._ssaoPostProcess.samples = this.textureSamples;
  81827. };
  81828. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81829. var _this = this;
  81830. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81831. this._ssaoCombinePostProcess.onApply = function (effect) {
  81832. var viewport = _this._scene.activeCamera.viewport;
  81833. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  81834. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81835. };
  81836. this._ssaoCombinePostProcess.samples = this.textureSamples;
  81837. };
  81838. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  81839. var size = 128;
  81840. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81841. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81842. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81843. var context = this._randomTexture.getContext();
  81844. var rand = function (min, max) {
  81845. return Math.random() * (max - min) + min;
  81846. };
  81847. var randVector = BABYLON.Vector3.Zero();
  81848. for (var x = 0; x < size; x++) {
  81849. for (var y = 0; y < size; y++) {
  81850. randVector.x = rand(0.0, 1.0);
  81851. randVector.y = rand(0.0, 1.0);
  81852. randVector.z = 0.0;
  81853. randVector.normalize();
  81854. randVector.scaleInPlace(255);
  81855. randVector.x = Math.floor(randVector.x);
  81856. randVector.y = Math.floor(randVector.y);
  81857. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81858. context.fillRect(x, y, 1, 1);
  81859. }
  81860. }
  81861. this._randomTexture.update(false);
  81862. };
  81863. /**
  81864. * Serialize the rendering pipeline (Used when exporting)
  81865. * @returns the serialized object
  81866. */
  81867. SSAO2RenderingPipeline.prototype.serialize = function () {
  81868. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81869. serializationObject.customType = "SSAO2RenderingPipeline";
  81870. return serializationObject;
  81871. };
  81872. /**
  81873. * Parse the serialized pipeline
  81874. * @param source Source pipeline.
  81875. * @param scene The scene to load the pipeline to.
  81876. * @param rootUrl The URL of the serialized pipeline.
  81877. * @returns An instantiated pipeline from the serialized object.
  81878. */
  81879. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  81880. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  81881. };
  81882. __decorate([
  81883. BABYLON.serialize()
  81884. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  81885. __decorate([
  81886. BABYLON.serialize()
  81887. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  81888. __decorate([
  81889. BABYLON.serialize()
  81890. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  81891. __decorate([
  81892. BABYLON.serialize("samples")
  81893. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  81894. __decorate([
  81895. BABYLON.serialize("textureSamples")
  81896. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  81897. __decorate([
  81898. BABYLON.serialize()
  81899. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  81900. __decorate([
  81901. BABYLON.serialize("expensiveBlur")
  81902. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  81903. __decorate([
  81904. BABYLON.serialize()
  81905. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  81906. __decorate([
  81907. BABYLON.serialize()
  81908. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  81909. return SSAO2RenderingPipeline;
  81910. }(BABYLON.PostProcessRenderPipeline));
  81911. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  81912. })(BABYLON || (BABYLON = {}));
  81913. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  81914. // BABYLON.JS Chromatic Aberration GLSL Shader
  81915. // Author: Olivier Guyot
  81916. // Separates very slightly R, G and B colors on the edges of the screen
  81917. // Inspired by Francois Tarlier & Martins Upitis
  81918. var BABYLON;
  81919. (function (BABYLON) {
  81920. var LensRenderingPipeline = /** @class */ (function (_super) {
  81921. __extends(LensRenderingPipeline, _super);
  81922. /**
  81923. * @constructor
  81924. *
  81925. * Effect parameters are as follow:
  81926. * {
  81927. * chromatic_aberration: number; // from 0 to x (1 for realism)
  81928. * edge_blur: number; // from 0 to x (1 for realism)
  81929. * distortion: number; // from 0 to x (1 for realism)
  81930. * grain_amount: number; // from 0 to 1
  81931. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  81932. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  81933. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  81934. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  81935. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  81936. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  81937. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  81938. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  81939. * }
  81940. * Note: if an effect parameter is unset, effect is disabled
  81941. *
  81942. * @param {string} name - The rendering pipeline name
  81943. * @param {object} parameters - An object containing all parameters (see above)
  81944. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81945. * @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)
  81946. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81947. */
  81948. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  81949. if (ratio === void 0) { ratio = 1.0; }
  81950. var _this = _super.call(this, scene.getEngine(), name) || this;
  81951. // Lens effects can be of the following:
  81952. // - chromatic aberration (slight shift of RGB colors)
  81953. // - blur on the edge of the lens
  81954. // - lens distortion
  81955. // - depth-of-field blur & highlights enhancing
  81956. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  81957. // - grain effect (noise or custom texture)
  81958. // Two additional texture samplers are needed:
  81959. // - depth map (for depth-of-field)
  81960. // - grain texture
  81961. /**
  81962. * The chromatic aberration PostProcess id in the pipeline
  81963. */
  81964. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  81965. /**
  81966. * The highlights enhancing PostProcess id in the pipeline
  81967. */
  81968. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  81969. /**
  81970. * The depth-of-field PostProcess id in the pipeline
  81971. */
  81972. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  81973. _this._scene = scene;
  81974. // Fetch texture samplers
  81975. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81976. if (parameters.grain_texture) {
  81977. _this._grainTexture = parameters.grain_texture;
  81978. }
  81979. else {
  81980. _this._createGrainTexture();
  81981. }
  81982. // save parameters
  81983. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  81984. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  81985. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  81986. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  81987. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  81988. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  81989. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  81990. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  81991. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  81992. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  81993. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  81994. // Create effects
  81995. _this._createChromaticAberrationPostProcess(ratio);
  81996. _this._createHighlightsPostProcess(ratio);
  81997. _this._createDepthOfFieldPostProcess(ratio / 4);
  81998. // Set up pipeline
  81999. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  82000. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  82001. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  82002. if (_this._highlightsGain === -1) {
  82003. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  82004. }
  82005. // Finish
  82006. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82007. if (cameras) {
  82008. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82009. }
  82010. return _this;
  82011. }
  82012. // public methods (self explanatory)
  82013. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  82014. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  82015. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  82016. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  82017. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  82018. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  82019. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  82020. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  82021. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  82022. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  82023. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  82024. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  82025. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  82026. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  82027. };
  82028. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  82029. this._highlightsPostProcess.updateEffect();
  82030. };
  82031. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  82032. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  82033. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  82034. this._highlightsGain = amount;
  82035. };
  82036. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  82037. if (this._highlightsGain === -1) {
  82038. this._highlightsGain = 1.0;
  82039. }
  82040. this._highlightsThreshold = amount;
  82041. };
  82042. LensRenderingPipeline.prototype.disableHighlights = function () {
  82043. this._highlightsGain = -1;
  82044. };
  82045. /**
  82046. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  82047. */
  82048. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  82049. if (disableDepthRender === void 0) { disableDepthRender = false; }
  82050. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82051. this._chromaticAberrationPostProcess = null;
  82052. this._highlightsPostProcess = null;
  82053. this._depthOfFieldPostProcess = null;
  82054. this._grainTexture.dispose();
  82055. if (disableDepthRender)
  82056. this._scene.disableDepthRenderer();
  82057. };
  82058. // colors shifting and distortion
  82059. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  82060. var _this = this;
  82061. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  82062. [], // samplers
  82063. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82064. this._chromaticAberrationPostProcess.onApply = function (effect) {
  82065. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  82066. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82067. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82068. effect.setFloat('radialIntensity', 1);
  82069. effect.setFloat2('direction', 17, 17);
  82070. effect.setFloat2('centerPosition', 0.5, 0.5);
  82071. };
  82072. };
  82073. // highlights enhancing
  82074. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  82075. var _this = this;
  82076. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  82077. [], // samplers
  82078. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  82079. this._highlightsPostProcess.onApply = function (effect) {
  82080. effect.setFloat('gain', _this._highlightsGain);
  82081. effect.setFloat('threshold', _this._highlightsThreshold);
  82082. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  82083. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82084. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82085. };
  82086. };
  82087. // colors shifting and distortion
  82088. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  82089. var _this = this;
  82090. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  82091. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  82092. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  82093. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82094. this._depthOfFieldPostProcess.onApply = function (effect) {
  82095. effect.setTexture("depthSampler", _this._depthTexture);
  82096. effect.setTexture("grainSampler", _this._grainTexture);
  82097. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  82098. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  82099. effect.setFloat('grain_amount', _this._grainAmount);
  82100. effect.setBool('blur_noise', _this._blurNoise);
  82101. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82102. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82103. effect.setFloat('distortion', _this._distortion);
  82104. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  82105. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  82106. effect.setFloat('aperture', _this._dofAperture);
  82107. effect.setFloat('darken', _this._dofDarken);
  82108. effect.setFloat('edge_blur', _this._edgeBlur);
  82109. effect.setBool('highlights', (_this._highlightsGain !== -1));
  82110. if (_this._scene.activeCamera) {
  82111. effect.setFloat('near', _this._scene.activeCamera.minZ);
  82112. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  82113. }
  82114. };
  82115. };
  82116. // creates a black and white random noise texture, 512x512
  82117. LensRenderingPipeline.prototype._createGrainTexture = function () {
  82118. var size = 512;
  82119. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82120. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82121. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82122. var context = this._grainTexture.getContext();
  82123. var rand = function (min, max) {
  82124. return Math.random() * (max - min) + min;
  82125. };
  82126. var value;
  82127. for (var x = 0; x < size; x++) {
  82128. for (var y = 0; y < size; y++) {
  82129. value = Math.floor(rand(0.42, 0.58) * 255);
  82130. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  82131. context.fillRect(x, y, 1, 1);
  82132. }
  82133. }
  82134. this._grainTexture.update(false);
  82135. };
  82136. return LensRenderingPipeline;
  82137. }(BABYLON.PostProcessRenderPipeline));
  82138. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  82139. })(BABYLON || (BABYLON = {}));
  82140. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  82141. var BABYLON;
  82142. (function (BABYLON) {
  82143. var StandardRenderingPipeline = /** @class */ (function (_super) {
  82144. __extends(StandardRenderingPipeline, _super);
  82145. /**
  82146. * @constructor
  82147. * @param {string} name - The rendering pipeline name
  82148. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82149. * @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)
  82150. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  82151. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82152. */
  82153. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  82154. if (originalPostProcess === void 0) { originalPostProcess = null; }
  82155. var _this = _super.call(this, scene.getEngine(), name) || this;
  82156. /**
  82157. * Post-process used to down scale an image x4
  82158. */
  82159. _this.downSampleX4PostProcess = null;
  82160. /**
  82161. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  82162. */
  82163. _this.brightPassPostProcess = null;
  82164. /**
  82165. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  82166. */
  82167. _this.blurHPostProcesses = [];
  82168. /**
  82169. * Post-process array storing all the vertical blur post-processes used by the pipeline
  82170. */
  82171. _this.blurVPostProcesses = [];
  82172. /**
  82173. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  82174. */
  82175. _this.textureAdderPostProcess = null;
  82176. /**
  82177. * Post-process used to create volumetric lighting effect
  82178. */
  82179. _this.volumetricLightPostProcess = null;
  82180. /**
  82181. * Post-process used to smooth the previous volumetric light post-process on the X axis
  82182. */
  82183. _this.volumetricLightSmoothXPostProcess = null;
  82184. /**
  82185. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  82186. */
  82187. _this.volumetricLightSmoothYPostProcess = null;
  82188. /**
  82189. * Post-process used to merge the volumetric light effect and the real scene color
  82190. */
  82191. _this.volumetricLightMergePostProces = null;
  82192. /**
  82193. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  82194. */
  82195. _this.volumetricLightFinalPostProcess = null;
  82196. /**
  82197. * Base post-process used to calculate the average luminance of the final image for HDR
  82198. */
  82199. _this.luminancePostProcess = null;
  82200. /**
  82201. * Post-processes used to create down sample post-processes in order to get
  82202. * the average luminance of the final image for HDR
  82203. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  82204. */
  82205. _this.luminanceDownSamplePostProcesses = [];
  82206. /**
  82207. * Post-process used to create a HDR effect (light adaptation)
  82208. */
  82209. _this.hdrPostProcess = null;
  82210. /**
  82211. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  82212. */
  82213. _this.textureAdderFinalPostProcess = null;
  82214. /**
  82215. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  82216. */
  82217. _this.lensFlareFinalPostProcess = null;
  82218. /**
  82219. * Post-process used to merge the final HDR post-process and the real scene color
  82220. */
  82221. _this.hdrFinalPostProcess = null;
  82222. /**
  82223. * Post-process used to create a lens flare effect
  82224. */
  82225. _this.lensFlarePostProcess = null;
  82226. /**
  82227. * Post-process that merges the result of the lens flare post-process and the real scene color
  82228. */
  82229. _this.lensFlareComposePostProcess = null;
  82230. /**
  82231. * Post-process used to create a motion blur effect
  82232. */
  82233. _this.motionBlurPostProcess = null;
  82234. /**
  82235. * Post-process used to create a depth of field effect
  82236. */
  82237. _this.depthOfFieldPostProcess = null;
  82238. /**
  82239. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  82240. */
  82241. _this.fxaaPostProcess = null;
  82242. // Values
  82243. /**
  82244. * Represents the brightness threshold in order to configure the illuminated surfaces
  82245. */
  82246. _this.brightThreshold = 1.0;
  82247. /**
  82248. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  82249. */
  82250. _this.blurWidth = 512.0;
  82251. /**
  82252. * Sets if the blur for highlighted surfaces must be only horizontal
  82253. */
  82254. _this.horizontalBlur = false;
  82255. /**
  82256. * Sets the overall exposure used by the pipeline
  82257. */
  82258. _this.exposure = 1.0;
  82259. /**
  82260. * Texture used typically to simulate "dirty" on camera lens
  82261. */
  82262. _this.lensTexture = null;
  82263. /**
  82264. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  82265. */
  82266. _this.volumetricLightCoefficient = 0.2;
  82267. /**
  82268. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  82269. */
  82270. _this.volumetricLightPower = 4.0;
  82271. /**
  82272. * Used the set the blur intensity to smooth the volumetric lights
  82273. */
  82274. _this.volumetricLightBlurScale = 64.0;
  82275. /**
  82276. * Light (spot or directional) used to generate the volumetric lights rays
  82277. * The source light must have a shadow generate so the pipeline can get its
  82278. * depth map
  82279. */
  82280. _this.sourceLight = null;
  82281. /**
  82282. * For eye adaptation, represents the minimum luminance the eye can see
  82283. */
  82284. _this.hdrMinimumLuminance = 1.0;
  82285. /**
  82286. * For eye adaptation, represents the decrease luminance speed
  82287. */
  82288. _this.hdrDecreaseRate = 0.5;
  82289. /**
  82290. * For eye adaptation, represents the increase luminance speed
  82291. */
  82292. _this.hdrIncreaseRate = 0.5;
  82293. /**
  82294. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  82295. */
  82296. _this.lensColorTexture = null;
  82297. /**
  82298. * The overall strengh for the lens flare effect
  82299. */
  82300. _this.lensFlareStrength = 20.0;
  82301. /**
  82302. * Dispersion coefficient for lens flare ghosts
  82303. */
  82304. _this.lensFlareGhostDispersal = 1.4;
  82305. /**
  82306. * Main lens flare halo width
  82307. */
  82308. _this.lensFlareHaloWidth = 0.7;
  82309. /**
  82310. * Based on the lens distortion effect, defines how much the lens flare result
  82311. * is distorted
  82312. */
  82313. _this.lensFlareDistortionStrength = 16.0;
  82314. /**
  82315. * Lens star texture must be used to simulate rays on the flares and is available
  82316. * in the documentation
  82317. */
  82318. _this.lensStarTexture = null;
  82319. /**
  82320. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  82321. * flare effect by taking account of the dirt texture
  82322. */
  82323. _this.lensFlareDirtTexture = null;
  82324. /**
  82325. * Represents the focal length for the depth of field effect
  82326. */
  82327. _this.depthOfFieldDistance = 10.0;
  82328. /**
  82329. * Represents the blur intensity for the blurred part of the depth of field effect
  82330. */
  82331. _this.depthOfFieldBlurWidth = 64.0;
  82332. /**
  82333. * For motion blur, defines how much the image is blurred by the movement
  82334. */
  82335. _this.motionStrength = 1.0;
  82336. /**
  82337. * List of animations for the pipeline (IAnimatable implementation)
  82338. */
  82339. _this.animations = [];
  82340. _this._currentDepthOfFieldSource = null;
  82341. _this._hdrCurrentLuminance = 1.0;
  82342. // Getters and setters
  82343. _this._bloomEnabled = false;
  82344. _this._depthOfFieldEnabled = false;
  82345. _this._vlsEnabled = false;
  82346. _this._lensFlareEnabled = false;
  82347. _this._hdrEnabled = false;
  82348. _this._motionBlurEnabled = false;
  82349. _this._fxaaEnabled = false;
  82350. _this._motionBlurSamples = 64.0;
  82351. _this._volumetricLightStepsCount = 50.0;
  82352. _this._samples = 1;
  82353. _this._cameras = cameras || [];
  82354. // Initialize
  82355. _this._scene = scene;
  82356. _this._basePostProcess = originalPostProcess;
  82357. _this._ratio = ratio;
  82358. // Misc
  82359. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82360. // Finish
  82361. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82362. _this._buildPipeline();
  82363. return _this;
  82364. }
  82365. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  82366. /**
  82367. * Specifies if the bloom pipeline is enabled
  82368. */
  82369. get: function () {
  82370. return this._bloomEnabled;
  82371. },
  82372. set: function (enabled) {
  82373. if (this._bloomEnabled === enabled) {
  82374. return;
  82375. }
  82376. this._bloomEnabled = enabled;
  82377. this._buildPipeline();
  82378. },
  82379. enumerable: true,
  82380. configurable: true
  82381. });
  82382. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  82383. /**
  82384. * Specifies if the depth of field pipeline is enabed
  82385. */
  82386. get: function () {
  82387. return this._depthOfFieldEnabled;
  82388. },
  82389. set: function (enabled) {
  82390. if (this._depthOfFieldEnabled === enabled) {
  82391. return;
  82392. }
  82393. this._depthOfFieldEnabled = enabled;
  82394. this._buildPipeline();
  82395. },
  82396. enumerable: true,
  82397. configurable: true
  82398. });
  82399. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  82400. /**
  82401. * Specifies if the lens flare pipeline is enabed
  82402. */
  82403. get: function () {
  82404. return this._lensFlareEnabled;
  82405. },
  82406. set: function (enabled) {
  82407. if (this._lensFlareEnabled === enabled) {
  82408. return;
  82409. }
  82410. this._lensFlareEnabled = enabled;
  82411. this._buildPipeline();
  82412. },
  82413. enumerable: true,
  82414. configurable: true
  82415. });
  82416. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  82417. /**
  82418. * Specifies if the HDR pipeline is enabled
  82419. */
  82420. get: function () {
  82421. return this._hdrEnabled;
  82422. },
  82423. set: function (enabled) {
  82424. if (this._hdrEnabled === enabled) {
  82425. return;
  82426. }
  82427. this._hdrEnabled = enabled;
  82428. this._buildPipeline();
  82429. },
  82430. enumerable: true,
  82431. configurable: true
  82432. });
  82433. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  82434. /**
  82435. * Specifies if the volumetric lights scattering effect is enabled
  82436. */
  82437. get: function () {
  82438. return this._vlsEnabled;
  82439. },
  82440. set: function (enabled) {
  82441. if (this._vlsEnabled === enabled) {
  82442. return;
  82443. }
  82444. if (enabled) {
  82445. var geometry = this._scene.enableGeometryBufferRenderer();
  82446. if (!geometry) {
  82447. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  82448. return;
  82449. }
  82450. }
  82451. this._vlsEnabled = enabled;
  82452. this._buildPipeline();
  82453. },
  82454. enumerable: true,
  82455. configurable: true
  82456. });
  82457. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  82458. /**
  82459. * Specifies if the motion blur effect is enabled
  82460. */
  82461. get: function () {
  82462. return this._motionBlurEnabled;
  82463. },
  82464. set: function (enabled) {
  82465. if (this._motionBlurEnabled === enabled) {
  82466. return;
  82467. }
  82468. this._motionBlurEnabled = enabled;
  82469. this._buildPipeline();
  82470. },
  82471. enumerable: true,
  82472. configurable: true
  82473. });
  82474. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  82475. /**
  82476. * Specifies if anti-aliasing is enabled
  82477. */
  82478. get: function () {
  82479. return this._fxaaEnabled;
  82480. },
  82481. set: function (enabled) {
  82482. if (this._fxaaEnabled === enabled) {
  82483. return;
  82484. }
  82485. this._fxaaEnabled = enabled;
  82486. this._buildPipeline();
  82487. },
  82488. enumerable: true,
  82489. configurable: true
  82490. });
  82491. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  82492. /**
  82493. * Specifies the number of steps used to calculate the volumetric lights
  82494. * Typically in interval [50, 200]
  82495. */
  82496. get: function () {
  82497. return this._volumetricLightStepsCount;
  82498. },
  82499. set: function (count) {
  82500. if (this.volumetricLightPostProcess) {
  82501. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  82502. }
  82503. this._volumetricLightStepsCount = count;
  82504. },
  82505. enumerable: true,
  82506. configurable: true
  82507. });
  82508. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  82509. /**
  82510. * Specifies the number of samples used for the motion blur effect
  82511. * Typically in interval [16, 64]
  82512. */
  82513. get: function () {
  82514. return this._motionBlurSamples;
  82515. },
  82516. set: function (samples) {
  82517. if (this.motionBlurPostProcess) {
  82518. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  82519. }
  82520. this._motionBlurSamples = samples;
  82521. },
  82522. enumerable: true,
  82523. configurable: true
  82524. });
  82525. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  82526. /**
  82527. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  82528. */
  82529. get: function () {
  82530. return this._samples;
  82531. },
  82532. set: function (sampleCount) {
  82533. if (this._samples === sampleCount) {
  82534. return;
  82535. }
  82536. this._samples = sampleCount;
  82537. this._buildPipeline();
  82538. },
  82539. enumerable: true,
  82540. configurable: true
  82541. });
  82542. StandardRenderingPipeline.prototype._buildPipeline = function () {
  82543. var _this = this;
  82544. var ratio = this._ratio;
  82545. var scene = this._scene;
  82546. this._disposePostProcesses();
  82547. this._reset();
  82548. // Create pass post-process
  82549. if (!this._basePostProcess) {
  82550. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  82551. this.originalPostProcess.onApply = function (effect) {
  82552. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  82553. };
  82554. }
  82555. else {
  82556. this.originalPostProcess = this._basePostProcess;
  82557. }
  82558. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  82559. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  82560. }
  82561. this._currentDepthOfFieldSource = this.originalPostProcess;
  82562. if (this._bloomEnabled) {
  82563. // Create down sample X4 post-process
  82564. this._createDownSampleX4PostProcess(scene, ratio / 2);
  82565. // Create bright pass post-process
  82566. this._createBrightPassPostProcess(scene, ratio / 2);
  82567. // Create gaussian blur post-processes (down sampling blurs)
  82568. this._createBlurPostProcesses(scene, ratio / 4, 1);
  82569. // Create texture adder post-process
  82570. this._createTextureAdderPostProcess(scene, ratio);
  82571. // Create depth-of-field source post-process
  82572. 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);
  82573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  82574. }
  82575. if (this._vlsEnabled) {
  82576. // Create volumetric light
  82577. this._createVolumetricLightPostProcess(scene, ratio);
  82578. // Create volumetric light final post-process
  82579. 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);
  82580. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  82581. }
  82582. if (this._lensFlareEnabled) {
  82583. // Create lens flare post-process
  82584. this._createLensFlarePostProcess(scene, ratio);
  82585. // Create depth-of-field source post-process post lens-flare and disable it now
  82586. 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);
  82587. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  82588. }
  82589. if (this._hdrEnabled) {
  82590. // Create luminance
  82591. this._createLuminancePostProcesses(scene, this._floatTextureType);
  82592. // Create HDR
  82593. this._createHdrPostProcess(scene, ratio);
  82594. // Create depth-of-field source post-process post hdr and disable it now
  82595. 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);
  82596. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  82597. }
  82598. if (this._depthOfFieldEnabled) {
  82599. // Create gaussian blur used by depth-of-field
  82600. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  82601. // Create depth-of-field post-process
  82602. this._createDepthOfFieldPostProcess(scene, ratio);
  82603. }
  82604. if (this._motionBlurEnabled) {
  82605. // Create motion blur post-process
  82606. this._createMotionBlurPostProcess(scene, ratio);
  82607. }
  82608. if (this._fxaaEnabled) {
  82609. // Create fxaa post-process
  82610. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82611. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  82612. }
  82613. if (this._cameras !== null) {
  82614. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  82615. }
  82616. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  82617. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  82618. }
  82619. };
  82620. // Down Sample X4 Post-Processs
  82621. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  82622. var _this = this;
  82623. var downSampleX4Offsets = new Array(32);
  82624. 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);
  82625. this.downSampleX4PostProcess.onApply = function (effect) {
  82626. var id = 0;
  82627. var width = _this.downSampleX4PostProcess.width;
  82628. var height = _this.downSampleX4PostProcess.height;
  82629. for (var i = -2; i < 2; i++) {
  82630. for (var j = -2; j < 2; j++) {
  82631. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  82632. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  82633. id += 2;
  82634. }
  82635. }
  82636. effect.setArray2("dsOffsets", downSampleX4Offsets);
  82637. };
  82638. // Add to pipeline
  82639. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  82640. };
  82641. // Brightpass Post-Process
  82642. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  82643. var _this = this;
  82644. var brightOffsets = new Array(8);
  82645. 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);
  82646. this.brightPassPostProcess.onApply = function (effect) {
  82647. var sU = (1.0 / _this.brightPassPostProcess.width);
  82648. var sV = (1.0 / _this.brightPassPostProcess.height);
  82649. brightOffsets[0] = -0.5 * sU;
  82650. brightOffsets[1] = 0.5 * sV;
  82651. brightOffsets[2] = 0.5 * sU;
  82652. brightOffsets[3] = 0.5 * sV;
  82653. brightOffsets[4] = -0.5 * sU;
  82654. brightOffsets[5] = -0.5 * sV;
  82655. brightOffsets[6] = 0.5 * sU;
  82656. brightOffsets[7] = -0.5 * sV;
  82657. effect.setArray2("dsOffsets", brightOffsets);
  82658. effect.setFloat("brightThreshold", _this.brightThreshold);
  82659. };
  82660. // Add to pipeline
  82661. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  82662. };
  82663. // Create blur H&V post-processes
  82664. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  82665. var _this = this;
  82666. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  82667. var engine = scene.getEngine();
  82668. 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);
  82669. 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);
  82670. blurX.onActivateObservable.add(function () {
  82671. var dw = blurX.width / engine.getRenderWidth();
  82672. blurX.kernel = _this[blurWidthKey] * dw;
  82673. });
  82674. blurY.onActivateObservable.add(function () {
  82675. var dw = blurY.height / engine.getRenderHeight();
  82676. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  82677. });
  82678. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  82679. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  82680. this.blurHPostProcesses.push(blurX);
  82681. this.blurVPostProcesses.push(blurY);
  82682. };
  82683. // Create texture adder post-process
  82684. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  82685. var _this = this;
  82686. 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);
  82687. this.textureAdderPostProcess.onApply = function (effect) {
  82688. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  82689. effect.setTexture("lensSampler", _this.lensTexture);
  82690. effect.setFloat("exposure", _this.exposure);
  82691. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  82692. };
  82693. // Add to pipeline
  82694. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  82695. };
  82696. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  82697. var _this = this;
  82698. var geometryRenderer = scene.enableGeometryBufferRenderer();
  82699. geometryRenderer.enablePosition = true;
  82700. var geometry = geometryRenderer.getGBuffer();
  82701. // Base post-process
  82702. 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));
  82703. var depthValues = BABYLON.Vector2.Zero();
  82704. this.volumetricLightPostProcess.onApply = function (effect) {
  82705. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  82706. var generator = _this.sourceLight.getShadowGenerator();
  82707. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  82708. effect.setTexture("positionSampler", geometry.textures[2]);
  82709. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  82710. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  82711. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  82712. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  82713. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  82714. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  82715. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  82716. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  82717. effect.setVector2("depthValues", depthValues);
  82718. }
  82719. };
  82720. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  82721. // Smooth
  82722. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  82723. // Merge
  82724. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  82725. this.volumetricLightMergePostProces.onApply = function (effect) {
  82726. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  82727. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  82728. };
  82729. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  82730. };
  82731. // Create luminance
  82732. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  82733. var _this = this;
  82734. // Create luminance
  82735. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  82736. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  82737. var offsets = [];
  82738. this.luminancePostProcess.onApply = function (effect) {
  82739. var sU = (1.0 / _this.luminancePostProcess.width);
  82740. var sV = (1.0 / _this.luminancePostProcess.height);
  82741. offsets[0] = -0.5 * sU;
  82742. offsets[1] = 0.5 * sV;
  82743. offsets[2] = 0.5 * sU;
  82744. offsets[3] = 0.5 * sV;
  82745. offsets[4] = -0.5 * sU;
  82746. offsets[5] = -0.5 * sV;
  82747. offsets[6] = 0.5 * sU;
  82748. offsets[7] = -0.5 * sV;
  82749. effect.setArray2("lumOffsets", offsets);
  82750. };
  82751. // Add to pipeline
  82752. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  82753. // Create down sample luminance
  82754. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  82755. var size = Math.pow(3, i);
  82756. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  82757. if (i === 0) {
  82758. defines += "#define FINAL_DOWN_SAMPLER";
  82759. }
  82760. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  82761. this.luminanceDownSamplePostProcesses.push(postProcess);
  82762. }
  82763. // Create callbacks and add effects
  82764. var lastLuminance = this.luminancePostProcess;
  82765. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  82766. var downSampleOffsets = new Array(18);
  82767. pp.onApply = function (effect) {
  82768. if (!lastLuminance) {
  82769. return;
  82770. }
  82771. var id = 0;
  82772. for (var x = -1; x < 2; x++) {
  82773. for (var y = -1; y < 2; y++) {
  82774. downSampleOffsets[id] = x / lastLuminance.width;
  82775. downSampleOffsets[id + 1] = y / lastLuminance.height;
  82776. id += 2;
  82777. }
  82778. }
  82779. effect.setArray2("dsOffsets", downSampleOffsets);
  82780. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  82781. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82782. lastLuminance = _this.luminancePostProcess;
  82783. }
  82784. else {
  82785. lastLuminance = pp;
  82786. }
  82787. };
  82788. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82789. pp.onAfterRender = function (effect) {
  82790. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  82791. 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);
  82792. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  82793. };
  82794. }
  82795. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  82796. });
  82797. };
  82798. // Create HDR post-process
  82799. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  82800. var _this = this;
  82801. 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);
  82802. var outputLiminance = 1;
  82803. var time = 0;
  82804. var lastTime = 0;
  82805. this.hdrPostProcess.onApply = function (effect) {
  82806. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  82807. time += scene.getEngine().getDeltaTime();
  82808. if (outputLiminance < 0) {
  82809. outputLiminance = _this._hdrCurrentLuminance;
  82810. }
  82811. else {
  82812. var dt = (lastTime - time) / 1000.0;
  82813. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  82814. outputLiminance += _this.hdrDecreaseRate * dt;
  82815. }
  82816. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  82817. outputLiminance -= _this.hdrIncreaseRate * dt;
  82818. }
  82819. else {
  82820. outputLiminance = _this._hdrCurrentLuminance;
  82821. }
  82822. }
  82823. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  82824. effect.setFloat("averageLuminance", outputLiminance);
  82825. lastTime = time;
  82826. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  82827. };
  82828. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  82829. };
  82830. // Create lens flare post-process
  82831. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  82832. var _this = this;
  82833. 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);
  82834. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  82835. this._createBlurPostProcesses(scene, ratio / 4, 2);
  82836. 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);
  82837. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  82838. var resolution = new BABYLON.Vector2(0, 0);
  82839. // Lens flare
  82840. this.lensFlarePostProcess.onApply = function (effect) {
  82841. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  82842. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  82843. effect.setFloat("strength", _this.lensFlareStrength);
  82844. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  82845. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  82846. // Shift
  82847. resolution.x = _this.lensFlarePostProcess.width;
  82848. resolution.y = _this.lensFlarePostProcess.height;
  82849. effect.setVector2("resolution", resolution);
  82850. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  82851. };
  82852. // Compose
  82853. 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);
  82854. 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);
  82855. this.lensFlareComposePostProcess.onApply = function (effect) {
  82856. if (!_this._scene.activeCamera) {
  82857. return;
  82858. }
  82859. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82860. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  82861. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  82862. // Lens start rotation matrix
  82863. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  82864. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  82865. 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));
  82866. camRot *= 4.0;
  82867. 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);
  82868. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  82869. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  82870. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  82871. };
  82872. };
  82873. // Create depth-of-field post-process
  82874. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  82875. var _this = this;
  82876. 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);
  82877. this.depthOfFieldPostProcess.onApply = function (effect) {
  82878. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82879. effect.setTexture("depthSampler", _this._getDepthTexture());
  82880. effect.setFloat("distance", _this.depthOfFieldDistance);
  82881. };
  82882. // Add to pipeline
  82883. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  82884. };
  82885. // Create motion blur post-process
  82886. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  82887. var _this = this;
  82888. 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);
  82889. var motionScale = 0;
  82890. var prevViewProjection = BABYLON.Matrix.Identity();
  82891. var invViewProjection = BABYLON.Matrix.Identity();
  82892. var viewProjection = BABYLON.Matrix.Identity();
  82893. var screenSize = BABYLON.Vector2.Zero();
  82894. this.motionBlurPostProcess.onApply = function (effect) {
  82895. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  82896. viewProjection.invertToRef(invViewProjection);
  82897. effect.setMatrix("inverseViewProjection", invViewProjection);
  82898. effect.setMatrix("prevViewProjection", prevViewProjection);
  82899. prevViewProjection = viewProjection;
  82900. screenSize.x = _this.motionBlurPostProcess.width;
  82901. screenSize.y = _this.motionBlurPostProcess.height;
  82902. effect.setVector2("screenSize", screenSize);
  82903. motionScale = scene.getEngine().getFps() / 60.0;
  82904. effect.setFloat("motionScale", motionScale);
  82905. effect.setFloat("motionStrength", _this.motionStrength);
  82906. effect.setTexture("depthSampler", _this._getDepthTexture());
  82907. };
  82908. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  82909. };
  82910. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  82911. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  82912. var renderer = this._scene.enableGeometryBufferRenderer();
  82913. return renderer.getGBuffer().textures[0];
  82914. }
  82915. return this._scene.enableDepthRenderer().getDepthMap();
  82916. };
  82917. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  82918. for (var i = 0; i < this._cameras.length; i++) {
  82919. var camera = this._cameras[i];
  82920. if (this.originalPostProcess) {
  82921. this.originalPostProcess.dispose(camera);
  82922. }
  82923. if (this.downSampleX4PostProcess) {
  82924. this.downSampleX4PostProcess.dispose(camera);
  82925. }
  82926. if (this.brightPassPostProcess) {
  82927. this.brightPassPostProcess.dispose(camera);
  82928. }
  82929. if (this.textureAdderPostProcess) {
  82930. this.textureAdderPostProcess.dispose(camera);
  82931. }
  82932. if (this.textureAdderFinalPostProcess) {
  82933. this.textureAdderFinalPostProcess.dispose(camera);
  82934. }
  82935. if (this.volumetricLightPostProcess) {
  82936. this.volumetricLightPostProcess.dispose(camera);
  82937. }
  82938. if (this.volumetricLightSmoothXPostProcess) {
  82939. this.volumetricLightSmoothXPostProcess.dispose(camera);
  82940. }
  82941. if (this.volumetricLightSmoothYPostProcess) {
  82942. this.volumetricLightSmoothYPostProcess.dispose(camera);
  82943. }
  82944. if (this.volumetricLightMergePostProces) {
  82945. this.volumetricLightMergePostProces.dispose(camera);
  82946. }
  82947. if (this.volumetricLightFinalPostProcess) {
  82948. this.volumetricLightFinalPostProcess.dispose(camera);
  82949. }
  82950. if (this.lensFlarePostProcess) {
  82951. this.lensFlarePostProcess.dispose(camera);
  82952. }
  82953. if (this.lensFlareComposePostProcess) {
  82954. this.lensFlareComposePostProcess.dispose(camera);
  82955. }
  82956. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  82957. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  82958. }
  82959. if (this.luminancePostProcess) {
  82960. this.luminancePostProcess.dispose(camera);
  82961. }
  82962. if (this.hdrPostProcess) {
  82963. this.hdrPostProcess.dispose(camera);
  82964. }
  82965. if (this.hdrFinalPostProcess) {
  82966. this.hdrFinalPostProcess.dispose(camera);
  82967. }
  82968. if (this.depthOfFieldPostProcess) {
  82969. this.depthOfFieldPostProcess.dispose(camera);
  82970. }
  82971. if (this.motionBlurPostProcess) {
  82972. this.motionBlurPostProcess.dispose(camera);
  82973. }
  82974. if (this.fxaaPostProcess) {
  82975. this.fxaaPostProcess.dispose(camera);
  82976. }
  82977. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  82978. this.blurHPostProcesses[j].dispose(camera);
  82979. }
  82980. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  82981. this.blurVPostProcesses[j].dispose(camera);
  82982. }
  82983. }
  82984. this.originalPostProcess = null;
  82985. this.downSampleX4PostProcess = null;
  82986. this.brightPassPostProcess = null;
  82987. this.textureAdderPostProcess = null;
  82988. this.textureAdderFinalPostProcess = null;
  82989. this.volumetricLightPostProcess = null;
  82990. this.volumetricLightSmoothXPostProcess = null;
  82991. this.volumetricLightSmoothYPostProcess = null;
  82992. this.volumetricLightMergePostProces = null;
  82993. this.volumetricLightFinalPostProcess = null;
  82994. this.lensFlarePostProcess = null;
  82995. this.lensFlareComposePostProcess = null;
  82996. this.luminancePostProcess = null;
  82997. this.hdrPostProcess = null;
  82998. this.hdrFinalPostProcess = null;
  82999. this.depthOfFieldPostProcess = null;
  83000. this.motionBlurPostProcess = null;
  83001. this.fxaaPostProcess = null;
  83002. this.luminanceDownSamplePostProcesses = [];
  83003. this.blurHPostProcesses = [];
  83004. this.blurVPostProcesses = [];
  83005. };
  83006. /**
  83007. * Dispose of the pipeline and stop all post processes
  83008. */
  83009. StandardRenderingPipeline.prototype.dispose = function () {
  83010. this._disposePostProcesses();
  83011. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83012. _super.prototype.dispose.call(this);
  83013. };
  83014. /**
  83015. * Serialize the rendering pipeline (Used when exporting)
  83016. * @returns the serialized object
  83017. */
  83018. StandardRenderingPipeline.prototype.serialize = function () {
  83019. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83020. if (this.sourceLight) {
  83021. serializationObject.sourceLightId = this.sourceLight.id;
  83022. }
  83023. serializationObject.customType = "StandardRenderingPipeline";
  83024. return serializationObject;
  83025. };
  83026. /**
  83027. * Parse the serialized pipeline
  83028. * @param source Source pipeline.
  83029. * @param scene The scene to load the pipeline to.
  83030. * @param rootUrl The URL of the serialized pipeline.
  83031. * @returns An instantiated pipeline from the serialized object.
  83032. */
  83033. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  83034. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  83035. if (source.sourceLightId) {
  83036. p.sourceLight = scene.getLightByID(source.sourceLightId);
  83037. }
  83038. return p;
  83039. };
  83040. // Luminance steps
  83041. StandardRenderingPipeline.LuminanceSteps = 6;
  83042. __decorate([
  83043. BABYLON.serialize()
  83044. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  83045. __decorate([
  83046. BABYLON.serialize()
  83047. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  83048. __decorate([
  83049. BABYLON.serialize()
  83050. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  83051. __decorate([
  83052. BABYLON.serialize()
  83053. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  83054. __decorate([
  83055. BABYLON.serializeAsTexture("lensTexture")
  83056. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  83057. __decorate([
  83058. BABYLON.serialize()
  83059. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  83060. __decorate([
  83061. BABYLON.serialize()
  83062. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  83063. __decorate([
  83064. BABYLON.serialize()
  83065. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  83066. __decorate([
  83067. BABYLON.serialize()
  83068. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  83069. __decorate([
  83070. BABYLON.serialize()
  83071. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  83072. __decorate([
  83073. BABYLON.serialize()
  83074. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  83075. __decorate([
  83076. BABYLON.serializeAsTexture("lensColorTexture")
  83077. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  83078. __decorate([
  83079. BABYLON.serialize()
  83080. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  83081. __decorate([
  83082. BABYLON.serialize()
  83083. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  83084. __decorate([
  83085. BABYLON.serialize()
  83086. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  83087. __decorate([
  83088. BABYLON.serialize()
  83089. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  83090. __decorate([
  83091. BABYLON.serializeAsTexture("lensStarTexture")
  83092. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  83093. __decorate([
  83094. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  83095. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  83096. __decorate([
  83097. BABYLON.serialize()
  83098. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  83099. __decorate([
  83100. BABYLON.serialize()
  83101. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  83102. __decorate([
  83103. BABYLON.serialize()
  83104. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  83105. __decorate([
  83106. BABYLON.serialize()
  83107. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  83108. __decorate([
  83109. BABYLON.serialize()
  83110. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  83111. __decorate([
  83112. BABYLON.serialize()
  83113. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  83114. __decorate([
  83115. BABYLON.serialize()
  83116. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  83117. __decorate([
  83118. BABYLON.serialize()
  83119. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  83120. __decorate([
  83121. BABYLON.serialize()
  83122. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  83123. __decorate([
  83124. BABYLON.serialize()
  83125. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  83126. __decorate([
  83127. BABYLON.serialize()
  83128. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  83129. __decorate([
  83130. BABYLON.serialize()
  83131. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  83132. __decorate([
  83133. BABYLON.serialize()
  83134. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  83135. __decorate([
  83136. BABYLON.serialize()
  83137. ], StandardRenderingPipeline.prototype, "samples", null);
  83138. return StandardRenderingPipeline;
  83139. }(BABYLON.PostProcessRenderPipeline));
  83140. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  83141. })(BABYLON || (BABYLON = {}));
  83142. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  83143. var BABYLON;
  83144. (function (BABYLON) {
  83145. var FxaaPostProcess = /** @class */ (function (_super) {
  83146. __extends(FxaaPostProcess, _super);
  83147. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83148. if (camera === void 0) { camera = null; }
  83149. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83150. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  83151. var defines = _this._getDefines();
  83152. _this.updateEffect(defines);
  83153. _this.onApplyObservable.add(function (effect) {
  83154. var texelSize = _this.texelSize;
  83155. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  83156. });
  83157. return _this;
  83158. }
  83159. FxaaPostProcess.prototype._getDefines = function () {
  83160. var engine = this.getEngine();
  83161. if (!engine) {
  83162. return null;
  83163. }
  83164. var glInfo = engine.getGlInfo();
  83165. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  83166. return "#define MALI 1\n";
  83167. }
  83168. return null;
  83169. };
  83170. return FxaaPostProcess;
  83171. }(BABYLON.PostProcess));
  83172. BABYLON.FxaaPostProcess = FxaaPostProcess;
  83173. })(BABYLON || (BABYLON = {}));
  83174. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  83175. var BABYLON;
  83176. (function (BABYLON) {
  83177. /**
  83178. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  83179. */
  83180. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  83181. __extends(ChromaticAberrationPostProcess, _super);
  83182. /**
  83183. * Creates a new instance ChromaticAberrationPostProcess
  83184. * @param name The name of the effect.
  83185. * @param screenWidth The width of the screen to apply the effect on.
  83186. * @param screenHeight The height of the screen to apply the effect on.
  83187. * @param options The required width/height ratio to downsize to before computing the render pass.
  83188. * @param camera The camera to apply the render pass to.
  83189. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83190. * @param engine The engine which the post process will be applied. (default: current engine)
  83191. * @param reusable If the post process can be reused on the same frame. (default: false)
  83192. * @param textureType Type of textures used when performing the post process. (default: 0)
  83193. * @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)
  83194. */
  83195. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83196. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83197. if (blockCompilation === void 0) { blockCompilation = false; }
  83198. 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;
  83199. /**
  83200. * The amount of seperation of rgb channels (default: 30)
  83201. */
  83202. _this.aberrationAmount = 30;
  83203. /**
  83204. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  83205. */
  83206. _this.radialIntensity = 0;
  83207. /**
  83208. * 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))
  83209. */
  83210. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  83211. /**
  83212. * 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))
  83213. */
  83214. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  83215. _this.onApplyObservable.add(function (effect) {
  83216. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  83217. effect.setFloat('screen_width', screenWidth);
  83218. effect.setFloat('screen_height', screenHeight);
  83219. effect.setFloat('radialIntensity', _this.radialIntensity);
  83220. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  83221. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  83222. });
  83223. return _this;
  83224. }
  83225. return ChromaticAberrationPostProcess;
  83226. }(BABYLON.PostProcess));
  83227. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  83228. })(BABYLON || (BABYLON = {}));
  83229. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  83230. var BABYLON;
  83231. (function (BABYLON) {
  83232. /**
  83233. * The GrainPostProcess adds noise to the image at mid luminance levels
  83234. */
  83235. var GrainPostProcess = /** @class */ (function (_super) {
  83236. __extends(GrainPostProcess, _super);
  83237. /**
  83238. * Creates a new instance of @see GrainPostProcess
  83239. * @param name The name of the effect.
  83240. * @param options The required width/height ratio to downsize to before computing the render pass.
  83241. * @param camera The camera to apply the render pass to.
  83242. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83243. * @param engine The engine which the post process will be applied. (default: current engine)
  83244. * @param reusable If the post process can be reused on the same frame. (default: false)
  83245. * @param textureType Type of textures used when performing the post process. (default: 0)
  83246. * @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)
  83247. */
  83248. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83249. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83250. if (blockCompilation === void 0) { blockCompilation = false; }
  83251. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83252. /**
  83253. * The intensity of the grain added (default: 30)
  83254. */
  83255. _this.intensity = 30;
  83256. /**
  83257. * If the grain should be randomized on every frame
  83258. */
  83259. _this.animated = false;
  83260. _this.onApplyObservable.add(function (effect) {
  83261. effect.setFloat('intensity', _this.intensity);
  83262. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  83263. });
  83264. return _this;
  83265. }
  83266. return GrainPostProcess;
  83267. }(BABYLON.PostProcess));
  83268. BABYLON.GrainPostProcess = GrainPostProcess;
  83269. })(BABYLON || (BABYLON = {}));
  83270. //# sourceMappingURL=babylon.grainPostProcess.js.map
  83271. var BABYLON;
  83272. (function (BABYLON) {
  83273. /**
  83274. * The SharpenPostProcess applies a sharpen kernel to every pixel
  83275. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83276. */
  83277. var SharpenPostProcess = /** @class */ (function (_super) {
  83278. __extends(SharpenPostProcess, _super);
  83279. /**
  83280. * Creates a new instance ConvolutionPostProcess
  83281. * @param name The name of the effect.
  83282. * @param options The required width/height ratio to downsize to before computing the render pass.
  83283. * @param camera The camera to apply the render pass to.
  83284. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83285. * @param engine The engine which the post process will be applied. (default: current engine)
  83286. * @param reusable If the post process can be reused on the same frame. (default: false)
  83287. * @param textureType Type of textures used when performing the post process. (default: 0)
  83288. * @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)
  83289. */
  83290. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83291. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83292. if (blockCompilation === void 0) { blockCompilation = false; }
  83293. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83294. /**
  83295. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  83296. */
  83297. _this.colorAmount = 1.0;
  83298. /**
  83299. * How much sharpness should be applied (default: 0.3)
  83300. */
  83301. _this.edgeAmount = 0.3;
  83302. _this.onApply = function (effect) {
  83303. effect.setFloat2("screenSize", _this.width, _this.height);
  83304. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  83305. };
  83306. return _this;
  83307. }
  83308. return SharpenPostProcess;
  83309. }(BABYLON.PostProcess));
  83310. BABYLON.SharpenPostProcess = SharpenPostProcess;
  83311. })(BABYLON || (BABYLON = {}));
  83312. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  83313. var BABYLON;
  83314. (function (BABYLON) {
  83315. /**
  83316. * The Blur Post Process which blurs an image based on a kernel and direction.
  83317. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  83318. */
  83319. var BlurPostProcess = /** @class */ (function (_super) {
  83320. __extends(BlurPostProcess, _super);
  83321. /**
  83322. * Creates a new instance BlurPostProcess
  83323. * @param name The name of the effect.
  83324. * @param direction The direction in which to blur the image.
  83325. * @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.
  83326. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  83327. * @param camera The camera to apply the render pass to.
  83328. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83329. * @param engine The engine which the post process will be applied. (default: current engine)
  83330. * @param reusable If the post process can be reused on the same frame. (default: false)
  83331. * @param textureType Type of textures used when performing the post process. (default: 0)
  83332. * @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)
  83333. */
  83334. function BlurPostProcess(name,
  83335. /** The direction in which to blur the image. */
  83336. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  83337. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83338. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83339. if (defines === void 0) { defines = ""; }
  83340. if (blockCompilation === void 0) { blockCompilation = false; }
  83341. 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;
  83342. _this.direction = direction;
  83343. _this.blockCompilation = blockCompilation;
  83344. _this._packedFloat = false;
  83345. _this._staticDefines = "";
  83346. _this._staticDefines = defines;
  83347. _this.onApplyObservable.add(function (effect) {
  83348. if (_this._outputTexture) {
  83349. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  83350. }
  83351. else {
  83352. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  83353. }
  83354. });
  83355. _this.kernel = kernel;
  83356. return _this;
  83357. }
  83358. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  83359. /**
  83360. * Gets the length in pixels of the blur sample region
  83361. */
  83362. get: function () {
  83363. return this._idealKernel;
  83364. },
  83365. /**
  83366. * Sets the length in pixels of the blur sample region
  83367. */
  83368. set: function (v) {
  83369. if (this._idealKernel === v) {
  83370. return;
  83371. }
  83372. v = Math.max(v, 1);
  83373. this._idealKernel = v;
  83374. this._kernel = this._nearestBestKernel(v);
  83375. if (!this.blockCompilation) {
  83376. this._updateParameters();
  83377. }
  83378. },
  83379. enumerable: true,
  83380. configurable: true
  83381. });
  83382. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  83383. /**
  83384. * Gets wether or not the blur is unpacking/repacking floats
  83385. */
  83386. get: function () {
  83387. return this._packedFloat;
  83388. },
  83389. /**
  83390. * Sets wether or not the blur needs to unpack/repack floats
  83391. */
  83392. set: function (v) {
  83393. if (this._packedFloat === v) {
  83394. return;
  83395. }
  83396. this._packedFloat = v;
  83397. if (!this.blockCompilation) {
  83398. this._updateParameters();
  83399. }
  83400. },
  83401. enumerable: true,
  83402. configurable: true
  83403. });
  83404. /**
  83405. * Updates the effect with the current post process compile time values and recompiles the shader.
  83406. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83407. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83408. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83409. * @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
  83410. * @param onCompiled Called when the shader has been compiled.
  83411. * @param onError Called if there is an error when compiling a shader.
  83412. */
  83413. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83414. if (defines === void 0) { defines = null; }
  83415. if (uniforms === void 0) { uniforms = null; }
  83416. if (samplers === void 0) { samplers = null; }
  83417. this._updateParameters(onCompiled, onError);
  83418. };
  83419. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  83420. // Generate sampling offsets and weights
  83421. var N = this._kernel;
  83422. var centerIndex = (N - 1) / 2;
  83423. // Generate Gaussian sampling weights over kernel
  83424. var offsets = [];
  83425. var weights = [];
  83426. var totalWeight = 0;
  83427. for (var i = 0; i < N; i++) {
  83428. var u = i / (N - 1);
  83429. var w = this._gaussianWeight(u * 2.0 - 1);
  83430. offsets[i] = (i - centerIndex);
  83431. weights[i] = w;
  83432. totalWeight += w;
  83433. }
  83434. // Normalize weights
  83435. for (var i = 0; i < weights.length; i++) {
  83436. weights[i] /= totalWeight;
  83437. }
  83438. // Optimize: combine samples to take advantage of hardware linear sampling
  83439. // Walk from left to center, combining pairs (symmetrically)
  83440. var linearSamplingWeights = [];
  83441. var linearSamplingOffsets = [];
  83442. var linearSamplingMap = [];
  83443. for (var i = 0; i <= centerIndex; i += 2) {
  83444. var j = Math.min(i + 1, Math.floor(centerIndex));
  83445. var singleCenterSample = i === j;
  83446. if (singleCenterSample) {
  83447. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83448. }
  83449. else {
  83450. var sharedCell = j === centerIndex;
  83451. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  83452. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  83453. if (offsetLinear === 0) {
  83454. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83455. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  83456. }
  83457. else {
  83458. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  83459. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  83460. }
  83461. }
  83462. }
  83463. for (var i = 0; i < linearSamplingMap.length; i++) {
  83464. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  83465. linearSamplingWeights[i] = linearSamplingMap[i].w;
  83466. }
  83467. // Replace with optimized
  83468. offsets = linearSamplingOffsets;
  83469. weights = linearSamplingWeights;
  83470. // Generate shaders
  83471. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  83472. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  83473. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  83474. var defines = "";
  83475. defines += this._staticDefines;
  83476. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  83477. if (this._staticDefines.indexOf("DOF") != -1) {
  83478. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  83479. varyingCount--;
  83480. }
  83481. for (var i = 0; i < varyingCount; i++) {
  83482. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  83483. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  83484. }
  83485. var depCount = 0;
  83486. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  83487. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  83488. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  83489. depCount++;
  83490. }
  83491. if (this.packedFloat) {
  83492. defines += "#define PACKEDFLOAT 1";
  83493. }
  83494. this.blockCompilation = false;
  83495. _super.prototype.updateEffect.call(this, defines, null, null, {
  83496. varyingCount: varyingCount,
  83497. depCount: depCount
  83498. }, onCompiled, onError);
  83499. };
  83500. /**
  83501. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  83502. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  83503. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  83504. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  83505. * The gaps between physical kernels are compensated for in the weighting of the samples
  83506. * @param idealKernel Ideal blur kernel.
  83507. * @return Nearest best kernel.
  83508. */
  83509. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  83510. var v = Math.round(idealKernel);
  83511. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  83512. var k = _a[_i];
  83513. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  83514. return Math.max(k, 3);
  83515. }
  83516. }
  83517. return Math.max(v, 3);
  83518. };
  83519. /**
  83520. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  83521. * @param x The point on the Gaussian distribution to sample.
  83522. * @return the value of the Gaussian function at x.
  83523. */
  83524. BlurPostProcess.prototype._gaussianWeight = function (x) {
  83525. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  83526. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  83527. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  83528. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  83529. // truncated at around 1.3% of peak strength.
  83530. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  83531. var sigma = (1 / 3);
  83532. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  83533. var exponent = -((x * x) / (2.0 * sigma * sigma));
  83534. var weight = (1.0 / denominator) * Math.exp(exponent);
  83535. return weight;
  83536. };
  83537. /**
  83538. * Generates a string that can be used as a floating point number in GLSL.
  83539. * @param x Value to print.
  83540. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  83541. * @return GLSL float string.
  83542. */
  83543. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  83544. if (decimalFigures === void 0) { decimalFigures = 8; }
  83545. return x.toFixed(decimalFigures).replace(/0+$/, '');
  83546. };
  83547. return BlurPostProcess;
  83548. }(BABYLON.PostProcess));
  83549. BABYLON.BlurPostProcess = BlurPostProcess;
  83550. })(BABYLON || (BABYLON = {}));
  83551. //# sourceMappingURL=babylon.blurPostProcess.js.map
  83552. var BABYLON;
  83553. (function (BABYLON) {
  83554. /**
  83555. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  83556. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  83557. * based on samples that have a large difference in distance than the center pixel.
  83558. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83559. */
  83560. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  83561. __extends(DepthOfFieldBlurPostProcess, _super);
  83562. /**
  83563. * Creates a new instance CircleOfConfusionPostProcess
  83564. * @param name The name of the effect.
  83565. * @param scene The scene the effect belongs to.
  83566. * @param direction The direction the blur should be applied.
  83567. * @param kernel The size of the kernel used to blur.
  83568. * @param options The required width/height ratio to downsize to before computing the render pass.
  83569. * @param camera The camera to apply the render pass to.
  83570. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  83571. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  83572. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83573. * @param engine The engine which the post process will be applied. (default: current engine)
  83574. * @param reusable If the post process can be reused on the same frame. (default: false)
  83575. * @param textureType Type of textures used when performing the post process. (default: 0)
  83576. * @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)
  83577. */
  83578. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  83579. if (imageToBlur === void 0) { imageToBlur = null; }
  83580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83581. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83582. if (blockCompilation === void 0) { blockCompilation = false; }
  83583. 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;
  83584. _this.direction = direction;
  83585. _this.onApplyObservable.add(function (effect) {
  83586. if (imageToBlur != null) {
  83587. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  83588. }
  83589. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83590. if (scene.activeCamera) {
  83591. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  83592. }
  83593. });
  83594. return _this;
  83595. }
  83596. return DepthOfFieldBlurPostProcess;
  83597. }(BABYLON.BlurPostProcess));
  83598. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  83599. })(BABYLON || (BABYLON = {}));
  83600. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  83601. var BABYLON;
  83602. (function (BABYLON) {
  83603. /**
  83604. * Options to be set when merging outputs from the default pipeline.
  83605. */
  83606. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  83607. function DepthOfFieldMergePostProcessOptions() {
  83608. }
  83609. return DepthOfFieldMergePostProcessOptions;
  83610. }());
  83611. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  83612. /**
  83613. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83614. */
  83615. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  83616. __extends(DepthOfFieldMergePostProcess, _super);
  83617. /**
  83618. * Creates a new instance of DepthOfFieldMergePostProcess
  83619. * @param name The name of the effect.
  83620. * @param originalFromInput Post process which's input will be used for the merge.
  83621. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  83622. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  83623. * @param options The required width/height ratio to downsize to before computing the render pass.
  83624. * @param camera The camera to apply the render pass to.
  83625. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83626. * @param engine The engine which the post process will be applied. (default: current engine)
  83627. * @param reusable If the post process can be reused on the same frame. (default: false)
  83628. * @param textureType Type of textures used when performing the post process. (default: 0)
  83629. * @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)
  83630. */
  83631. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83632. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83633. if (blockCompilation === void 0) { blockCompilation = false; }
  83634. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83635. _this.blurSteps = blurSteps;
  83636. _this.onApplyObservable.add(function (effect) {
  83637. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83638. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83639. blurSteps.forEach(function (step, index) {
  83640. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  83641. });
  83642. });
  83643. if (!blockCompilation) {
  83644. _this.updateEffect();
  83645. }
  83646. return _this;
  83647. }
  83648. /**
  83649. * Updates the effect with the current post process compile time values and recompiles the shader.
  83650. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83651. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83652. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83653. * @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
  83654. * @param onCompiled Called when the shader has been compiled.
  83655. * @param onError Called if there is an error when compiling a shader.
  83656. */
  83657. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83658. if (defines === void 0) { defines = null; }
  83659. if (uniforms === void 0) { uniforms = null; }
  83660. if (samplers === void 0) { samplers = null; }
  83661. if (!defines) {
  83662. defines = "";
  83663. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  83664. }
  83665. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  83666. };
  83667. return DepthOfFieldMergePostProcess;
  83668. }(BABYLON.PostProcess));
  83669. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  83670. })(BABYLON || (BABYLON = {}));
  83671. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  83672. var BABYLON;
  83673. (function (BABYLON) {
  83674. /**
  83675. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  83676. */
  83677. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  83678. __extends(CircleOfConfusionPostProcess, _super);
  83679. /**
  83680. * Creates a new instance CircleOfConfusionPostProcess
  83681. * @param name The name of the effect.
  83682. * @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.
  83683. * @param options The required width/height ratio to downsize to before computing the render pass.
  83684. * @param camera The camera to apply the render pass to.
  83685. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83686. * @param engine The engine which the post process will be applied. (default: current engine)
  83687. * @param reusable If the post process can be reused on the same frame. (default: false)
  83688. * @param textureType Type of textures used when performing the post process. (default: 0)
  83689. * @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)
  83690. */
  83691. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83692. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83693. if (blockCompilation === void 0) { blockCompilation = false; }
  83694. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83695. /**
  83696. * 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.
  83697. */
  83698. _this.lensSize = 50;
  83699. /**
  83700. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83701. */
  83702. _this.fStop = 1.4;
  83703. /**
  83704. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83705. */
  83706. _this.focusDistance = 2000;
  83707. /**
  83708. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  83709. */
  83710. _this.focalLength = 50;
  83711. _this._depthTexture = null;
  83712. _this._depthTexture = depthTexture;
  83713. _this.onApplyObservable.add(function (effect) {
  83714. if (!_this._depthTexture) {
  83715. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  83716. return;
  83717. }
  83718. effect.setTexture("depthSampler", _this._depthTexture);
  83719. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  83720. var aperture = _this.lensSize / _this.fStop;
  83721. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  83722. effect.setFloat('focusDistance', _this.focusDistance);
  83723. effect.setFloat('cocPrecalculation', cocPrecalculation);
  83724. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  83725. });
  83726. return _this;
  83727. }
  83728. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  83729. /**
  83730. * 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.
  83731. */
  83732. set: function (value) {
  83733. this._depthTexture = value;
  83734. },
  83735. enumerable: true,
  83736. configurable: true
  83737. });
  83738. return CircleOfConfusionPostProcess;
  83739. }(BABYLON.PostProcess));
  83740. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  83741. })(BABYLON || (BABYLON = {}));
  83742. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  83743. var BABYLON;
  83744. (function (BABYLON) {
  83745. /**
  83746. * Specifies the level of max blur that should be applied when using the depth of field effect
  83747. */
  83748. var DepthOfFieldEffectBlurLevel;
  83749. (function (DepthOfFieldEffectBlurLevel) {
  83750. /**
  83751. * Subtle blur
  83752. */
  83753. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  83754. /**
  83755. * Medium blur
  83756. */
  83757. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  83758. /**
  83759. * Large blur
  83760. */
  83761. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  83762. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  83763. ;
  83764. /**
  83765. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  83766. */
  83767. var DepthOfFieldEffect = /** @class */ (function (_super) {
  83768. __extends(DepthOfFieldEffect, _super);
  83769. /**
  83770. * Creates a new instance DepthOfFieldEffect
  83771. * @param scene The scene the effect belongs to.
  83772. * @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.
  83773. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83774. * @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)
  83775. */
  83776. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  83777. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  83778. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83779. if (blockCompilation === void 0) { blockCompilation = false; }
  83780. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  83781. return _this._effects;
  83782. }, true) || this;
  83783. /**
  83784. * @hidden Internal post processes in depth of field effect
  83785. */
  83786. _this._effects = [];
  83787. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  83788. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83789. // 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)
  83790. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  83791. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83792. _this._depthOfFieldBlurY = [];
  83793. _this._depthOfFieldBlurX = [];
  83794. var blurCount = 1;
  83795. var kernelSize = 15;
  83796. switch (blurLevel) {
  83797. case DepthOfFieldEffectBlurLevel.High: {
  83798. blurCount = 3;
  83799. kernelSize = 51;
  83800. break;
  83801. }
  83802. case DepthOfFieldEffectBlurLevel.Medium: {
  83803. blurCount = 2;
  83804. kernelSize = 31;
  83805. break;
  83806. }
  83807. default: {
  83808. kernelSize = 15;
  83809. blurCount = 1;
  83810. break;
  83811. }
  83812. }
  83813. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  83814. var ratio = 1.0;
  83815. for (var i = 0; i < blurCount; i++) {
  83816. 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);
  83817. blurY.autoClear = false;
  83818. ratio = 0.75 / Math.pow(2, i);
  83819. 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);
  83820. blurX.autoClear = false;
  83821. _this._depthOfFieldBlurY.push(blurY);
  83822. _this._depthOfFieldBlurX.push(blurX);
  83823. }
  83824. // Set all post processes on the effect.
  83825. _this._effects = [_this._circleOfConfusion];
  83826. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  83827. _this._effects.push(_this._depthOfFieldBlurY[i]);
  83828. _this._effects.push(_this._depthOfFieldBlurX[i]);
  83829. }
  83830. // Merge blurred images with original image based on circleOfConfusion
  83831. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83832. _this._dofMerge.autoClear = false;
  83833. _this._effects.push(_this._dofMerge);
  83834. return _this;
  83835. }
  83836. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  83837. get: function () {
  83838. return this._circleOfConfusion.focalLength;
  83839. },
  83840. /**
  83841. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  83842. */
  83843. set: function (value) {
  83844. this._circleOfConfusion.focalLength = value;
  83845. },
  83846. enumerable: true,
  83847. configurable: true
  83848. });
  83849. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  83850. get: function () {
  83851. return this._circleOfConfusion.fStop;
  83852. },
  83853. /**
  83854. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83855. */
  83856. set: function (value) {
  83857. this._circleOfConfusion.fStop = value;
  83858. },
  83859. enumerable: true,
  83860. configurable: true
  83861. });
  83862. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  83863. get: function () {
  83864. return this._circleOfConfusion.focusDistance;
  83865. },
  83866. /**
  83867. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83868. */
  83869. set: function (value) {
  83870. this._circleOfConfusion.focusDistance = value;
  83871. },
  83872. enumerable: true,
  83873. configurable: true
  83874. });
  83875. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  83876. get: function () {
  83877. return this._circleOfConfusion.lensSize;
  83878. },
  83879. /**
  83880. * 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.
  83881. */
  83882. set: function (value) {
  83883. this._circleOfConfusion.lensSize = value;
  83884. },
  83885. enumerable: true,
  83886. configurable: true
  83887. });
  83888. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  83889. /**
  83890. * 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.
  83891. */
  83892. set: function (value) {
  83893. this._circleOfConfusion.depthTexture = value;
  83894. },
  83895. enumerable: true,
  83896. configurable: true
  83897. });
  83898. /**
  83899. * Disposes each of the internal effects for a given camera.
  83900. * @param camera The camera to dispose the effect on.
  83901. */
  83902. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  83903. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83904. this._effects[effectIndex].dispose(camera);
  83905. }
  83906. };
  83907. /**
  83908. * @hidden Internal
  83909. */
  83910. DepthOfFieldEffect.prototype._updateEffects = function () {
  83911. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83912. this._effects[effectIndex].updateEffect();
  83913. }
  83914. };
  83915. /**
  83916. * Internal
  83917. * @returns if all the contained post processes are ready.
  83918. * @hidden
  83919. */
  83920. DepthOfFieldEffect.prototype._isReady = function () {
  83921. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83922. if (!this._effects[effectIndex].isReady()) {
  83923. return false;
  83924. }
  83925. }
  83926. return true;
  83927. };
  83928. return DepthOfFieldEffect;
  83929. }(BABYLON.PostProcessRenderEffect));
  83930. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  83931. })(BABYLON || (BABYLON = {}));
  83932. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  83933. var BABYLON;
  83934. (function (BABYLON) {
  83935. /**
  83936. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83937. */
  83938. var BloomMergePostProcess = /** @class */ (function (_super) {
  83939. __extends(BloomMergePostProcess, _super);
  83940. /**
  83941. * Creates a new instance of @see BloomMergePostProcess
  83942. * @param name The name of the effect.
  83943. * @param originalFromInput Post process which's input will be used for the merge.
  83944. * @param blurred Blurred highlights post process which's output will be used.
  83945. * @param weight Weight of the bloom to be added to the original input.
  83946. * @param options The required width/height ratio to downsize to before computing the render pass.
  83947. * @param camera The camera to apply the render pass to.
  83948. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83949. * @param engine The engine which the post process will be applied. (default: current engine)
  83950. * @param reusable If the post process can be reused on the same frame. (default: false)
  83951. * @param textureType Type of textures used when performing the post process. (default: 0)
  83952. * @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)
  83953. */
  83954. function BloomMergePostProcess(name, originalFromInput, blurred,
  83955. /** Weight of the bloom to be added to the original input. */
  83956. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83957. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83958. if (blockCompilation === void 0) { blockCompilation = false; }
  83959. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83960. _this.weight = weight;
  83961. _this.onApplyObservable.add(function (effect) {
  83962. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83963. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  83964. effect.setFloat("bloomWeight", _this.weight);
  83965. });
  83966. if (!blockCompilation) {
  83967. _this.updateEffect();
  83968. }
  83969. return _this;
  83970. }
  83971. return BloomMergePostProcess;
  83972. }(BABYLON.PostProcess));
  83973. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  83974. })(BABYLON || (BABYLON = {}));
  83975. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  83976. var BABYLON;
  83977. (function (BABYLON) {
  83978. /**
  83979. * 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.
  83980. */
  83981. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  83982. __extends(ExtractHighlightsPostProcess, _super);
  83983. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83984. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83985. if (blockCompilation === void 0) { blockCompilation = false; }
  83986. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83987. /**
  83988. * The luminance threshold, pixels below this value will be set to black.
  83989. */
  83990. _this.threshold = 0.9;
  83991. /** @hidden */
  83992. _this._exposure = 1;
  83993. /**
  83994. * Post process which has the input texture to be used when performing highlight extraction
  83995. * @hidden
  83996. */
  83997. _this._inputPostProcess = null;
  83998. _this.onApplyObservable.add(function (effect) {
  83999. if (_this._inputPostProcess) {
  84000. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  84001. }
  84002. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  84003. effect.setFloat('exposure', _this._exposure);
  84004. });
  84005. return _this;
  84006. }
  84007. return ExtractHighlightsPostProcess;
  84008. }(BABYLON.PostProcess));
  84009. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  84010. })(BABYLON || (BABYLON = {}));
  84011. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  84012. var BABYLON;
  84013. (function (BABYLON) {
  84014. /**
  84015. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  84016. */
  84017. var BloomEffect = /** @class */ (function (_super) {
  84018. __extends(BloomEffect, _super);
  84019. /**
  84020. * Creates a new instance of @see BloomEffect
  84021. * @param scene The scene the effect belongs to.
  84022. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  84023. * @param bloomKernel The size of the kernel to be used when applying the blur.
  84024. * @param bloomWeight The the strength of bloom.
  84025. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  84026. * @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)
  84027. */
  84028. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  84029. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  84030. if (blockCompilation === void 0) { blockCompilation = false; }
  84031. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  84032. return _this._effects;
  84033. }, true) || this;
  84034. _this.bloomScale = bloomScale;
  84035. /**
  84036. * @hidden Internal
  84037. */
  84038. _this._effects = [];
  84039. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84040. _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);
  84041. _this._blurX.alwaysForcePOT = true;
  84042. _this._blurX.autoClear = false;
  84043. _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);
  84044. _this._blurY.alwaysForcePOT = true;
  84045. _this._blurY.autoClear = false;
  84046. _this.kernel = bloomKernel;
  84047. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  84048. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84049. _this._merge.autoClear = false;
  84050. _this._effects.push(_this._merge);
  84051. return _this;
  84052. }
  84053. Object.defineProperty(BloomEffect.prototype, "threshold", {
  84054. /**
  84055. * The luminance threshold to find bright areas of the image to bloom.
  84056. */
  84057. get: function () {
  84058. return this._downscale.threshold;
  84059. },
  84060. set: function (value) {
  84061. this._downscale.threshold = value;
  84062. },
  84063. enumerable: true,
  84064. configurable: true
  84065. });
  84066. Object.defineProperty(BloomEffect.prototype, "weight", {
  84067. /**
  84068. * The strength of the bloom.
  84069. */
  84070. get: function () {
  84071. return this._merge.weight;
  84072. },
  84073. set: function (value) {
  84074. this._merge.weight = value;
  84075. },
  84076. enumerable: true,
  84077. configurable: true
  84078. });
  84079. Object.defineProperty(BloomEffect.prototype, "kernel", {
  84080. /**
  84081. * Specifies the size of the bloom blur kernel, relative to the final output size
  84082. */
  84083. get: function () {
  84084. return this._blurX.kernel / this.bloomScale;
  84085. },
  84086. set: function (value) {
  84087. this._blurX.kernel = value * this.bloomScale;
  84088. this._blurY.kernel = value * this.bloomScale;
  84089. },
  84090. enumerable: true,
  84091. configurable: true
  84092. });
  84093. /**
  84094. * Disposes each of the internal effects for a given camera.
  84095. * @param camera The camera to dispose the effect on.
  84096. */
  84097. BloomEffect.prototype.disposeEffects = function (camera) {
  84098. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84099. this._effects[effectIndex].dispose(camera);
  84100. }
  84101. };
  84102. /**
  84103. * @hidden Internal
  84104. */
  84105. BloomEffect.prototype._updateEffects = function () {
  84106. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84107. this._effects[effectIndex].updateEffect();
  84108. }
  84109. };
  84110. /**
  84111. * Internal
  84112. * @returns if all the contained post processes are ready.
  84113. * @hidden
  84114. */
  84115. BloomEffect.prototype._isReady = function () {
  84116. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84117. if (!this._effects[effectIndex].isReady()) {
  84118. return false;
  84119. }
  84120. }
  84121. return true;
  84122. };
  84123. return BloomEffect;
  84124. }(BABYLON.PostProcessRenderEffect));
  84125. BABYLON.BloomEffect = BloomEffect;
  84126. })(BABYLON || (BABYLON = {}));
  84127. //# sourceMappingURL=babylon.bloomEffect.js.map
  84128. var BABYLON;
  84129. (function (BABYLON) {
  84130. /**
  84131. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  84132. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  84133. */
  84134. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  84135. __extends(DefaultRenderingPipeline, _super);
  84136. /**
  84137. * @constructor
  84138. * @param {string} name - The rendering pipeline name (default: "")
  84139. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  84140. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  84141. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  84142. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  84143. */
  84144. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  84145. if (name === void 0) { name = ""; }
  84146. if (hdr === void 0) { hdr = true; }
  84147. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  84148. if (automaticBuild === void 0) { automaticBuild = true; }
  84149. var _this = _super.call(this, scene.getEngine(), name) || this;
  84150. _this._camerasToBeAttached = [];
  84151. /**
  84152. * ID of the sharpen post process,
  84153. */
  84154. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  84155. /**
  84156. * ID of the image processing post process;
  84157. */
  84158. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  84159. /**
  84160. * ID of the Fast Approximate Anti-Aliasing post process;
  84161. */
  84162. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  84163. /**
  84164. * ID of the chromatic aberration post process,
  84165. */
  84166. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  84167. /**
  84168. * ID of the grain post process
  84169. */
  84170. _this.GrainPostProcessId = "GrainPostProcessEffect";
  84171. /**
  84172. * Glow post process which adds a glow to emmisive areas of the image
  84173. */
  84174. _this._glowLayer = null;
  84175. /**
  84176. * Animations which can be used to tweak settings over a period of time
  84177. */
  84178. _this.animations = [];
  84179. _this._imageProcessingConfigurationObserver = null;
  84180. // Values
  84181. _this._sharpenEnabled = false;
  84182. _this._bloomEnabled = false;
  84183. _this._depthOfFieldEnabled = false;
  84184. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  84185. _this._fxaaEnabled = false;
  84186. _this._imageProcessingEnabled = true;
  84187. _this._bloomScale = 0.5;
  84188. _this._chromaticAberrationEnabled = false;
  84189. _this._grainEnabled = false;
  84190. _this._buildAllowed = true;
  84191. _this._resizeObserver = null;
  84192. _this._hardwareScaleLevel = 1.0;
  84193. _this._bloomKernel = 64;
  84194. /**
  84195. * Specifies the weight of the bloom in the final rendering
  84196. */
  84197. _this._bloomWeight = 0.15;
  84198. /**
  84199. * Specifies the luma threshold for the area that will be blurred by the bloom
  84200. */
  84201. _this._bloomThreshold = 0.9;
  84202. _this._samples = 1;
  84203. _this._hasCleared = false;
  84204. _this._prevPostProcess = null;
  84205. _this._prevPrevPostProcess = null;
  84206. _this._depthOfFieldSceneObserver = null;
  84207. _this._cameras = cameras || scene.cameras;
  84208. _this._cameras = _this._cameras.slice();
  84209. _this._camerasToBeAttached = _this._cameras.slice();
  84210. _this._buildAllowed = automaticBuild;
  84211. // Initialize
  84212. _this._scene = scene;
  84213. var caps = _this._scene.getEngine().getCaps();
  84214. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  84215. // Misc
  84216. if (_this._hdr) {
  84217. if (caps.textureHalfFloatRender) {
  84218. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84219. }
  84220. else if (caps.textureFloatRender) {
  84221. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84222. }
  84223. }
  84224. else {
  84225. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84226. }
  84227. // Attach
  84228. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84229. var engine = _this._scene.getEngine();
  84230. // Create post processes before hand so they can be modified before enabled.
  84231. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  84232. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  84233. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  84234. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  84235. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  84236. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  84237. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  84238. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  84239. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  84240. _this._resizeObserver = engine.onResizeObservable.add(function () {
  84241. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  84242. _this.bloomKernel = _this.bloomKernel;
  84243. });
  84244. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  84245. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  84246. });
  84247. _this._buildPipeline();
  84248. return _this;
  84249. }
  84250. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  84251. get: function () {
  84252. return this._sharpenEnabled;
  84253. },
  84254. /**
  84255. * Enable or disable the sharpen process from the pipeline
  84256. */
  84257. set: function (enabled) {
  84258. if (this._sharpenEnabled === enabled) {
  84259. return;
  84260. }
  84261. this._sharpenEnabled = enabled;
  84262. this._buildPipeline();
  84263. },
  84264. enumerable: true,
  84265. configurable: true
  84266. });
  84267. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  84268. /**
  84269. * Specifies the size of the bloom blur kernel, relative to the final output size
  84270. */
  84271. get: function () {
  84272. return this._bloomKernel;
  84273. },
  84274. set: function (value) {
  84275. this._bloomKernel = value;
  84276. this.bloom.kernel = value / this._hardwareScaleLevel;
  84277. },
  84278. enumerable: true,
  84279. configurable: true
  84280. });
  84281. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  84282. get: function () {
  84283. return this._bloomWeight;
  84284. },
  84285. /**
  84286. * The strength of the bloom.
  84287. */
  84288. set: function (value) {
  84289. if (this._bloomWeight === value) {
  84290. return;
  84291. }
  84292. this.bloom.weight = value;
  84293. this._bloomWeight = value;
  84294. },
  84295. enumerable: true,
  84296. configurable: true
  84297. });
  84298. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  84299. get: function () {
  84300. return this._bloomThreshold;
  84301. },
  84302. /**
  84303. * The strength of the bloom.
  84304. */
  84305. set: function (value) {
  84306. if (this._bloomThreshold === value) {
  84307. return;
  84308. }
  84309. this.bloom.threshold = value;
  84310. this._bloomThreshold = value;
  84311. },
  84312. enumerable: true,
  84313. configurable: true
  84314. });
  84315. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  84316. get: function () {
  84317. return this._bloomScale;
  84318. },
  84319. /**
  84320. * The scale of the bloom, lower value will provide better performance.
  84321. */
  84322. set: function (value) {
  84323. if (this._bloomScale === value) {
  84324. return;
  84325. }
  84326. this._bloomScale = value;
  84327. // recreate bloom and dispose old as this setting is not dynamic
  84328. this._rebuildBloom();
  84329. this._buildPipeline();
  84330. },
  84331. enumerable: true,
  84332. configurable: true
  84333. });
  84334. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  84335. get: function () {
  84336. return this._bloomEnabled;
  84337. },
  84338. /**
  84339. * Enable or disable the bloom from the pipeline
  84340. */
  84341. set: function (enabled) {
  84342. if (this._bloomEnabled === enabled) {
  84343. return;
  84344. }
  84345. this._bloomEnabled = enabled;
  84346. this._buildPipeline();
  84347. },
  84348. enumerable: true,
  84349. configurable: true
  84350. });
  84351. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  84352. // recreate bloom and dispose old as this setting is not dynamic
  84353. var oldBloom = this.bloom;
  84354. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  84355. this.bloom.threshold = oldBloom.threshold;
  84356. for (var i = 0; i < this._cameras.length; i++) {
  84357. oldBloom.disposeEffects(this._cameras[i]);
  84358. }
  84359. };
  84360. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  84361. /**
  84362. * If the depth of field is enabled.
  84363. */
  84364. get: function () {
  84365. return this._depthOfFieldEnabled;
  84366. },
  84367. set: function (enabled) {
  84368. if (this._depthOfFieldEnabled === enabled) {
  84369. return;
  84370. }
  84371. this._depthOfFieldEnabled = enabled;
  84372. this._buildPipeline();
  84373. },
  84374. enumerable: true,
  84375. configurable: true
  84376. });
  84377. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  84378. /**
  84379. * Blur level of the depth of field effect. (Higher blur will effect performance)
  84380. */
  84381. get: function () {
  84382. return this._depthOfFieldBlurLevel;
  84383. },
  84384. set: function (value) {
  84385. if (this._depthOfFieldBlurLevel === value) {
  84386. return;
  84387. }
  84388. this._depthOfFieldBlurLevel = value;
  84389. // recreate dof and dispose old as this setting is not dynamic
  84390. var oldDof = this.depthOfField;
  84391. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  84392. this.depthOfField.focalLength = oldDof.focalLength;
  84393. this.depthOfField.focusDistance = oldDof.focusDistance;
  84394. this.depthOfField.fStop = oldDof.fStop;
  84395. this.depthOfField.lensSize = oldDof.lensSize;
  84396. for (var i = 0; i < this._cameras.length; i++) {
  84397. oldDof.disposeEffects(this._cameras[i]);
  84398. }
  84399. this._buildPipeline();
  84400. },
  84401. enumerable: true,
  84402. configurable: true
  84403. });
  84404. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  84405. get: function () {
  84406. return this._fxaaEnabled;
  84407. },
  84408. /**
  84409. * If the anti aliasing is enabled.
  84410. */
  84411. set: function (enabled) {
  84412. if (this._fxaaEnabled === enabled) {
  84413. return;
  84414. }
  84415. this._fxaaEnabled = enabled;
  84416. this._buildPipeline();
  84417. },
  84418. enumerable: true,
  84419. configurable: true
  84420. });
  84421. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  84422. get: function () {
  84423. return this._samples;
  84424. },
  84425. /**
  84426. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84427. */
  84428. set: function (sampleCount) {
  84429. if (this._samples === sampleCount) {
  84430. return;
  84431. }
  84432. this._samples = sampleCount;
  84433. this._buildPipeline();
  84434. },
  84435. enumerable: true,
  84436. configurable: true
  84437. });
  84438. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  84439. get: function () {
  84440. return this._imageProcessingEnabled;
  84441. },
  84442. /**
  84443. * If image processing is enabled.
  84444. */
  84445. set: function (enabled) {
  84446. if (this._imageProcessingEnabled === enabled) {
  84447. return;
  84448. }
  84449. this._imageProcessingEnabled = enabled;
  84450. this._buildPipeline();
  84451. },
  84452. enumerable: true,
  84453. configurable: true
  84454. });
  84455. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  84456. get: function () {
  84457. return this._glowLayer == null;
  84458. },
  84459. /**
  84460. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  84461. */
  84462. set: function (enabled) {
  84463. if (enabled && !this._glowLayer) {
  84464. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  84465. }
  84466. else if (!enabled && this._glowLayer) {
  84467. this._glowLayer.dispose();
  84468. this._glowLayer = null;
  84469. }
  84470. },
  84471. enumerable: true,
  84472. configurable: true
  84473. });
  84474. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  84475. get: function () {
  84476. return this._chromaticAberrationEnabled;
  84477. },
  84478. /**
  84479. * Enable or disable the chromaticAberration process from the pipeline
  84480. */
  84481. set: function (enabled) {
  84482. if (this._chromaticAberrationEnabled === enabled) {
  84483. return;
  84484. }
  84485. this._chromaticAberrationEnabled = enabled;
  84486. this._buildPipeline();
  84487. },
  84488. enumerable: true,
  84489. configurable: true
  84490. });
  84491. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  84492. get: function () {
  84493. return this._grainEnabled;
  84494. },
  84495. /**
  84496. * Enable or disable the grain process from the pipeline
  84497. */
  84498. set: function (enabled) {
  84499. if (this._grainEnabled === enabled) {
  84500. return;
  84501. }
  84502. this._grainEnabled = enabled;
  84503. this._buildPipeline();
  84504. },
  84505. enumerable: true,
  84506. configurable: true
  84507. });
  84508. /**
  84509. * Force the compilation of the entire pipeline.
  84510. */
  84511. DefaultRenderingPipeline.prototype.prepare = function () {
  84512. var previousState = this._buildAllowed;
  84513. this._buildAllowed = true;
  84514. this._buildPipeline();
  84515. this._buildAllowed = previousState;
  84516. };
  84517. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  84518. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  84519. if (this._hasCleared) {
  84520. postProcess.autoClear = false;
  84521. }
  84522. else {
  84523. postProcess.autoClear = true;
  84524. this._scene.autoClear = false;
  84525. this._hasCleared = true;
  84526. }
  84527. if (!skipTextureSharing) {
  84528. if (this._prevPrevPostProcess) {
  84529. postProcess.shareOutputWith(this._prevPrevPostProcess);
  84530. }
  84531. else {
  84532. postProcess.useOwnOutput();
  84533. }
  84534. if (this._prevPostProcess) {
  84535. this._prevPrevPostProcess = this._prevPostProcess;
  84536. }
  84537. this._prevPostProcess = postProcess;
  84538. }
  84539. };
  84540. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  84541. var _this = this;
  84542. if (!this._buildAllowed) {
  84543. return;
  84544. }
  84545. this._scene.autoClear = true;
  84546. var engine = this._scene.getEngine();
  84547. this._disposePostProcesses();
  84548. if (this._cameras !== null) {
  84549. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84550. // get back cameras to be used to reattach pipeline
  84551. this._cameras = this._camerasToBeAttached.slice();
  84552. }
  84553. this._reset();
  84554. this._prevPostProcess = null;
  84555. this._prevPrevPostProcess = null;
  84556. this._hasCleared = false;
  84557. if (this.depthOfFieldEnabled) {
  84558. // Multi camera suport
  84559. if (this._cameras.length > 1) {
  84560. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  84561. var camera = _a[_i];
  84562. var depthRenderer = this._scene.enableDepthRenderer(camera);
  84563. depthRenderer.useOnlyInActiveCamera = true;
  84564. }
  84565. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  84566. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  84567. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  84568. }
  84569. });
  84570. }
  84571. else {
  84572. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84573. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  84574. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  84575. }
  84576. if (!this.depthOfField._isReady()) {
  84577. this.depthOfField._updateEffects();
  84578. }
  84579. this.addEffect(this.depthOfField);
  84580. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  84581. }
  84582. else {
  84583. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84584. }
  84585. if (this.bloomEnabled) {
  84586. if (!this.bloom._isReady()) {
  84587. this.bloom._updateEffects();
  84588. }
  84589. this.addEffect(this.bloom);
  84590. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  84591. }
  84592. if (this._imageProcessingEnabled) {
  84593. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84594. if (this._hdr) {
  84595. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  84596. this._setAutoClearAndTextureSharing(this.imageProcessing);
  84597. }
  84598. else {
  84599. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  84600. }
  84601. }
  84602. if (this.sharpenEnabled) {
  84603. if (!this.sharpen.isReady()) {
  84604. this.sharpen.updateEffect();
  84605. }
  84606. this.addEffect(this._sharpenEffect);
  84607. this._setAutoClearAndTextureSharing(this.sharpen);
  84608. }
  84609. if (this.grainEnabled) {
  84610. if (!this.grain.isReady()) {
  84611. this.grain.updateEffect();
  84612. }
  84613. this.addEffect(this._grainEffect);
  84614. this._setAutoClearAndTextureSharing(this.grain);
  84615. }
  84616. if (this.chromaticAberrationEnabled) {
  84617. if (!this.chromaticAberration.isReady()) {
  84618. this.chromaticAberration.updateEffect();
  84619. }
  84620. this.addEffect(this._chromaticAberrationEffect);
  84621. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  84622. }
  84623. if (this.fxaaEnabled) {
  84624. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84625. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  84626. this._setAutoClearAndTextureSharing(this.fxaa, true);
  84627. }
  84628. if (this._cameras !== null) {
  84629. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  84630. }
  84631. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  84632. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  84633. }
  84634. };
  84635. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  84636. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  84637. for (var i = 0; i < this._cameras.length; i++) {
  84638. var camera = this._cameras[i];
  84639. if (this.imageProcessing) {
  84640. this.imageProcessing.dispose(camera);
  84641. }
  84642. if (this.fxaa) {
  84643. this.fxaa.dispose(camera);
  84644. }
  84645. // These are created in the constructor and should not be disposed on every pipeline change
  84646. if (disposeNonRecreated) {
  84647. if (this.sharpen) {
  84648. this.sharpen.dispose(camera);
  84649. }
  84650. if (this.depthOfField) {
  84651. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84652. this.depthOfField.disposeEffects(camera);
  84653. }
  84654. if (this.bloom) {
  84655. this.bloom.disposeEffects(camera);
  84656. }
  84657. if (this.chromaticAberration) {
  84658. this.chromaticAberration.dispose(camera);
  84659. }
  84660. if (this.grain) {
  84661. this.grain.dispose(camera);
  84662. }
  84663. if (this._glowLayer) {
  84664. this._glowLayer.dispose();
  84665. }
  84666. }
  84667. }
  84668. this.imageProcessing = null;
  84669. this.fxaa = null;
  84670. if (disposeNonRecreated) {
  84671. this.sharpen = null;
  84672. this._sharpenEffect = null;
  84673. this.depthOfField = null;
  84674. this.bloom = null;
  84675. this.chromaticAberration = null;
  84676. this._chromaticAberrationEffect = null;
  84677. this.grain = null;
  84678. this._grainEffect = null;
  84679. this._glowLayer = null;
  84680. }
  84681. };
  84682. /**
  84683. * Adds a camera to the pipeline
  84684. * @param camera the camera to be added
  84685. */
  84686. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  84687. this._camerasToBeAttached.push(camera);
  84688. this._buildPipeline();
  84689. };
  84690. /**
  84691. * Removes a camera from the pipeline
  84692. * @param camera the camera to remove
  84693. */
  84694. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  84695. var index = this._camerasToBeAttached.indexOf(camera);
  84696. this._camerasToBeAttached.splice(index, 1);
  84697. this._buildPipeline();
  84698. };
  84699. /**
  84700. * Dispose of the pipeline and stop all post processes
  84701. */
  84702. DefaultRenderingPipeline.prototype.dispose = function () {
  84703. this._disposePostProcesses(true);
  84704. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84705. this._scene.autoClear = true;
  84706. if (this._resizeObserver) {
  84707. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  84708. this._resizeObserver = null;
  84709. }
  84710. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  84711. _super.prototype.dispose.call(this);
  84712. };
  84713. /**
  84714. * Serialize the rendering pipeline (Used when exporting)
  84715. * @returns the serialized object
  84716. */
  84717. DefaultRenderingPipeline.prototype.serialize = function () {
  84718. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84719. serializationObject.customType = "DefaultRenderingPipeline";
  84720. return serializationObject;
  84721. };
  84722. /**
  84723. * Parse the serialized pipeline
  84724. * @param source Source pipeline.
  84725. * @param scene The scene to load the pipeline to.
  84726. * @param rootUrl The URL of the serialized pipeline.
  84727. * @returns An instantiated pipeline from the serialized object.
  84728. */
  84729. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  84730. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  84731. };
  84732. __decorate([
  84733. BABYLON.serialize()
  84734. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  84735. __decorate([
  84736. BABYLON.serialize()
  84737. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  84738. __decorate([
  84739. BABYLON.serialize()
  84740. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  84741. __decorate([
  84742. BABYLON.serialize()
  84743. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  84744. __decorate([
  84745. BABYLON.serialize()
  84746. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  84747. __decorate([
  84748. BABYLON.serialize()
  84749. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  84750. __decorate([
  84751. BABYLON.serialize()
  84752. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  84753. __decorate([
  84754. BABYLON.serialize()
  84755. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  84756. __decorate([
  84757. BABYLON.serialize()
  84758. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  84759. __decorate([
  84760. BABYLON.serialize()
  84761. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  84762. __decorate([
  84763. BABYLON.serialize()
  84764. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  84765. __decorate([
  84766. BABYLON.serialize()
  84767. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  84768. __decorate([
  84769. BABYLON.serialize()
  84770. ], DefaultRenderingPipeline.prototype, "samples", null);
  84771. __decorate([
  84772. BABYLON.serialize()
  84773. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  84774. __decorate([
  84775. BABYLON.serialize()
  84776. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  84777. __decorate([
  84778. BABYLON.serialize()
  84779. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  84780. __decorate([
  84781. BABYLON.serialize()
  84782. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  84783. return DefaultRenderingPipeline;
  84784. }(BABYLON.PostProcessRenderPipeline));
  84785. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  84786. })(BABYLON || (BABYLON = {}));
  84787. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  84788. var BABYLON;
  84789. (function (BABYLON) {
  84790. /**
  84791. * @hidden
  84792. */
  84793. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  84794. __extends(ImageProcessingConfigurationDefines, _super);
  84795. function ImageProcessingConfigurationDefines() {
  84796. var _this = _super.call(this) || this;
  84797. _this.IMAGEPROCESSING = false;
  84798. _this.VIGNETTE = false;
  84799. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  84800. _this.VIGNETTEBLENDMODEOPAQUE = false;
  84801. _this.TONEMAPPING = false;
  84802. _this.TONEMAPPING_ACES = false;
  84803. _this.CONTRAST = false;
  84804. _this.COLORCURVES = false;
  84805. _this.COLORGRADING = false;
  84806. _this.COLORGRADING3D = false;
  84807. _this.SAMPLER3DGREENDEPTH = false;
  84808. _this.SAMPLER3DBGRMAP = false;
  84809. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  84810. _this.EXPOSURE = false;
  84811. _this.rebuild();
  84812. return _this;
  84813. }
  84814. return ImageProcessingConfigurationDefines;
  84815. }(BABYLON.MaterialDefines));
  84816. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  84817. /**
  84818. * This groups together the common properties used for image processing either in direct forward pass
  84819. * or through post processing effect depending on the use of the image processing pipeline in your scene
  84820. * or not.
  84821. */
  84822. var ImageProcessingConfiguration = /** @class */ (function () {
  84823. function ImageProcessingConfiguration() {
  84824. /**
  84825. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  84826. */
  84827. this.colorCurves = new BABYLON.ColorCurves();
  84828. this._colorCurvesEnabled = false;
  84829. this._colorGradingEnabled = false;
  84830. this._colorGradingWithGreenDepth = true;
  84831. this._colorGradingBGR = true;
  84832. /** @hidden */
  84833. this._exposure = 1.0;
  84834. this._toneMappingEnabled = false;
  84835. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  84836. this._contrast = 1.0;
  84837. /**
  84838. * Vignette stretch size.
  84839. */
  84840. this.vignetteStretch = 0;
  84841. /**
  84842. * Vignette centre X Offset.
  84843. */
  84844. this.vignetteCentreX = 0;
  84845. /**
  84846. * Vignette centre Y Offset.
  84847. */
  84848. this.vignetteCentreY = 0;
  84849. /**
  84850. * Vignette weight or intensity of the vignette effect.
  84851. */
  84852. this.vignetteWeight = 1.5;
  84853. /**
  84854. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84855. * if vignetteEnabled is set to true.
  84856. */
  84857. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  84858. /**
  84859. * Camera field of view used by the Vignette effect.
  84860. */
  84861. this.vignetteCameraFov = 0.5;
  84862. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  84863. this._vignetteEnabled = false;
  84864. this._applyByPostProcess = false;
  84865. this._isEnabled = true;
  84866. /**
  84867. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  84868. */
  84869. this.onUpdateParameters = new BABYLON.Observable();
  84870. }
  84871. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  84872. /**
  84873. * Gets wether the color curves effect is enabled.
  84874. */
  84875. get: function () {
  84876. return this._colorCurvesEnabled;
  84877. },
  84878. /**
  84879. * Sets wether the color curves effect is enabled.
  84880. */
  84881. set: function (value) {
  84882. if (this._colorCurvesEnabled === value) {
  84883. return;
  84884. }
  84885. this._colorCurvesEnabled = value;
  84886. this._updateParameters();
  84887. },
  84888. enumerable: true,
  84889. configurable: true
  84890. });
  84891. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  84892. /**
  84893. * Gets wether the color grading effect is enabled.
  84894. */
  84895. get: function () {
  84896. return this._colorGradingEnabled;
  84897. },
  84898. /**
  84899. * Sets wether the color grading effect is enabled.
  84900. */
  84901. set: function (value) {
  84902. if (this._colorGradingEnabled === value) {
  84903. return;
  84904. }
  84905. this._colorGradingEnabled = value;
  84906. this._updateParameters();
  84907. },
  84908. enumerable: true,
  84909. configurable: true
  84910. });
  84911. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  84912. /**
  84913. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  84914. */
  84915. get: function () {
  84916. return this._colorGradingWithGreenDepth;
  84917. },
  84918. /**
  84919. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  84920. */
  84921. set: function (value) {
  84922. if (this._colorGradingWithGreenDepth === value) {
  84923. return;
  84924. }
  84925. this._colorGradingWithGreenDepth = value;
  84926. this._updateParameters();
  84927. },
  84928. enumerable: true,
  84929. configurable: true
  84930. });
  84931. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  84932. /**
  84933. * Gets wether the color grading texture contains BGR values.
  84934. */
  84935. get: function () {
  84936. return this._colorGradingBGR;
  84937. },
  84938. /**
  84939. * Sets wether the color grading texture contains BGR values.
  84940. */
  84941. set: function (value) {
  84942. if (this._colorGradingBGR === value) {
  84943. return;
  84944. }
  84945. this._colorGradingBGR = value;
  84946. this._updateParameters();
  84947. },
  84948. enumerable: true,
  84949. configurable: true
  84950. });
  84951. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  84952. /**
  84953. * Gets the Exposure used in the effect.
  84954. */
  84955. get: function () {
  84956. return this._exposure;
  84957. },
  84958. /**
  84959. * Sets the Exposure used in the effect.
  84960. */
  84961. set: function (value) {
  84962. if (this._exposure === value) {
  84963. return;
  84964. }
  84965. this._exposure = value;
  84966. this._updateParameters();
  84967. },
  84968. enumerable: true,
  84969. configurable: true
  84970. });
  84971. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  84972. /**
  84973. * Gets wether the tone mapping effect is enabled.
  84974. */
  84975. get: function () {
  84976. return this._toneMappingEnabled;
  84977. },
  84978. /**
  84979. * Sets wether the tone mapping effect is enabled.
  84980. */
  84981. set: function (value) {
  84982. if (this._toneMappingEnabled === value) {
  84983. return;
  84984. }
  84985. this._toneMappingEnabled = value;
  84986. this._updateParameters();
  84987. },
  84988. enumerable: true,
  84989. configurable: true
  84990. });
  84991. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  84992. /**
  84993. * Gets the type of tone mapping effect.
  84994. */
  84995. get: function () {
  84996. return this._toneMappingType;
  84997. },
  84998. /**
  84999. * Sets the type of tone mapping effect used in BabylonJS.
  85000. */
  85001. set: function (value) {
  85002. if (this._toneMappingType === value) {
  85003. return;
  85004. }
  85005. this._toneMappingType = value;
  85006. this._updateParameters();
  85007. },
  85008. enumerable: true,
  85009. configurable: true
  85010. });
  85011. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  85012. /**
  85013. * Gets the contrast used in the effect.
  85014. */
  85015. get: function () {
  85016. return this._contrast;
  85017. },
  85018. /**
  85019. * Sets the contrast used in the effect.
  85020. */
  85021. set: function (value) {
  85022. if (this._contrast === value) {
  85023. return;
  85024. }
  85025. this._contrast = value;
  85026. this._updateParameters();
  85027. },
  85028. enumerable: true,
  85029. configurable: true
  85030. });
  85031. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  85032. /**
  85033. * Gets the vignette blend mode allowing different kind of effect.
  85034. */
  85035. get: function () {
  85036. return this._vignetteBlendMode;
  85037. },
  85038. /**
  85039. * Sets the vignette blend mode allowing different kind of effect.
  85040. */
  85041. set: function (value) {
  85042. if (this._vignetteBlendMode === value) {
  85043. return;
  85044. }
  85045. this._vignetteBlendMode = value;
  85046. this._updateParameters();
  85047. },
  85048. enumerable: true,
  85049. configurable: true
  85050. });
  85051. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  85052. /**
  85053. * Gets wether the vignette effect is enabled.
  85054. */
  85055. get: function () {
  85056. return this._vignetteEnabled;
  85057. },
  85058. /**
  85059. * Sets wether the vignette effect is enabled.
  85060. */
  85061. set: function (value) {
  85062. if (this._vignetteEnabled === value) {
  85063. return;
  85064. }
  85065. this._vignetteEnabled = value;
  85066. this._updateParameters();
  85067. },
  85068. enumerable: true,
  85069. configurable: true
  85070. });
  85071. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  85072. /**
  85073. * Gets wether the image processing is applied through a post process or not.
  85074. */
  85075. get: function () {
  85076. return this._applyByPostProcess;
  85077. },
  85078. /**
  85079. * Sets wether the image processing is applied through a post process or not.
  85080. */
  85081. set: function (value) {
  85082. if (this._applyByPostProcess === value) {
  85083. return;
  85084. }
  85085. this._applyByPostProcess = value;
  85086. this._updateParameters();
  85087. },
  85088. enumerable: true,
  85089. configurable: true
  85090. });
  85091. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  85092. /**
  85093. * Gets wether the image processing is enabled or not.
  85094. */
  85095. get: function () {
  85096. return this._isEnabled;
  85097. },
  85098. /**
  85099. * Sets wether the image processing is enabled or not.
  85100. */
  85101. set: function (value) {
  85102. if (this._isEnabled === value) {
  85103. return;
  85104. }
  85105. this._isEnabled = value;
  85106. this._updateParameters();
  85107. },
  85108. enumerable: true,
  85109. configurable: true
  85110. });
  85111. /**
  85112. * Method called each time the image processing information changes requires to recompile the effect.
  85113. */
  85114. ImageProcessingConfiguration.prototype._updateParameters = function () {
  85115. this.onUpdateParameters.notifyObservers(this);
  85116. };
  85117. ImageProcessingConfiguration.prototype.getClassName = function () {
  85118. return "ImageProcessingConfiguration";
  85119. };
  85120. /**
  85121. * Prepare the list of uniforms associated with the Image Processing effects.
  85122. * @param uniformsList The list of uniforms used in the effect
  85123. * @param defines the list of defines currently in use
  85124. */
  85125. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  85126. if (defines.EXPOSURE) {
  85127. uniforms.push("exposureLinear");
  85128. }
  85129. if (defines.CONTRAST) {
  85130. uniforms.push("contrast");
  85131. }
  85132. if (defines.COLORGRADING) {
  85133. uniforms.push("colorTransformSettings");
  85134. }
  85135. if (defines.VIGNETTE) {
  85136. uniforms.push("vInverseScreenSize");
  85137. uniforms.push("vignetteSettings1");
  85138. uniforms.push("vignetteSettings2");
  85139. }
  85140. if (defines.COLORCURVES) {
  85141. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  85142. }
  85143. };
  85144. /**
  85145. * Prepare the list of samplers associated with the Image Processing effects.
  85146. * @param uniformsList The list of uniforms used in the effect
  85147. * @param defines the list of defines currently in use
  85148. */
  85149. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  85150. if (defines.COLORGRADING) {
  85151. samplersList.push("txColorTransform");
  85152. }
  85153. };
  85154. /**
  85155. * Prepare the list of defines associated to the shader.
  85156. * @param defines the list of defines to complete
  85157. */
  85158. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  85159. if (forPostProcess === void 0) { forPostProcess = false; }
  85160. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  85161. defines.VIGNETTE = false;
  85162. defines.TONEMAPPING = false;
  85163. defines.TONEMAPPING_ACES = false;
  85164. defines.CONTRAST = false;
  85165. defines.EXPOSURE = false;
  85166. defines.COLORCURVES = false;
  85167. defines.COLORGRADING = false;
  85168. defines.COLORGRADING3D = false;
  85169. defines.IMAGEPROCESSING = false;
  85170. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  85171. return;
  85172. }
  85173. defines.VIGNETTE = this.vignetteEnabled;
  85174. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  85175. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  85176. defines.TONEMAPPING = this.toneMappingEnabled;
  85177. switch (this._toneMappingType) {
  85178. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  85179. defines.TONEMAPPING_ACES = true;
  85180. break;
  85181. }
  85182. defines.CONTRAST = (this.contrast !== 1.0);
  85183. defines.EXPOSURE = (this.exposure !== 1.0);
  85184. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  85185. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  85186. if (defines.COLORGRADING) {
  85187. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  85188. }
  85189. else {
  85190. defines.COLORGRADING3D = false;
  85191. }
  85192. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  85193. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  85194. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  85195. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  85196. };
  85197. /**
  85198. * Returns true if all the image processing information are ready.
  85199. */
  85200. ImageProcessingConfiguration.prototype.isReady = function () {
  85201. // Color Grading texure can not be none blocking.
  85202. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  85203. };
  85204. /**
  85205. * Binds the image processing to the shader.
  85206. * @param effect The effect to bind to
  85207. */
  85208. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  85209. if (aspectRatio === void 0) { aspectRatio = 1; }
  85210. // Color Curves
  85211. if (this._colorCurvesEnabled && this.colorCurves) {
  85212. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  85213. }
  85214. // Vignette
  85215. if (this._vignetteEnabled) {
  85216. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  85217. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  85218. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  85219. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  85220. var vignetteScaleX = vignetteScaleY * aspectRatio;
  85221. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  85222. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  85223. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  85224. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  85225. var vignettePower = -2.0 * this.vignetteWeight;
  85226. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  85227. }
  85228. // Exposure
  85229. effect.setFloat("exposureLinear", this.exposure);
  85230. // Contrast
  85231. effect.setFloat("contrast", this.contrast);
  85232. // Color transform settings
  85233. if (this.colorGradingTexture) {
  85234. effect.setTexture("txColorTransform", this.colorGradingTexture);
  85235. var textureSize = this.colorGradingTexture.getSize().height;
  85236. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  85237. 0.5 / textureSize, // textureOffset
  85238. textureSize, // textureSize
  85239. this.colorGradingTexture.level // weight
  85240. );
  85241. }
  85242. };
  85243. /**
  85244. * Clones the current image processing instance.
  85245. * @return The cloned image processing
  85246. */
  85247. ImageProcessingConfiguration.prototype.clone = function () {
  85248. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  85249. };
  85250. /**
  85251. * Serializes the current image processing instance to a json representation.
  85252. * @return a JSON representation
  85253. */
  85254. ImageProcessingConfiguration.prototype.serialize = function () {
  85255. return BABYLON.SerializationHelper.Serialize(this);
  85256. };
  85257. /**
  85258. * Parses the image processing from a json representation.
  85259. * @param source the JSON source to parse
  85260. * @return The parsed image processing
  85261. */
  85262. ImageProcessingConfiguration.Parse = function (source) {
  85263. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  85264. };
  85265. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  85266. /**
  85267. * Used to apply the vignette as a mix with the pixel color.
  85268. */
  85269. get: function () {
  85270. return this._VIGNETTEMODE_MULTIPLY;
  85271. },
  85272. enumerable: true,
  85273. configurable: true
  85274. });
  85275. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  85276. /**
  85277. * Used to apply the vignette as a replacement of the pixel color.
  85278. */
  85279. get: function () {
  85280. return this._VIGNETTEMODE_OPAQUE;
  85281. },
  85282. enumerable: true,
  85283. configurable: true
  85284. });
  85285. /**
  85286. * Default tone mapping applied in BabylonJS.
  85287. */
  85288. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  85289. /**
  85290. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  85291. * to other engines rendering to increase portability.
  85292. */
  85293. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  85294. // Static constants associated to the image processing.
  85295. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  85296. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  85297. __decorate([
  85298. BABYLON.serializeAsColorCurves()
  85299. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  85300. __decorate([
  85301. BABYLON.serialize()
  85302. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  85303. __decorate([
  85304. BABYLON.serializeAsTexture()
  85305. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  85306. __decorate([
  85307. BABYLON.serialize()
  85308. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  85309. __decorate([
  85310. BABYLON.serialize()
  85311. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  85312. __decorate([
  85313. BABYLON.serialize()
  85314. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  85315. __decorate([
  85316. BABYLON.serialize()
  85317. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  85318. __decorate([
  85319. BABYLON.serialize()
  85320. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  85321. __decorate([
  85322. BABYLON.serialize()
  85323. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  85324. __decorate([
  85325. BABYLON.serialize()
  85326. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  85327. __decorate([
  85328. BABYLON.serialize()
  85329. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  85330. __decorate([
  85331. BABYLON.serialize()
  85332. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  85333. __decorate([
  85334. BABYLON.serialize()
  85335. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  85336. __decorate([
  85337. BABYLON.serialize()
  85338. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  85339. __decorate([
  85340. BABYLON.serializeAsColor4()
  85341. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  85342. __decorate([
  85343. BABYLON.serialize()
  85344. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  85345. __decorate([
  85346. BABYLON.serialize()
  85347. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  85348. __decorate([
  85349. BABYLON.serialize()
  85350. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  85351. __decorate([
  85352. BABYLON.serialize()
  85353. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  85354. __decorate([
  85355. BABYLON.serialize()
  85356. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  85357. return ImageProcessingConfiguration;
  85358. }());
  85359. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  85360. })(BABYLON || (BABYLON = {}));
  85361. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  85362. var BABYLON;
  85363. (function (BABYLON) {
  85364. /**
  85365. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  85366. * It can help converting any input color in a desired output one. This can then be used to create effects
  85367. * from sepia, black and white to sixties or futuristic rendering...
  85368. *
  85369. * The only supported format is currently 3dl.
  85370. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  85371. */
  85372. var ColorGradingTexture = /** @class */ (function (_super) {
  85373. __extends(ColorGradingTexture, _super);
  85374. /**
  85375. * Instantiates a ColorGradingTexture from the following parameters.
  85376. *
  85377. * @param url The location of the color gradind data (currently only supporting 3dl)
  85378. * @param scene The scene the texture will be used in
  85379. */
  85380. function ColorGradingTexture(url, scene) {
  85381. var _this = _super.call(this, scene) || this;
  85382. if (!url) {
  85383. return _this;
  85384. }
  85385. _this._engine = scene.getEngine();
  85386. _this._textureMatrix = BABYLON.Matrix.Identity();
  85387. _this.name = url;
  85388. _this.url = url;
  85389. _this.hasAlpha = false;
  85390. _this.isCube = false;
  85391. _this.is3D = _this._engine.webGLVersion > 1;
  85392. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85393. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85394. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85395. _this.anisotropicFilteringLevel = 1;
  85396. _this._texture = _this._getFromCache(url, true);
  85397. if (!_this._texture) {
  85398. if (!scene.useDelayedTextureLoading) {
  85399. _this.loadTexture();
  85400. }
  85401. else {
  85402. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85403. }
  85404. }
  85405. return _this;
  85406. }
  85407. /**
  85408. * Returns the texture matrix used in most of the material.
  85409. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  85410. */
  85411. ColorGradingTexture.prototype.getTextureMatrix = function () {
  85412. return this._textureMatrix;
  85413. };
  85414. /**
  85415. * Occurs when the file being loaded is a .3dl LUT file.
  85416. */
  85417. ColorGradingTexture.prototype.load3dlTexture = function () {
  85418. var engine = this._engine;
  85419. var texture;
  85420. if (engine.webGLVersion === 1) {
  85421. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85422. }
  85423. else {
  85424. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85425. }
  85426. this._texture = texture;
  85427. var callback = function (text) {
  85428. if (typeof text !== "string") {
  85429. return;
  85430. }
  85431. var data = null;
  85432. var tempData = null;
  85433. var line;
  85434. var lines = text.split('\n');
  85435. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  85436. var maxColor = 0;
  85437. for (var i = 0; i < lines.length; i++) {
  85438. line = lines[i];
  85439. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  85440. continue;
  85441. if (line.indexOf('#') === 0)
  85442. continue;
  85443. var words = line.split(" ");
  85444. if (size === 0) {
  85445. // Number of space + one
  85446. size = words.length;
  85447. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  85448. tempData = new Float32Array(size * size * size * 4);
  85449. continue;
  85450. }
  85451. if (size != 0) {
  85452. var r = Math.max(parseInt(words[0]), 0);
  85453. var g = Math.max(parseInt(words[1]), 0);
  85454. var b = Math.max(parseInt(words[2]), 0);
  85455. maxColor = Math.max(r, maxColor);
  85456. maxColor = Math.max(g, maxColor);
  85457. maxColor = Math.max(b, maxColor);
  85458. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  85459. if (tempData) {
  85460. tempData[pixelStorageIndex + 0] = r;
  85461. tempData[pixelStorageIndex + 1] = g;
  85462. tempData[pixelStorageIndex + 2] = b;
  85463. }
  85464. pixelIndexSlice++;
  85465. if (pixelIndexSlice % size == 0) {
  85466. pixelIndexH++;
  85467. pixelIndexSlice = 0;
  85468. if (pixelIndexH % size == 0) {
  85469. pixelIndexW++;
  85470. pixelIndexH = 0;
  85471. }
  85472. }
  85473. }
  85474. }
  85475. if (tempData && data) {
  85476. for (var i = 0; i < tempData.length; i++) {
  85477. if (i > 0 && (i + 1) % 4 === 0) {
  85478. data[i] = 255;
  85479. }
  85480. else {
  85481. var value = tempData[i];
  85482. data[i] = (value / maxColor * 255);
  85483. }
  85484. }
  85485. }
  85486. if (texture.is3D) {
  85487. texture.updateSize(size, size, size);
  85488. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85489. }
  85490. else {
  85491. texture.updateSize(size * size, size);
  85492. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85493. }
  85494. };
  85495. var scene = this.getScene();
  85496. if (scene) {
  85497. scene._loadFile(this.url, callback);
  85498. }
  85499. else {
  85500. this._engine._loadFile(this.url, callback);
  85501. }
  85502. return this._texture;
  85503. };
  85504. /**
  85505. * Starts the loading process of the texture.
  85506. */
  85507. ColorGradingTexture.prototype.loadTexture = function () {
  85508. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  85509. this.load3dlTexture();
  85510. }
  85511. };
  85512. /**
  85513. * Clones the color gradind texture.
  85514. */
  85515. ColorGradingTexture.prototype.clone = function () {
  85516. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  85517. // Base texture
  85518. newTexture.level = this.level;
  85519. return newTexture;
  85520. };
  85521. /**
  85522. * Called during delayed load for textures.
  85523. */
  85524. ColorGradingTexture.prototype.delayLoad = function () {
  85525. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85526. return;
  85527. }
  85528. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85529. this._texture = this._getFromCache(this.url, true);
  85530. if (!this._texture) {
  85531. this.loadTexture();
  85532. }
  85533. };
  85534. /**
  85535. * Parses a color grading texture serialized by Babylon.
  85536. * @param parsedTexture The texture information being parsedTexture
  85537. * @param scene The scene to load the texture in
  85538. * @param rootUrl The root url of the data assets to load
  85539. * @return A color gradind texture
  85540. */
  85541. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85542. var texture = null;
  85543. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85544. texture = new ColorGradingTexture(parsedTexture.name, scene);
  85545. texture.name = parsedTexture.name;
  85546. texture.level = parsedTexture.level;
  85547. }
  85548. return texture;
  85549. };
  85550. /**
  85551. * Serializes the LUT texture to json format.
  85552. */
  85553. ColorGradingTexture.prototype.serialize = function () {
  85554. if (!this.name) {
  85555. return null;
  85556. }
  85557. var serializationObject = {};
  85558. serializationObject.name = this.name;
  85559. serializationObject.level = this.level;
  85560. serializationObject.customType = "BABYLON.ColorGradingTexture";
  85561. return serializationObject;
  85562. };
  85563. /**
  85564. * Empty line regex stored for GC.
  85565. */
  85566. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  85567. return ColorGradingTexture;
  85568. }(BABYLON.BaseTexture));
  85569. BABYLON.ColorGradingTexture = ColorGradingTexture;
  85570. })(BABYLON || (BABYLON = {}));
  85571. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  85572. var BABYLON;
  85573. (function (BABYLON) {
  85574. /**
  85575. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85576. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85577. * 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;
  85578. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85579. */
  85580. var ColorCurves = /** @class */ (function () {
  85581. function ColorCurves() {
  85582. this._dirty = true;
  85583. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  85584. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  85585. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85586. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  85587. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85588. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  85589. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  85590. this._globalHue = 30;
  85591. this._globalDensity = 0;
  85592. this._globalSaturation = 0;
  85593. this._globalExposure = 0;
  85594. this._highlightsHue = 30;
  85595. this._highlightsDensity = 0;
  85596. this._highlightsSaturation = 0;
  85597. this._highlightsExposure = 0;
  85598. this._midtonesHue = 30;
  85599. this._midtonesDensity = 0;
  85600. this._midtonesSaturation = 0;
  85601. this._midtonesExposure = 0;
  85602. this._shadowsHue = 30;
  85603. this._shadowsDensity = 0;
  85604. this._shadowsSaturation = 0;
  85605. this._shadowsExposure = 0;
  85606. }
  85607. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  85608. /**
  85609. * Gets the global Hue value.
  85610. * 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).
  85611. */
  85612. get: function () {
  85613. return this._globalHue;
  85614. },
  85615. /**
  85616. * Sets the global Hue value.
  85617. * 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).
  85618. */
  85619. set: function (value) {
  85620. this._globalHue = value;
  85621. this._dirty = true;
  85622. },
  85623. enumerable: true,
  85624. configurable: true
  85625. });
  85626. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  85627. /**
  85628. * Gets the global Density value.
  85629. * 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.
  85630. * Values less than zero provide a filter of opposite hue.
  85631. */
  85632. get: function () {
  85633. return this._globalDensity;
  85634. },
  85635. /**
  85636. * Sets the global Density value.
  85637. * 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.
  85638. * Values less than zero provide a filter of opposite hue.
  85639. */
  85640. set: function (value) {
  85641. this._globalDensity = value;
  85642. this._dirty = true;
  85643. },
  85644. enumerable: true,
  85645. configurable: true
  85646. });
  85647. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  85648. /**
  85649. * Gets the global Saturation value.
  85650. * 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.
  85651. */
  85652. get: function () {
  85653. return this._globalSaturation;
  85654. },
  85655. /**
  85656. * Sets the global Saturation value.
  85657. * 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.
  85658. */
  85659. set: function (value) {
  85660. this._globalSaturation = value;
  85661. this._dirty = true;
  85662. },
  85663. enumerable: true,
  85664. configurable: true
  85665. });
  85666. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  85667. /**
  85668. * Gets the global Exposure value.
  85669. * 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.
  85670. */
  85671. get: function () {
  85672. return this._globalExposure;
  85673. },
  85674. /**
  85675. * Sets the global Exposure value.
  85676. * 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.
  85677. */
  85678. set: function (value) {
  85679. this._globalExposure = value;
  85680. this._dirty = true;
  85681. },
  85682. enumerable: true,
  85683. configurable: true
  85684. });
  85685. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  85686. /**
  85687. * Gets the highlights Hue value.
  85688. * 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).
  85689. */
  85690. get: function () {
  85691. return this._highlightsHue;
  85692. },
  85693. /**
  85694. * Sets the highlights Hue value.
  85695. * 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).
  85696. */
  85697. set: function (value) {
  85698. this._highlightsHue = value;
  85699. this._dirty = true;
  85700. },
  85701. enumerable: true,
  85702. configurable: true
  85703. });
  85704. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  85705. /**
  85706. * Gets the highlights Density value.
  85707. * 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.
  85708. * Values less than zero provide a filter of opposite hue.
  85709. */
  85710. get: function () {
  85711. return this._highlightsDensity;
  85712. },
  85713. /**
  85714. * Sets the highlights Density value.
  85715. * 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.
  85716. * Values less than zero provide a filter of opposite hue.
  85717. */
  85718. set: function (value) {
  85719. this._highlightsDensity = value;
  85720. this._dirty = true;
  85721. },
  85722. enumerable: true,
  85723. configurable: true
  85724. });
  85725. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  85726. /**
  85727. * Gets the highlights Saturation value.
  85728. * 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.
  85729. */
  85730. get: function () {
  85731. return this._highlightsSaturation;
  85732. },
  85733. /**
  85734. * Sets the highlights Saturation value.
  85735. * 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.
  85736. */
  85737. set: function (value) {
  85738. this._highlightsSaturation = value;
  85739. this._dirty = true;
  85740. },
  85741. enumerable: true,
  85742. configurable: true
  85743. });
  85744. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  85745. /**
  85746. * Gets the highlights Exposure value.
  85747. * 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.
  85748. */
  85749. get: function () {
  85750. return this._highlightsExposure;
  85751. },
  85752. /**
  85753. * Sets the highlights Exposure value.
  85754. * 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.
  85755. */
  85756. set: function (value) {
  85757. this._highlightsExposure = value;
  85758. this._dirty = true;
  85759. },
  85760. enumerable: true,
  85761. configurable: true
  85762. });
  85763. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  85764. /**
  85765. * Gets the midtones Hue value.
  85766. * 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).
  85767. */
  85768. get: function () {
  85769. return this._midtonesHue;
  85770. },
  85771. /**
  85772. * Sets the midtones Hue value.
  85773. * 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).
  85774. */
  85775. set: function (value) {
  85776. this._midtonesHue = value;
  85777. this._dirty = true;
  85778. },
  85779. enumerable: true,
  85780. configurable: true
  85781. });
  85782. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  85783. /**
  85784. * Gets the midtones Density value.
  85785. * 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.
  85786. * Values less than zero provide a filter of opposite hue.
  85787. */
  85788. get: function () {
  85789. return this._midtonesDensity;
  85790. },
  85791. /**
  85792. * Sets the midtones Density value.
  85793. * 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.
  85794. * Values less than zero provide a filter of opposite hue.
  85795. */
  85796. set: function (value) {
  85797. this._midtonesDensity = value;
  85798. this._dirty = true;
  85799. },
  85800. enumerable: true,
  85801. configurable: true
  85802. });
  85803. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  85804. /**
  85805. * Gets the midtones Saturation value.
  85806. * 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.
  85807. */
  85808. get: function () {
  85809. return this._midtonesSaturation;
  85810. },
  85811. /**
  85812. * Sets the midtones Saturation value.
  85813. * 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.
  85814. */
  85815. set: function (value) {
  85816. this._midtonesSaturation = value;
  85817. this._dirty = true;
  85818. },
  85819. enumerable: true,
  85820. configurable: true
  85821. });
  85822. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  85823. /**
  85824. * Gets the midtones Exposure value.
  85825. * 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.
  85826. */
  85827. get: function () {
  85828. return this._midtonesExposure;
  85829. },
  85830. /**
  85831. * Sets the midtones Exposure value.
  85832. * 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.
  85833. */
  85834. set: function (value) {
  85835. this._midtonesExposure = value;
  85836. this._dirty = true;
  85837. },
  85838. enumerable: true,
  85839. configurable: true
  85840. });
  85841. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  85842. /**
  85843. * Gets the shadows Hue value.
  85844. * 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).
  85845. */
  85846. get: function () {
  85847. return this._shadowsHue;
  85848. },
  85849. /**
  85850. * Sets the shadows Hue value.
  85851. * 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).
  85852. */
  85853. set: function (value) {
  85854. this._shadowsHue = value;
  85855. this._dirty = true;
  85856. },
  85857. enumerable: true,
  85858. configurable: true
  85859. });
  85860. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  85861. /**
  85862. * Gets the shadows Density value.
  85863. * 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.
  85864. * Values less than zero provide a filter of opposite hue.
  85865. */
  85866. get: function () {
  85867. return this._shadowsDensity;
  85868. },
  85869. /**
  85870. * Sets the shadows Density value.
  85871. * 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.
  85872. * Values less than zero provide a filter of opposite hue.
  85873. */
  85874. set: function (value) {
  85875. this._shadowsDensity = value;
  85876. this._dirty = true;
  85877. },
  85878. enumerable: true,
  85879. configurable: true
  85880. });
  85881. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  85882. /**
  85883. * Gets the shadows Saturation value.
  85884. * 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.
  85885. */
  85886. get: function () {
  85887. return this._shadowsSaturation;
  85888. },
  85889. /**
  85890. * Sets the shadows Saturation value.
  85891. * 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.
  85892. */
  85893. set: function (value) {
  85894. this._shadowsSaturation = value;
  85895. this._dirty = true;
  85896. },
  85897. enumerable: true,
  85898. configurable: true
  85899. });
  85900. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  85901. /**
  85902. * Gets the shadows Exposure value.
  85903. * 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.
  85904. */
  85905. get: function () {
  85906. return this._shadowsExposure;
  85907. },
  85908. /**
  85909. * Sets the shadows Exposure value.
  85910. * 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.
  85911. */
  85912. set: function (value) {
  85913. this._shadowsExposure = value;
  85914. this._dirty = true;
  85915. },
  85916. enumerable: true,
  85917. configurable: true
  85918. });
  85919. /**
  85920. * Returns the class name
  85921. * @returns The class name
  85922. */
  85923. ColorCurves.prototype.getClassName = function () {
  85924. return "ColorCurves";
  85925. };
  85926. /**
  85927. * Binds the color curves to the shader.
  85928. * @param colorCurves The color curve to bind
  85929. * @param effect The effect to bind to
  85930. * @param positiveUniform The positive uniform shader parameter
  85931. * @param neutralUniform The neutral uniform shader parameter
  85932. * @param negativeUniform The negative uniform shader parameter
  85933. */
  85934. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  85935. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  85936. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  85937. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  85938. if (colorCurves._dirty) {
  85939. colorCurves._dirty = false;
  85940. // Fill in global info.
  85941. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  85942. // Compute highlights info.
  85943. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  85944. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  85945. // Compute midtones info.
  85946. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  85947. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  85948. // Compute shadows info.
  85949. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  85950. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  85951. // Compute deltas (neutral is midtones).
  85952. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  85953. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  85954. }
  85955. if (effect) {
  85956. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  85957. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  85958. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  85959. }
  85960. };
  85961. /**
  85962. * Prepare the list of uniforms associated with the ColorCurves effects.
  85963. * @param uniformsList The list of uniforms used in the effect
  85964. */
  85965. ColorCurves.PrepareUniforms = function (uniformsList) {
  85966. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  85967. };
  85968. /**
  85969. * Returns color grading data based on a hue, density, saturation and exposure value.
  85970. * @param filterHue The hue of the color filter.
  85971. * @param filterDensity The density of the color filter.
  85972. * @param saturation The saturation.
  85973. * @param exposure The exposure.
  85974. * @param result The result data container.
  85975. */
  85976. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  85977. if (hue == null) {
  85978. return;
  85979. }
  85980. hue = ColorCurves.clamp(hue, 0, 360);
  85981. density = ColorCurves.clamp(density, -100, 100);
  85982. saturation = ColorCurves.clamp(saturation, -100, 100);
  85983. exposure = ColorCurves.clamp(exposure, -100, 100);
  85984. // Remap the slider/config filter density with non-linear mapping and also scale by half
  85985. // so that the maximum filter density is only 50% control. This provides fine control
  85986. // for small values and reasonable range.
  85987. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  85988. density *= 0.5;
  85989. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  85990. if (density < 0) {
  85991. density *= -1;
  85992. hue = (hue + 180) % 360;
  85993. }
  85994. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  85995. result.scaleToRef(2, result);
  85996. result.a = 1 + 0.01 * saturation;
  85997. };
  85998. /**
  85999. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  86000. * @param value The input slider value in range [-100,100].
  86001. * @returns Adjusted value.
  86002. */
  86003. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  86004. value /= 100;
  86005. var x = Math.abs(value);
  86006. x = Math.pow(x, 2);
  86007. if (value < 0) {
  86008. x *= -1;
  86009. }
  86010. x *= 100;
  86011. return x;
  86012. };
  86013. /**
  86014. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  86015. * @param hue The hue (H) input.
  86016. * @param saturation The saturation (S) input.
  86017. * @param brightness The brightness (B) input.
  86018. * @result An RGBA color represented as Vector4.
  86019. */
  86020. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  86021. var h = ColorCurves.clamp(hue, 0, 360);
  86022. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  86023. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  86024. if (s === 0) {
  86025. result.r = v;
  86026. result.g = v;
  86027. result.b = v;
  86028. }
  86029. else {
  86030. // sector 0 to 5
  86031. h /= 60;
  86032. var i = Math.floor(h);
  86033. // fractional part of h
  86034. var f = h - i;
  86035. var p = v * (1 - s);
  86036. var q = v * (1 - s * f);
  86037. var t = v * (1 - s * (1 - f));
  86038. switch (i) {
  86039. case 0:
  86040. result.r = v;
  86041. result.g = t;
  86042. result.b = p;
  86043. break;
  86044. case 1:
  86045. result.r = q;
  86046. result.g = v;
  86047. result.b = p;
  86048. break;
  86049. case 2:
  86050. result.r = p;
  86051. result.g = v;
  86052. result.b = t;
  86053. break;
  86054. case 3:
  86055. result.r = p;
  86056. result.g = q;
  86057. result.b = v;
  86058. break;
  86059. case 4:
  86060. result.r = t;
  86061. result.g = p;
  86062. result.b = v;
  86063. break;
  86064. default: // case 5:
  86065. result.r = v;
  86066. result.g = p;
  86067. result.b = q;
  86068. break;
  86069. }
  86070. }
  86071. result.a = 1;
  86072. };
  86073. /**
  86074. * Returns a value clamped between min and max
  86075. * @param value The value to clamp
  86076. * @param min The minimum of value
  86077. * @param max The maximum of value
  86078. * @returns The clamped value.
  86079. */
  86080. ColorCurves.clamp = function (value, min, max) {
  86081. return Math.min(Math.max(value, min), max);
  86082. };
  86083. /**
  86084. * Clones the current color curve instance.
  86085. * @return The cloned curves
  86086. */
  86087. ColorCurves.prototype.clone = function () {
  86088. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  86089. };
  86090. /**
  86091. * Serializes the current color curve instance to a json representation.
  86092. * @return a JSON representation
  86093. */
  86094. ColorCurves.prototype.serialize = function () {
  86095. return BABYLON.SerializationHelper.Serialize(this);
  86096. };
  86097. /**
  86098. * Parses the color curve from a json representation.
  86099. * @param source the JSON source to parse
  86100. * @return The parsed curves
  86101. */
  86102. ColorCurves.Parse = function (source) {
  86103. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  86104. };
  86105. __decorate([
  86106. BABYLON.serialize()
  86107. ], ColorCurves.prototype, "_globalHue", void 0);
  86108. __decorate([
  86109. BABYLON.serialize()
  86110. ], ColorCurves.prototype, "_globalDensity", void 0);
  86111. __decorate([
  86112. BABYLON.serialize()
  86113. ], ColorCurves.prototype, "_globalSaturation", void 0);
  86114. __decorate([
  86115. BABYLON.serialize()
  86116. ], ColorCurves.prototype, "_globalExposure", void 0);
  86117. __decorate([
  86118. BABYLON.serialize()
  86119. ], ColorCurves.prototype, "_highlightsHue", void 0);
  86120. __decorate([
  86121. BABYLON.serialize()
  86122. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  86123. __decorate([
  86124. BABYLON.serialize()
  86125. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  86126. __decorate([
  86127. BABYLON.serialize()
  86128. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  86129. __decorate([
  86130. BABYLON.serialize()
  86131. ], ColorCurves.prototype, "_midtonesHue", void 0);
  86132. __decorate([
  86133. BABYLON.serialize()
  86134. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  86135. __decorate([
  86136. BABYLON.serialize()
  86137. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  86138. __decorate([
  86139. BABYLON.serialize()
  86140. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  86141. return ColorCurves;
  86142. }());
  86143. BABYLON.ColorCurves = ColorCurves;
  86144. })(BABYLON || (BABYLON = {}));
  86145. //# sourceMappingURL=babylon.colorCurves.js.map
  86146. var BABYLON;
  86147. (function (BABYLON) {
  86148. var RefractionPostProcess = /** @class */ (function (_super) {
  86149. __extends(RefractionPostProcess, _super);
  86150. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  86151. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  86152. _this.color = color;
  86153. _this.depth = depth;
  86154. _this.colorLevel = colorLevel;
  86155. _this._ownRefractionTexture = true;
  86156. _this.onActivateObservable.add(function (cam) {
  86157. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  86158. });
  86159. _this.onApplyObservable.add(function (effect) {
  86160. effect.setColor3("baseColor", _this.color);
  86161. effect.setFloat("depth", _this.depth);
  86162. effect.setFloat("colorLevel", _this.colorLevel);
  86163. effect.setTexture("refractionSampler", _this._refTexture);
  86164. });
  86165. return _this;
  86166. }
  86167. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  86168. /**
  86169. * Gets or sets the refraction texture
  86170. * Please note that you are responsible for disposing the texture if you set it manually
  86171. */
  86172. get: function () {
  86173. return this._refTexture;
  86174. },
  86175. set: function (value) {
  86176. if (this._refTexture && this._ownRefractionTexture) {
  86177. this._refTexture.dispose();
  86178. }
  86179. this._refTexture = value;
  86180. this._ownRefractionTexture = false;
  86181. },
  86182. enumerable: true,
  86183. configurable: true
  86184. });
  86185. // Methods
  86186. RefractionPostProcess.prototype.dispose = function (camera) {
  86187. if (this._refTexture && this._ownRefractionTexture) {
  86188. this._refTexture.dispose();
  86189. this._refTexture = null;
  86190. }
  86191. _super.prototype.dispose.call(this, camera);
  86192. };
  86193. return RefractionPostProcess;
  86194. }(BABYLON.PostProcess));
  86195. BABYLON.RefractionPostProcess = RefractionPostProcess;
  86196. })(BABYLON || (BABYLON = {}));
  86197. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  86198. var BABYLON;
  86199. (function (BABYLON) {
  86200. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  86201. __extends(BlackAndWhitePostProcess, _super);
  86202. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  86203. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  86204. _this.degree = 1;
  86205. _this.onApplyObservable.add(function (effect) {
  86206. effect.setFloat("degree", _this.degree);
  86207. });
  86208. return _this;
  86209. }
  86210. return BlackAndWhitePostProcess;
  86211. }(BABYLON.PostProcess));
  86212. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  86213. })(BABYLON || (BABYLON = {}));
  86214. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  86215. var BABYLON;
  86216. (function (BABYLON) {
  86217. /**
  86218. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  86219. * input texture to perform effects such as edge detection or sharpening
  86220. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  86221. */
  86222. var ConvolutionPostProcess = /** @class */ (function (_super) {
  86223. __extends(ConvolutionPostProcess, _super);
  86224. /**
  86225. * Creates a new instance ConvolutionPostProcess
  86226. * @param name The name of the effect.
  86227. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  86228. * @param options The required width/height ratio to downsize to before computing the render pass.
  86229. * @param camera The camera to apply the render pass to.
  86230. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86231. * @param engine The engine which the post process will be applied. (default: current engine)
  86232. * @param reusable If the post process can be reused on the same frame. (default: false)
  86233. * @param textureType Type of textures used when performing the post process. (default: 0)
  86234. */
  86235. function ConvolutionPostProcess(name,
  86236. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  86237. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  86238. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86239. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  86240. _this.kernel = kernel;
  86241. _this.onApply = function (effect) {
  86242. effect.setFloat2("screenSize", _this.width, _this.height);
  86243. effect.setArray("kernel", _this.kernel);
  86244. };
  86245. return _this;
  86246. }
  86247. // Statics
  86248. /**
  86249. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86250. */
  86251. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  86252. /**
  86253. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86254. */
  86255. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  86256. /**
  86257. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86258. */
  86259. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  86260. /**
  86261. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86262. */
  86263. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  86264. /**
  86265. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86266. */
  86267. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  86268. /**
  86269. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86270. */
  86271. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  86272. return ConvolutionPostProcess;
  86273. }(BABYLON.PostProcess));
  86274. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  86275. })(BABYLON || (BABYLON = {}));
  86276. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  86277. var BABYLON;
  86278. (function (BABYLON) {
  86279. var FilterPostProcess = /** @class */ (function (_super) {
  86280. __extends(FilterPostProcess, _super);
  86281. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  86282. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  86283. _this.kernelMatrix = kernelMatrix;
  86284. _this.onApply = function (effect) {
  86285. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  86286. };
  86287. return _this;
  86288. }
  86289. return FilterPostProcess;
  86290. }(BABYLON.PostProcess));
  86291. BABYLON.FilterPostProcess = FilterPostProcess;
  86292. })(BABYLON || (BABYLON = {}));
  86293. //# sourceMappingURL=babylon.filterPostProcess.js.map
  86294. var BABYLON;
  86295. (function (BABYLON) {
  86296. /**
  86297. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  86298. */
  86299. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  86300. __extends(VolumetricLightScatteringPostProcess, _super);
  86301. /**
  86302. * @constructor
  86303. * @param {string} name - The post-process name
  86304. * @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)
  86305. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  86306. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  86307. * @param {number} samples - The post-process quality, default 100
  86308. * @param {number} samplingMode - The post-process filtering mode
  86309. * @param {BABYLON.Engine} engine - The babylon engine
  86310. * @param {boolean} reusable - If the post-process is reusable
  86311. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  86312. */
  86313. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  86314. if (samples === void 0) { samples = 100; }
  86315. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86316. 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;
  86317. _this._screenCoordinates = BABYLON.Vector2.Zero();
  86318. /**
  86319. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  86320. */
  86321. _this.customMeshPosition = BABYLON.Vector3.Zero();
  86322. /**
  86323. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  86324. */
  86325. _this.useCustomMeshPosition = false;
  86326. /**
  86327. * If the post-process should inverse the light scattering direction
  86328. */
  86329. _this.invert = true;
  86330. /**
  86331. * Array containing the excluded meshes not rendered in the internal pass
  86332. */
  86333. _this.excludedMeshes = new Array();
  86334. /**
  86335. * Controls the overall intensity of the post-process
  86336. */
  86337. _this.exposure = 0.3;
  86338. /**
  86339. * Dissipates each sample's contribution in range [0, 1]
  86340. */
  86341. _this.decay = 0.96815;
  86342. /**
  86343. * Controls the overall intensity of each sample
  86344. */
  86345. _this.weight = 0.58767;
  86346. /**
  86347. * Controls the density of each sample
  86348. */
  86349. _this.density = 0.926;
  86350. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  86351. engine = scene.getEngine();
  86352. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  86353. // Configure mesh
  86354. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  86355. // Configure
  86356. _this._createPass(scene, ratio.passRatio || ratio);
  86357. _this.onActivate = function (camera) {
  86358. if (!_this.isSupported) {
  86359. _this.dispose(camera);
  86360. }
  86361. _this.onActivate = null;
  86362. };
  86363. _this.onApplyObservable.add(function (effect) {
  86364. _this._updateMeshScreenCoordinates(scene);
  86365. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  86366. effect.setFloat("exposure", _this.exposure);
  86367. effect.setFloat("decay", _this.decay);
  86368. effect.setFloat("weight", _this.weight);
  86369. effect.setFloat("density", _this.density);
  86370. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  86371. });
  86372. return _this;
  86373. }
  86374. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  86375. /**
  86376. * @hidden
  86377. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  86378. */
  86379. get: function () {
  86380. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86381. return false;
  86382. },
  86383. set: function (useDiffuseColor) {
  86384. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86385. },
  86386. enumerable: true,
  86387. configurable: true
  86388. });
  86389. /**
  86390. * Returns the string "VolumetricLightScatteringPostProcess"
  86391. * @returns "VolumetricLightScatteringPostProcess"
  86392. */
  86393. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  86394. return "VolumetricLightScatteringPostProcess";
  86395. };
  86396. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  86397. var mesh = subMesh.getMesh();
  86398. // Render this.mesh as default
  86399. if (mesh === this.mesh && mesh.material) {
  86400. return mesh.material.isReady(mesh);
  86401. }
  86402. var defines = [];
  86403. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86404. var material = subMesh.getMaterial();
  86405. // Alpha test
  86406. if (material) {
  86407. if (material.needAlphaTesting()) {
  86408. defines.push("#define ALPHATEST");
  86409. }
  86410. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86411. attribs.push(BABYLON.VertexBuffer.UVKind);
  86412. defines.push("#define UV1");
  86413. }
  86414. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86415. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86416. defines.push("#define UV2");
  86417. }
  86418. }
  86419. // Bones
  86420. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86421. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86422. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86423. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86424. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86425. }
  86426. else {
  86427. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86428. }
  86429. // Instances
  86430. if (useInstances) {
  86431. defines.push("#define INSTANCES");
  86432. attribs.push("world0");
  86433. attribs.push("world1");
  86434. attribs.push("world2");
  86435. attribs.push("world3");
  86436. }
  86437. // Get correct effect
  86438. var join = defines.join("\n");
  86439. if (this._cachedDefines !== join) {
  86440. this._cachedDefines = join;
  86441. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  86442. }
  86443. return this._volumetricLightScatteringPass.isReady();
  86444. };
  86445. /**
  86446. * Sets the new light position for light scattering effect
  86447. * @param position The new custom light position
  86448. */
  86449. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  86450. this.customMeshPosition = position;
  86451. };
  86452. /**
  86453. * Returns the light position for light scattering effect
  86454. * @return {BABYLON.Vector3} The custom light position
  86455. */
  86456. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  86457. return this.customMeshPosition;
  86458. };
  86459. /**
  86460. * Disposes the internal assets and detaches the post-process from the camera
  86461. */
  86462. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  86463. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  86464. if (rttIndex !== -1) {
  86465. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  86466. }
  86467. this._volumetricLightScatteringRTT.dispose();
  86468. _super.prototype.dispose.call(this, camera);
  86469. };
  86470. /**
  86471. * Returns the render target texture used by the post-process
  86472. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  86473. */
  86474. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  86475. return this._volumetricLightScatteringRTT;
  86476. };
  86477. // Private methods
  86478. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  86479. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  86480. return true;
  86481. }
  86482. return false;
  86483. };
  86484. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  86485. var _this = this;
  86486. var engine = scene.getEngine();
  86487. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86488. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86489. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86490. this._volumetricLightScatteringRTT.renderList = null;
  86491. this._volumetricLightScatteringRTT.renderParticles = false;
  86492. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  86493. var camera = this.getCamera();
  86494. if (camera) {
  86495. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86496. }
  86497. else {
  86498. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86499. }
  86500. // Custom render function for submeshes
  86501. var renderSubMesh = function (subMesh) {
  86502. var mesh = subMesh.getRenderingMesh();
  86503. if (_this._meshExcluded(mesh)) {
  86504. return;
  86505. }
  86506. var material = subMesh.getMaterial();
  86507. if (!material) {
  86508. return;
  86509. }
  86510. var scene = mesh.getScene();
  86511. var engine = scene.getEngine();
  86512. // Culling
  86513. engine.setState(material.backFaceCulling);
  86514. // Managing instances
  86515. var batch = mesh._getInstancesRenderList(subMesh._id);
  86516. if (batch.mustReturn) {
  86517. return;
  86518. }
  86519. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  86520. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  86521. var effect = _this._volumetricLightScatteringPass;
  86522. if (mesh === _this.mesh) {
  86523. if (subMesh.effect) {
  86524. effect = subMesh.effect;
  86525. }
  86526. else {
  86527. effect = material.getEffect();
  86528. }
  86529. }
  86530. engine.enableEffect(effect);
  86531. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  86532. if (mesh === _this.mesh) {
  86533. material.bind(mesh.getWorldMatrix(), mesh);
  86534. }
  86535. else {
  86536. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  86537. // Alpha test
  86538. if (material && material.needAlphaTesting()) {
  86539. var alphaTexture = material.getAlphaTestTexture();
  86540. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  86541. if (alphaTexture) {
  86542. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86543. }
  86544. }
  86545. // Bones
  86546. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86547. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86548. }
  86549. }
  86550. // Draw
  86551. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  86552. }
  86553. };
  86554. // Render target texture callbacks
  86555. var savedSceneClearColor;
  86556. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  86557. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  86558. savedSceneClearColor = scene.clearColor;
  86559. scene.clearColor = sceneClearColor;
  86560. });
  86561. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  86562. scene.clearColor = savedSceneClearColor;
  86563. });
  86564. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86565. var engine = scene.getEngine();
  86566. var index;
  86567. if (depthOnlySubMeshes.length) {
  86568. engine.setColorWrite(false);
  86569. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86570. renderSubMesh(depthOnlySubMeshes.data[index]);
  86571. }
  86572. engine.setColorWrite(true);
  86573. }
  86574. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86575. renderSubMesh(opaqueSubMeshes.data[index]);
  86576. }
  86577. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86578. renderSubMesh(alphaTestSubMeshes.data[index]);
  86579. }
  86580. if (transparentSubMeshes.length) {
  86581. // Sort sub meshes
  86582. for (index = 0; index < transparentSubMeshes.length; index++) {
  86583. var submesh = transparentSubMeshes.data[index];
  86584. var boundingInfo = submesh.getBoundingInfo();
  86585. if (boundingInfo && scene.activeCamera) {
  86586. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  86587. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  86588. }
  86589. }
  86590. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  86591. sortedArray.sort(function (a, b) {
  86592. // Alpha index first
  86593. if (a._alphaIndex > b._alphaIndex) {
  86594. return 1;
  86595. }
  86596. if (a._alphaIndex < b._alphaIndex) {
  86597. return -1;
  86598. }
  86599. // Then distance to camera
  86600. if (a._distanceToCamera < b._distanceToCamera) {
  86601. return 1;
  86602. }
  86603. if (a._distanceToCamera > b._distanceToCamera) {
  86604. return -1;
  86605. }
  86606. return 0;
  86607. });
  86608. // Render sub meshes
  86609. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  86610. for (index = 0; index < sortedArray.length; index++) {
  86611. renderSubMesh(sortedArray[index]);
  86612. }
  86613. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86614. }
  86615. };
  86616. };
  86617. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  86618. var transform = scene.getTransformMatrix();
  86619. var meshPosition;
  86620. if (this.useCustomMeshPosition) {
  86621. meshPosition = this.customMeshPosition;
  86622. }
  86623. else if (this.attachedNode) {
  86624. meshPosition = this.attachedNode.position;
  86625. }
  86626. else {
  86627. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  86628. }
  86629. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  86630. this._screenCoordinates.x = pos.x / this._viewPort.width;
  86631. this._screenCoordinates.y = pos.y / this._viewPort.height;
  86632. if (this.invert)
  86633. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  86634. };
  86635. // Static methods
  86636. /**
  86637. * Creates a default mesh for the Volumeric Light Scattering post-process
  86638. * @param name The mesh name
  86639. * @param scene The scene where to create the mesh
  86640. * @return {BABYLON.Mesh} the default mesh
  86641. */
  86642. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  86643. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  86644. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  86645. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  86646. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  86647. mesh.material = material;
  86648. return mesh;
  86649. };
  86650. __decorate([
  86651. BABYLON.serializeAsVector3()
  86652. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  86653. __decorate([
  86654. BABYLON.serialize()
  86655. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  86656. __decorate([
  86657. BABYLON.serialize()
  86658. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  86659. __decorate([
  86660. BABYLON.serializeAsMeshReference()
  86661. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  86662. __decorate([
  86663. BABYLON.serialize()
  86664. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  86665. __decorate([
  86666. BABYLON.serialize()
  86667. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  86668. __decorate([
  86669. BABYLON.serialize()
  86670. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  86671. __decorate([
  86672. BABYLON.serialize()
  86673. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  86674. __decorate([
  86675. BABYLON.serialize()
  86676. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  86677. return VolumetricLightScatteringPostProcess;
  86678. }(BABYLON.PostProcess));
  86679. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  86680. })(BABYLON || (BABYLON = {}));
  86681. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  86682. var BABYLON;
  86683. (function (BABYLON) {
  86684. /**
  86685. *
  86686. * This post-process allows the modification of rendered colors by using
  86687. * a 'look-up table' (LUT). This effect is also called Color Grading.
  86688. *
  86689. * The object needs to be provided an url to a texture containing the color
  86690. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  86691. * Use an image editing software to tweak the LUT to match your needs.
  86692. *
  86693. * For an example of a color LUT, see here:
  86694. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  86695. * For explanations on color grading, see here:
  86696. * @see http://udn.epicgames.com/Three/ColorGrading.html
  86697. *
  86698. */
  86699. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  86700. __extends(ColorCorrectionPostProcess, _super);
  86701. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  86702. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  86703. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86704. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  86705. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86706. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86707. _this.onApply = function (effect) {
  86708. effect.setTexture("colorTable", _this._colorTableTexture);
  86709. };
  86710. return _this;
  86711. }
  86712. return ColorCorrectionPostProcess;
  86713. }(BABYLON.PostProcess));
  86714. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  86715. })(BABYLON || (BABYLON = {}));
  86716. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  86717. var BABYLON;
  86718. (function (BABYLON) {
  86719. /** Defines operator used for tonemapping */
  86720. var TonemappingOperator;
  86721. (function (TonemappingOperator) {
  86722. /** Hable */
  86723. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  86724. /** Reinhard */
  86725. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  86726. /** HejiDawson */
  86727. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  86728. /** Photographic */
  86729. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  86730. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  86731. ;
  86732. /**
  86733. * Defines a post process to apply tone mapping
  86734. */
  86735. var TonemapPostProcess = /** @class */ (function (_super) {
  86736. __extends(TonemapPostProcess, _super);
  86737. /**
  86738. * Creates a new TonemapPostProcess
  86739. * @param name defines the name of the postprocess
  86740. * @param _operator defines the operator to use
  86741. * @param exposureAdjustment defines the required exposure adjustement
  86742. * @param camera defines the camera to use (can be null)
  86743. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  86744. * @param engine defines the hosting engine (can be ignore if camera is set)
  86745. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  86746. */
  86747. function TonemapPostProcess(name, _operator,
  86748. /** Defines the required exposure adjustement */
  86749. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  86750. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86751. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86752. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  86753. _this._operator = _operator;
  86754. _this.exposureAdjustment = exposureAdjustment;
  86755. var defines = "#define ";
  86756. if (_this._operator === TonemappingOperator.Hable)
  86757. defines += "HABLE_TONEMAPPING";
  86758. else if (_this._operator === TonemappingOperator.Reinhard)
  86759. defines += "REINHARD_TONEMAPPING";
  86760. else if (_this._operator === TonemappingOperator.HejiDawson)
  86761. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  86762. else if (_this._operator === TonemappingOperator.Photographic)
  86763. defines += "PHOTOGRAPHIC_TONEMAPPING";
  86764. //sadly a second call to create the effect.
  86765. _this.updateEffect(defines);
  86766. _this.onApply = function (effect) {
  86767. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  86768. };
  86769. return _this;
  86770. }
  86771. return TonemapPostProcess;
  86772. }(BABYLON.PostProcess));
  86773. BABYLON.TonemapPostProcess = TonemapPostProcess;
  86774. })(BABYLON || (BABYLON = {}));
  86775. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  86776. var BABYLON;
  86777. (function (BABYLON) {
  86778. var DisplayPassPostProcess = /** @class */ (function (_super) {
  86779. __extends(DisplayPassPostProcess, _super);
  86780. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  86781. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  86782. }
  86783. return DisplayPassPostProcess;
  86784. }(BABYLON.PostProcess));
  86785. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  86786. })(BABYLON || (BABYLON = {}));
  86787. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  86788. var BABYLON;
  86789. (function (BABYLON) {
  86790. var HighlightsPostProcess = /** @class */ (function (_super) {
  86791. __extends(HighlightsPostProcess, _super);
  86792. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  86793. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86794. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  86795. }
  86796. return HighlightsPostProcess;
  86797. }(BABYLON.PostProcess));
  86798. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  86799. })(BABYLON || (BABYLON = {}));
  86800. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  86801. var BABYLON;
  86802. (function (BABYLON) {
  86803. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  86804. __extends(ImageProcessingPostProcess, _super);
  86805. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  86806. if (camera === void 0) { camera = null; }
  86807. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86808. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  86809. _this._fromLinearSpace = true;
  86810. /**
  86811. * Defines cache preventing GC.
  86812. */
  86813. _this._defines = {
  86814. IMAGEPROCESSING: false,
  86815. VIGNETTE: false,
  86816. VIGNETTEBLENDMODEMULTIPLY: false,
  86817. VIGNETTEBLENDMODEOPAQUE: false,
  86818. TONEMAPPING: false,
  86819. TONEMAPPING_ACES: false,
  86820. CONTRAST: false,
  86821. COLORCURVES: false,
  86822. COLORGRADING: false,
  86823. COLORGRADING3D: false,
  86824. FROMLINEARSPACE: false,
  86825. SAMPLER3DGREENDEPTH: false,
  86826. SAMPLER3DBGRMAP: false,
  86827. IMAGEPROCESSINGPOSTPROCESS: false,
  86828. EXPOSURE: false,
  86829. };
  86830. // Setup the configuration as forced by the constructor. This would then not force the
  86831. // scene materials output in linear space and let untouched the default forward pass.
  86832. if (imageProcessingConfiguration) {
  86833. imageProcessingConfiguration.applyByPostProcess = true;
  86834. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  86835. // This will cause the shader to be compiled
  86836. _this.fromLinearSpace = false;
  86837. }
  86838. // Setup the default processing configuration to the scene.
  86839. else {
  86840. _this._attachImageProcessingConfiguration(null, true);
  86841. _this.imageProcessingConfiguration.applyByPostProcess = true;
  86842. }
  86843. _this.onApply = function (effect) {
  86844. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  86845. };
  86846. return _this;
  86847. }
  86848. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  86849. /**
  86850. * Gets the image processing configuration used either in this material.
  86851. */
  86852. get: function () {
  86853. return this._imageProcessingConfiguration;
  86854. },
  86855. /**
  86856. * Sets the Default image processing configuration used either in the this material.
  86857. *
  86858. * If sets to null, the scene one is in use.
  86859. */
  86860. set: function (value) {
  86861. this._attachImageProcessingConfiguration(value);
  86862. },
  86863. enumerable: true,
  86864. configurable: true
  86865. });
  86866. /**
  86867. * Attaches a new image processing configuration to the PBR Material.
  86868. * @param configuration
  86869. */
  86870. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  86871. var _this = this;
  86872. if (doNotBuild === void 0) { doNotBuild = false; }
  86873. if (configuration === this._imageProcessingConfiguration) {
  86874. return;
  86875. }
  86876. // Detaches observer.
  86877. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86878. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86879. }
  86880. // Pick the scene configuration if needed.
  86881. if (!configuration) {
  86882. var scene = null;
  86883. var engine = this.getEngine();
  86884. var camera = this.getCamera();
  86885. if (camera) {
  86886. scene = camera.getScene();
  86887. }
  86888. else if (engine && engine.scenes) {
  86889. var scenes = engine.scenes;
  86890. scene = scenes[scenes.length - 1];
  86891. }
  86892. else {
  86893. scene = BABYLON.Engine.LastCreatedScene;
  86894. }
  86895. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  86896. }
  86897. else {
  86898. this._imageProcessingConfiguration = configuration;
  86899. }
  86900. // Attaches observer.
  86901. if (this._imageProcessingConfiguration) {
  86902. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86903. _this._updateParameters();
  86904. });
  86905. }
  86906. // Ensure the effect will be rebuilt.
  86907. if (!doNotBuild) {
  86908. this._updateParameters();
  86909. }
  86910. };
  86911. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  86912. /**
  86913. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86914. */
  86915. get: function () {
  86916. return this.imageProcessingConfiguration.colorCurves;
  86917. },
  86918. /**
  86919. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86920. */
  86921. set: function (value) {
  86922. this.imageProcessingConfiguration.colorCurves = value;
  86923. },
  86924. enumerable: true,
  86925. configurable: true
  86926. });
  86927. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  86928. /**
  86929. * Gets wether the color curves effect is enabled.
  86930. */
  86931. get: function () {
  86932. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86933. },
  86934. /**
  86935. * Sets wether the color curves effect is enabled.
  86936. */
  86937. set: function (value) {
  86938. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86939. },
  86940. enumerable: true,
  86941. configurable: true
  86942. });
  86943. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  86944. /**
  86945. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86946. */
  86947. get: function () {
  86948. return this.imageProcessingConfiguration.colorGradingTexture;
  86949. },
  86950. /**
  86951. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86952. */
  86953. set: function (value) {
  86954. this.imageProcessingConfiguration.colorGradingTexture = value;
  86955. },
  86956. enumerable: true,
  86957. configurable: true
  86958. });
  86959. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  86960. /**
  86961. * Gets wether the color grading effect is enabled.
  86962. */
  86963. get: function () {
  86964. return this.imageProcessingConfiguration.colorGradingEnabled;
  86965. },
  86966. /**
  86967. * Gets wether the color grading effect is enabled.
  86968. */
  86969. set: function (value) {
  86970. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86971. },
  86972. enumerable: true,
  86973. configurable: true
  86974. });
  86975. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  86976. /**
  86977. * Gets exposure used in the effect.
  86978. */
  86979. get: function () {
  86980. return this.imageProcessingConfiguration.exposure;
  86981. },
  86982. /**
  86983. * Sets exposure used in the effect.
  86984. */
  86985. set: function (value) {
  86986. this.imageProcessingConfiguration.exposure = value;
  86987. },
  86988. enumerable: true,
  86989. configurable: true
  86990. });
  86991. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  86992. /**
  86993. * Gets wether tonemapping is enabled or not.
  86994. */
  86995. get: function () {
  86996. return this._imageProcessingConfiguration.toneMappingEnabled;
  86997. },
  86998. /**
  86999. * Sets wether tonemapping is enabled or not
  87000. */
  87001. set: function (value) {
  87002. this._imageProcessingConfiguration.toneMappingEnabled = value;
  87003. },
  87004. enumerable: true,
  87005. configurable: true
  87006. });
  87007. ;
  87008. ;
  87009. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  87010. /**
  87011. * Gets contrast used in the effect.
  87012. */
  87013. get: function () {
  87014. return this.imageProcessingConfiguration.contrast;
  87015. },
  87016. /**
  87017. * Sets contrast used in the effect.
  87018. */
  87019. set: function (value) {
  87020. this.imageProcessingConfiguration.contrast = value;
  87021. },
  87022. enumerable: true,
  87023. configurable: true
  87024. });
  87025. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  87026. /**
  87027. * Gets Vignette stretch size.
  87028. */
  87029. get: function () {
  87030. return this.imageProcessingConfiguration.vignetteStretch;
  87031. },
  87032. /**
  87033. * Sets Vignette stretch size.
  87034. */
  87035. set: function (value) {
  87036. this.imageProcessingConfiguration.vignetteStretch = value;
  87037. },
  87038. enumerable: true,
  87039. configurable: true
  87040. });
  87041. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  87042. /**
  87043. * Gets Vignette centre X Offset.
  87044. */
  87045. get: function () {
  87046. return this.imageProcessingConfiguration.vignetteCentreX;
  87047. },
  87048. /**
  87049. * Sets Vignette centre X Offset.
  87050. */
  87051. set: function (value) {
  87052. this.imageProcessingConfiguration.vignetteCentreX = value;
  87053. },
  87054. enumerable: true,
  87055. configurable: true
  87056. });
  87057. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  87058. /**
  87059. * Gets Vignette centre Y Offset.
  87060. */
  87061. get: function () {
  87062. return this.imageProcessingConfiguration.vignetteCentreY;
  87063. },
  87064. /**
  87065. * Sets Vignette centre Y Offset.
  87066. */
  87067. set: function (value) {
  87068. this.imageProcessingConfiguration.vignetteCentreY = value;
  87069. },
  87070. enumerable: true,
  87071. configurable: true
  87072. });
  87073. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  87074. /**
  87075. * Gets Vignette weight or intensity of the vignette effect.
  87076. */
  87077. get: function () {
  87078. return this.imageProcessingConfiguration.vignetteWeight;
  87079. },
  87080. /**
  87081. * Sets Vignette weight or intensity of the vignette effect.
  87082. */
  87083. set: function (value) {
  87084. this.imageProcessingConfiguration.vignetteWeight = value;
  87085. },
  87086. enumerable: true,
  87087. configurable: true
  87088. });
  87089. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  87090. /**
  87091. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87092. * if vignetteEnabled is set to true.
  87093. */
  87094. get: function () {
  87095. return this.imageProcessingConfiguration.vignetteColor;
  87096. },
  87097. /**
  87098. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87099. * if vignetteEnabled is set to true.
  87100. */
  87101. set: function (value) {
  87102. this.imageProcessingConfiguration.vignetteColor = value;
  87103. },
  87104. enumerable: true,
  87105. configurable: true
  87106. });
  87107. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  87108. /**
  87109. * Gets Camera field of view used by the Vignette effect.
  87110. */
  87111. get: function () {
  87112. return this.imageProcessingConfiguration.vignetteCameraFov;
  87113. },
  87114. /**
  87115. * Sets Camera field of view used by the Vignette effect.
  87116. */
  87117. set: function (value) {
  87118. this.imageProcessingConfiguration.vignetteCameraFov = value;
  87119. },
  87120. enumerable: true,
  87121. configurable: true
  87122. });
  87123. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  87124. /**
  87125. * Gets the vignette blend mode allowing different kind of effect.
  87126. */
  87127. get: function () {
  87128. return this.imageProcessingConfiguration.vignetteBlendMode;
  87129. },
  87130. /**
  87131. * Sets the vignette blend mode allowing different kind of effect.
  87132. */
  87133. set: function (value) {
  87134. this.imageProcessingConfiguration.vignetteBlendMode = value;
  87135. },
  87136. enumerable: true,
  87137. configurable: true
  87138. });
  87139. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  87140. /**
  87141. * Gets wether the vignette effect is enabled.
  87142. */
  87143. get: function () {
  87144. return this.imageProcessingConfiguration.vignetteEnabled;
  87145. },
  87146. /**
  87147. * Sets wether the vignette effect is enabled.
  87148. */
  87149. set: function (value) {
  87150. this.imageProcessingConfiguration.vignetteEnabled = value;
  87151. },
  87152. enumerable: true,
  87153. configurable: true
  87154. });
  87155. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  87156. /**
  87157. * Gets wether the input of the processing is in Gamma or Linear Space.
  87158. */
  87159. get: function () {
  87160. return this._fromLinearSpace;
  87161. },
  87162. /**
  87163. * Sets wether the input of the processing is in Gamma or Linear Space.
  87164. */
  87165. set: function (value) {
  87166. if (this._fromLinearSpace === value) {
  87167. return;
  87168. }
  87169. this._fromLinearSpace = value;
  87170. this._updateParameters();
  87171. },
  87172. enumerable: true,
  87173. configurable: true
  87174. });
  87175. ImageProcessingPostProcess.prototype.getClassName = function () {
  87176. return "ImageProcessingPostProcess";
  87177. };
  87178. ImageProcessingPostProcess.prototype._updateParameters = function () {
  87179. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  87180. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  87181. var defines = "";
  87182. for (var define in this._defines) {
  87183. if (this._defines[define]) {
  87184. defines += "#define " + define + ";\r\n";
  87185. }
  87186. }
  87187. var samplers = ["textureSampler"];
  87188. var uniforms = ["scale"];
  87189. if (BABYLON.ImageProcessingConfiguration) {
  87190. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  87191. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  87192. }
  87193. this.updateEffect(defines, uniforms, samplers);
  87194. };
  87195. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  87196. _super.prototype.dispose.call(this, camera);
  87197. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87198. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87199. }
  87200. if (this._imageProcessingConfiguration) {
  87201. this.imageProcessingConfiguration.applyByPostProcess = false;
  87202. }
  87203. };
  87204. __decorate([
  87205. BABYLON.serialize()
  87206. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  87207. return ImageProcessingPostProcess;
  87208. }(BABYLON.PostProcess));
  87209. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  87210. })(BABYLON || (BABYLON = {}));
  87211. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  87212. var BABYLON;
  87213. (function (BABYLON) {
  87214. /**
  87215. * Class used to store bone information
  87216. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  87217. */
  87218. var Bone = /** @class */ (function (_super) {
  87219. __extends(Bone, _super);
  87220. /**
  87221. * Create a new bone
  87222. * @param name defines the bone name
  87223. * @param skeleton defines the parent skeleton
  87224. * @param parentBone defines the parent (can be null if the bone is the root)
  87225. * @param localMatrix defines the local matrix
  87226. * @param restPose defines the rest pose matrix
  87227. * @param baseMatrix defines the base matrix
  87228. * @param index defines index of the bone in the hiearchy
  87229. */
  87230. function Bone(
  87231. /**
  87232. * defines the bone name
  87233. */
  87234. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  87235. if (parentBone === void 0) { parentBone = null; }
  87236. if (localMatrix === void 0) { localMatrix = null; }
  87237. if (restPose === void 0) { restPose = null; }
  87238. if (baseMatrix === void 0) { baseMatrix = null; }
  87239. if (index === void 0) { index = null; }
  87240. var _this = _super.call(this, name, skeleton.getScene()) || this;
  87241. _this.name = name;
  87242. /**
  87243. * Gets the list of child bones
  87244. */
  87245. _this.children = new Array();
  87246. /** Gets the animations associated with this bone */
  87247. _this.animations = new Array();
  87248. /**
  87249. * @hidden Internal only
  87250. * Set this value to map this bone to a different index in the transform matrices
  87251. * Set this value to -1 to exclude the bone from the transform matrices
  87252. */
  87253. _this._index = null;
  87254. _this._absoluteTransform = new BABYLON.Matrix();
  87255. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  87256. _this._scalingDeterminant = 1;
  87257. _this._worldTransform = new BABYLON.Matrix();
  87258. _this._needToDecompose = true;
  87259. _this._needToCompose = false;
  87260. _this._skeleton = skeleton;
  87261. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  87262. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  87263. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  87264. _this._index = index;
  87265. skeleton.bones.push(_this);
  87266. _this.setParent(parentBone, false);
  87267. if (baseMatrix || localMatrix) {
  87268. _this._updateDifferenceMatrix();
  87269. }
  87270. return _this;
  87271. }
  87272. Object.defineProperty(Bone.prototype, "_matrix", {
  87273. /** @hidden */
  87274. get: function () {
  87275. this._compose();
  87276. return this._localMatrix;
  87277. },
  87278. /** @hidden */
  87279. set: function (value) {
  87280. this._localMatrix.copyFrom(value);
  87281. this._needToDecompose = true;
  87282. },
  87283. enumerable: true,
  87284. configurable: true
  87285. });
  87286. // Members
  87287. /**
  87288. * Gets the parent skeleton
  87289. * @returns a skeleton
  87290. */
  87291. Bone.prototype.getSkeleton = function () {
  87292. return this._skeleton;
  87293. };
  87294. /**
  87295. * Gets parent bone
  87296. * @returns a bone or null if the bone is the root of the bone hierarchy
  87297. */
  87298. Bone.prototype.getParent = function () {
  87299. return this._parent;
  87300. };
  87301. /**
  87302. * Sets the parent bone
  87303. * @param parent defines the parent (can be null if the bone is the root)
  87304. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  87305. */
  87306. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  87307. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  87308. if (this._parent === parent) {
  87309. return;
  87310. }
  87311. if (this._parent) {
  87312. var index = this._parent.children.indexOf(this);
  87313. if (index !== -1) {
  87314. this._parent.children.splice(index, 1);
  87315. }
  87316. }
  87317. this._parent = parent;
  87318. if (this._parent) {
  87319. this._parent.children.push(this);
  87320. }
  87321. if (updateDifferenceMatrix) {
  87322. this._updateDifferenceMatrix();
  87323. }
  87324. this.markAsDirty();
  87325. };
  87326. /**
  87327. * Gets the local matrix
  87328. * @returns a matrix
  87329. */
  87330. Bone.prototype.getLocalMatrix = function () {
  87331. this._compose();
  87332. return this._localMatrix;
  87333. };
  87334. /**
  87335. * Gets the base matrix (initial matrix which remains unchanged)
  87336. * @returns a matrix
  87337. */
  87338. Bone.prototype.getBaseMatrix = function () {
  87339. return this._baseMatrix;
  87340. };
  87341. /**
  87342. * Gets the rest pose matrix
  87343. * @returns a matrix
  87344. */
  87345. Bone.prototype.getRestPose = function () {
  87346. return this._restPose;
  87347. };
  87348. /**
  87349. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  87350. */
  87351. Bone.prototype.getWorldMatrix = function () {
  87352. return this._worldTransform;
  87353. };
  87354. /**
  87355. * Sets the local matrix to rest pose matrix
  87356. */
  87357. Bone.prototype.returnToRest = function () {
  87358. this.updateMatrix(this._restPose.clone());
  87359. };
  87360. /**
  87361. * Gets the inverse of the absolute transform matrix.
  87362. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  87363. * @returns a matrix
  87364. */
  87365. Bone.prototype.getInvertedAbsoluteTransform = function () {
  87366. return this._invertedAbsoluteTransform;
  87367. };
  87368. /**
  87369. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  87370. * @returns a matrix
  87371. */
  87372. Bone.prototype.getAbsoluteTransform = function () {
  87373. return this._absoluteTransform;
  87374. };
  87375. Object.defineProperty(Bone.prototype, "position", {
  87376. // Properties (matches AbstractMesh properties)
  87377. /** Gets or sets current position (in local space) */
  87378. get: function () {
  87379. this._decompose();
  87380. return this._localPosition;
  87381. },
  87382. set: function (newPosition) {
  87383. this._decompose();
  87384. this._localPosition.copyFrom(newPosition);
  87385. this._markAsDirtyAndCompose();
  87386. },
  87387. enumerable: true,
  87388. configurable: true
  87389. });
  87390. Object.defineProperty(Bone.prototype, "rotation", {
  87391. /** Gets or sets current rotation (in local space) */
  87392. get: function () {
  87393. return this.getRotation();
  87394. },
  87395. set: function (newRotation) {
  87396. this.setRotation(newRotation);
  87397. },
  87398. enumerable: true,
  87399. configurable: true
  87400. });
  87401. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  87402. /** Gets or sets current rotation quaternion (in local space) */
  87403. get: function () {
  87404. this._decompose();
  87405. return this._localRotation;
  87406. },
  87407. set: function (newRotation) {
  87408. this.setRotationQuaternion(newRotation);
  87409. },
  87410. enumerable: true,
  87411. configurable: true
  87412. });
  87413. Object.defineProperty(Bone.prototype, "scaling", {
  87414. /** Gets or sets current scaling (in local space) */
  87415. get: function () {
  87416. return this.getScale();
  87417. },
  87418. set: function (newScaling) {
  87419. this.setScale(newScaling);
  87420. },
  87421. enumerable: true,
  87422. configurable: true
  87423. });
  87424. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  87425. /**
  87426. * Gets the animation properties override
  87427. */
  87428. get: function () {
  87429. return this._skeleton.animationPropertiesOverride;
  87430. },
  87431. enumerable: true,
  87432. configurable: true
  87433. });
  87434. // Methods
  87435. Bone.prototype._decompose = function () {
  87436. if (!this._needToDecompose) {
  87437. return;
  87438. }
  87439. this._needToDecompose = false;
  87440. if (!this._localScaling) {
  87441. this._localScaling = BABYLON.Vector3.Zero();
  87442. this._localRotation = BABYLON.Quaternion.Zero();
  87443. this._localPosition = BABYLON.Vector3.Zero();
  87444. }
  87445. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  87446. };
  87447. Bone.prototype._compose = function () {
  87448. if (!this._needToCompose) {
  87449. return;
  87450. }
  87451. this._needToCompose = false;
  87452. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  87453. };
  87454. /**
  87455. * Update the base and local matrices
  87456. * @param matrix defines the new base or local matrix
  87457. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  87458. * @param updateLocalMatrix defines if the local matrix should be updated
  87459. */
  87460. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  87461. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  87462. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  87463. this._baseMatrix.copyFrom(matrix);
  87464. if (updateDifferenceMatrix) {
  87465. this._updateDifferenceMatrix();
  87466. }
  87467. if (updateLocalMatrix) {
  87468. this._localMatrix.copyFrom(matrix);
  87469. this._markAsDirtyAndDecompose();
  87470. }
  87471. else {
  87472. this.markAsDirty();
  87473. }
  87474. };
  87475. /** @hidden */
  87476. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  87477. if (updateChildren === void 0) { updateChildren = true; }
  87478. if (!rootMatrix) {
  87479. rootMatrix = this._baseMatrix;
  87480. }
  87481. if (this._parent) {
  87482. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87483. }
  87484. else {
  87485. this._absoluteTransform.copyFrom(rootMatrix);
  87486. }
  87487. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  87488. if (updateChildren) {
  87489. for (var index = 0; index < this.children.length; index++) {
  87490. this.children[index]._updateDifferenceMatrix();
  87491. }
  87492. }
  87493. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  87494. };
  87495. /**
  87496. * Flag the bone as dirty (Forcing it to update everything)
  87497. */
  87498. Bone.prototype.markAsDirty = function () {
  87499. this._currentRenderId++;
  87500. this._childRenderId++;
  87501. this._skeleton._markAsDirty();
  87502. };
  87503. Bone.prototype._markAsDirtyAndCompose = function () {
  87504. this.markAsDirty();
  87505. this._needToCompose = true;
  87506. };
  87507. Bone.prototype._markAsDirtyAndDecompose = function () {
  87508. this.markAsDirty();
  87509. this._needToDecompose = true;
  87510. };
  87511. /**
  87512. * Copy an animation range from another bone
  87513. * @param source defines the source bone
  87514. * @param rangeName defines the range name to copy
  87515. * @param frameOffset defines the frame offset
  87516. * @param rescaleAsRequired defines if rescaling must be applied if required
  87517. * @param skelDimensionsRatio defines the scaling ratio
  87518. * @returns true if operation was successful
  87519. */
  87520. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  87521. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  87522. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  87523. // all animation may be coming from a library skeleton, so may need to create animation
  87524. if (this.animations.length === 0) {
  87525. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  87526. this.animations[0].setKeys([]);
  87527. }
  87528. // get animation info / verify there is such a range from the source bone
  87529. var sourceRange = source.animations[0].getRange(rangeName);
  87530. if (!sourceRange) {
  87531. return false;
  87532. }
  87533. var from = sourceRange.from;
  87534. var to = sourceRange.to;
  87535. var sourceKeys = source.animations[0].getKeys();
  87536. // rescaling prep
  87537. var sourceBoneLength = source.length;
  87538. var sourceParent = source.getParent();
  87539. var parent = this.getParent();
  87540. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  87541. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  87542. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  87543. var destKeys = this.animations[0].getKeys();
  87544. // loop vars declaration
  87545. var orig;
  87546. var origTranslation;
  87547. var mat;
  87548. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  87549. orig = sourceKeys[key];
  87550. if (orig.frame >= from && orig.frame <= to) {
  87551. if (rescaleAsRequired) {
  87552. mat = orig.value.clone();
  87553. // scale based on parent ratio, when bone has parent
  87554. if (parentScalingReqd) {
  87555. origTranslation = mat.getTranslation();
  87556. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  87557. // scale based on skeleton dimension ratio when root bone, and value is passed
  87558. }
  87559. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  87560. origTranslation = mat.getTranslation();
  87561. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  87562. // use original when root bone, and no data for skelDimensionsRatio
  87563. }
  87564. else {
  87565. mat = orig.value;
  87566. }
  87567. }
  87568. else {
  87569. mat = orig.value;
  87570. }
  87571. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  87572. }
  87573. }
  87574. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  87575. return true;
  87576. };
  87577. /**
  87578. * Translate the bone in local or world space
  87579. * @param vec The amount to translate the bone
  87580. * @param space The space that the translation is in
  87581. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87582. */
  87583. Bone.prototype.translate = function (vec, space, mesh) {
  87584. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87585. var lm = this.getLocalMatrix();
  87586. if (space == BABYLON.Space.LOCAL) {
  87587. lm.m[12] += vec.x;
  87588. lm.m[13] += vec.y;
  87589. lm.m[14] += vec.z;
  87590. }
  87591. else {
  87592. var wm = null;
  87593. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87594. if (mesh) {
  87595. wm = mesh.getWorldMatrix();
  87596. }
  87597. this._skeleton.computeAbsoluteTransforms();
  87598. var tmat = Bone._tmpMats[0];
  87599. var tvec = Bone._tmpVecs[0];
  87600. if (this._parent) {
  87601. if (mesh && wm) {
  87602. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87603. tmat.multiplyToRef(wm, tmat);
  87604. }
  87605. else {
  87606. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87607. }
  87608. }
  87609. tmat.m[12] = 0;
  87610. tmat.m[13] = 0;
  87611. tmat.m[14] = 0;
  87612. tmat.invert();
  87613. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  87614. lm.m[12] += tvec.x;
  87615. lm.m[13] += tvec.y;
  87616. lm.m[14] += tvec.z;
  87617. }
  87618. this._markAsDirtyAndDecompose();
  87619. };
  87620. /**
  87621. * Set the postion of the bone in local or world space
  87622. * @param position The position to set the bone
  87623. * @param space The space that the position is in
  87624. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87625. */
  87626. Bone.prototype.setPosition = function (position, space, mesh) {
  87627. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87628. var lm = this.getLocalMatrix();
  87629. if (space == BABYLON.Space.LOCAL) {
  87630. lm.m[12] = position.x;
  87631. lm.m[13] = position.y;
  87632. lm.m[14] = position.z;
  87633. }
  87634. else {
  87635. var wm = null;
  87636. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87637. if (mesh) {
  87638. wm = mesh.getWorldMatrix();
  87639. }
  87640. this._skeleton.computeAbsoluteTransforms();
  87641. var tmat = Bone._tmpMats[0];
  87642. var vec = Bone._tmpVecs[0];
  87643. if (this._parent) {
  87644. if (mesh && wm) {
  87645. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87646. tmat.multiplyToRef(wm, tmat);
  87647. }
  87648. else {
  87649. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87650. }
  87651. }
  87652. tmat.invert();
  87653. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  87654. lm.m[12] = vec.x;
  87655. lm.m[13] = vec.y;
  87656. lm.m[14] = vec.z;
  87657. }
  87658. this._markAsDirtyAndDecompose();
  87659. };
  87660. /**
  87661. * Set the absolute position of the bone (world space)
  87662. * @param position The position to set the bone
  87663. * @param mesh The mesh that this bone is attached to
  87664. */
  87665. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  87666. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  87667. };
  87668. /**
  87669. * Scale the bone on the x, y and z axes (in local space)
  87670. * @param x The amount to scale the bone on the x axis
  87671. * @param y The amount to scale the bone on the y axis
  87672. * @param z The amount to scale the bone on the z axis
  87673. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  87674. */
  87675. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  87676. if (scaleChildren === void 0) { scaleChildren = false; }
  87677. var locMat = this.getLocalMatrix();
  87678. // Apply new scaling on top of current local matrix
  87679. var scaleMat = Bone._tmpMats[0];
  87680. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  87681. scaleMat.multiplyToRef(locMat, locMat);
  87682. // Invert scaling matrix and apply the inverse to all children
  87683. scaleMat.invert();
  87684. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  87685. var child = _a[_i];
  87686. var cm = child.getLocalMatrix();
  87687. cm.multiplyToRef(scaleMat, cm);
  87688. cm.m[12] *= x;
  87689. cm.m[13] *= y;
  87690. cm.m[14] *= z;
  87691. child._markAsDirtyAndDecompose();
  87692. }
  87693. this._markAsDirtyAndDecompose();
  87694. if (scaleChildren) {
  87695. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  87696. var child = _c[_b];
  87697. child.scale(x, y, z, scaleChildren);
  87698. }
  87699. }
  87700. };
  87701. /**
  87702. * Set the bone scaling in local space
  87703. * @param scale defines the scaling vector
  87704. */
  87705. Bone.prototype.setScale = function (scale) {
  87706. this._decompose();
  87707. this._localScaling.copyFrom(scale);
  87708. this._markAsDirtyAndCompose();
  87709. };
  87710. /**
  87711. * Gets the current scaling in local space
  87712. * @returns the current scaling vector
  87713. */
  87714. Bone.prototype.getScale = function () {
  87715. this._decompose();
  87716. return this._localScaling;
  87717. };
  87718. /**
  87719. * Gets the current scaling in local space and stores it in a target vector
  87720. * @param result defines the target vector
  87721. */
  87722. Bone.prototype.getScaleToRef = function (result) {
  87723. this._decompose();
  87724. result.copyFrom(this._localScaling);
  87725. };
  87726. /**
  87727. * Set the yaw, pitch, and roll of the bone in local or world space
  87728. * @param yaw The rotation of the bone on the y axis
  87729. * @param pitch The rotation of the bone on the x axis
  87730. * @param roll The rotation of the bone on the z axis
  87731. * @param space The space that the axes of rotation are in
  87732. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87733. */
  87734. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  87735. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87736. if (space === BABYLON.Space.LOCAL) {
  87737. var quat = Bone._tmpQuat;
  87738. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  87739. this.setRotationQuaternion(quat, space, mesh);
  87740. return;
  87741. }
  87742. var rotMatInv = Bone._tmpMats[0];
  87743. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87744. return;
  87745. }
  87746. var rotMat = Bone._tmpMats[1];
  87747. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  87748. rotMatInv.multiplyToRef(rotMat, rotMat);
  87749. this._rotateWithMatrix(rotMat, space, mesh);
  87750. };
  87751. /**
  87752. * Add a rotation to the bone on an axis in local or world space
  87753. * @param axis The axis to rotate the bone on
  87754. * @param amount The amount to rotate the bone
  87755. * @param space The space that the axis is in
  87756. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87757. */
  87758. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  87759. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87760. var rmat = Bone._tmpMats[0];
  87761. rmat.m[12] = 0;
  87762. rmat.m[13] = 0;
  87763. rmat.m[14] = 0;
  87764. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  87765. this._rotateWithMatrix(rmat, space, mesh);
  87766. };
  87767. /**
  87768. * Set the rotation of the bone to a particular axis angle in local or world space
  87769. * @param axis The axis to rotate the bone on
  87770. * @param angle The angle that the bone should be rotated to
  87771. * @param space The space that the axis is in
  87772. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87773. */
  87774. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  87775. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87776. if (space === BABYLON.Space.LOCAL) {
  87777. var quat = Bone._tmpQuat;
  87778. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  87779. this.setRotationQuaternion(quat, space, mesh);
  87780. return;
  87781. }
  87782. var rotMatInv = Bone._tmpMats[0];
  87783. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87784. return;
  87785. }
  87786. var rotMat = Bone._tmpMats[1];
  87787. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  87788. rotMatInv.multiplyToRef(rotMat, rotMat);
  87789. this._rotateWithMatrix(rotMat, space, mesh);
  87790. };
  87791. /**
  87792. * Set the euler rotation of the bone in local of world space
  87793. * @param rotation The euler rotation that the bone should be set to
  87794. * @param space The space that the rotation is in
  87795. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87796. */
  87797. Bone.prototype.setRotation = function (rotation, space, mesh) {
  87798. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87799. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  87800. };
  87801. /**
  87802. * Set the quaternion rotation of the bone in local of world space
  87803. * @param quat The quaternion rotation that the bone should be set to
  87804. * @param space The space that the rotation is in
  87805. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87806. */
  87807. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  87808. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87809. if (space === BABYLON.Space.LOCAL) {
  87810. this._decompose();
  87811. this._localRotation.copyFrom(quat);
  87812. this._markAsDirtyAndCompose();
  87813. return;
  87814. }
  87815. var rotMatInv = Bone._tmpMats[0];
  87816. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87817. return;
  87818. }
  87819. var rotMat = Bone._tmpMats[1];
  87820. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  87821. rotMatInv.multiplyToRef(rotMat, rotMat);
  87822. this._rotateWithMatrix(rotMat, space, mesh);
  87823. };
  87824. /**
  87825. * Set the rotation matrix of the bone in local of world space
  87826. * @param rotMat The rotation matrix that the bone should be set to
  87827. * @param space The space that the rotation is in
  87828. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87829. */
  87830. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  87831. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87832. if (space === BABYLON.Space.LOCAL) {
  87833. var quat = Bone._tmpQuat;
  87834. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  87835. this.setRotationQuaternion(quat, space, mesh);
  87836. return;
  87837. }
  87838. var rotMatInv = Bone._tmpMats[0];
  87839. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87840. return;
  87841. }
  87842. var rotMat2 = Bone._tmpMats[1];
  87843. rotMat2.copyFrom(rotMat);
  87844. rotMatInv.multiplyToRef(rotMat, rotMat2);
  87845. this._rotateWithMatrix(rotMat2, space, mesh);
  87846. };
  87847. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  87848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87849. var lmat = this.getLocalMatrix();
  87850. var lx = lmat.m[12];
  87851. var ly = lmat.m[13];
  87852. var lz = lmat.m[14];
  87853. var parent = this.getParent();
  87854. var parentScale = Bone._tmpMats[3];
  87855. var parentScaleInv = Bone._tmpMats[4];
  87856. if (parent && space == BABYLON.Space.WORLD) {
  87857. if (mesh) {
  87858. parentScale.copyFrom(mesh.getWorldMatrix());
  87859. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  87860. }
  87861. else {
  87862. parentScale.copyFrom(parent.getAbsoluteTransform());
  87863. }
  87864. parentScaleInv.copyFrom(parentScale);
  87865. parentScaleInv.invert();
  87866. lmat.multiplyToRef(parentScale, lmat);
  87867. lmat.multiplyToRef(rmat, lmat);
  87868. lmat.multiplyToRef(parentScaleInv, lmat);
  87869. }
  87870. else {
  87871. if (space == BABYLON.Space.WORLD && mesh) {
  87872. parentScale.copyFrom(mesh.getWorldMatrix());
  87873. parentScaleInv.copyFrom(parentScale);
  87874. parentScaleInv.invert();
  87875. lmat.multiplyToRef(parentScale, lmat);
  87876. lmat.multiplyToRef(rmat, lmat);
  87877. lmat.multiplyToRef(parentScaleInv, lmat);
  87878. }
  87879. else {
  87880. lmat.multiplyToRef(rmat, lmat);
  87881. }
  87882. }
  87883. lmat.m[12] = lx;
  87884. lmat.m[13] = ly;
  87885. lmat.m[14] = lz;
  87886. this.computeAbsoluteTransforms();
  87887. this._markAsDirtyAndDecompose();
  87888. };
  87889. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  87890. var scaleMatrix = Bone._tmpMats[2];
  87891. rotMatInv.copyFrom(this.getAbsoluteTransform());
  87892. if (mesh) {
  87893. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  87894. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  87895. }
  87896. rotMatInv.invert();
  87897. if (isNaN(rotMatInv.m[0])) {
  87898. // Matrix failed to invert.
  87899. // This can happen if scale is zero for example.
  87900. return false;
  87901. }
  87902. scaleMatrix.m[0] *= this._scalingDeterminant;
  87903. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  87904. return true;
  87905. };
  87906. /**
  87907. * Get the position of the bone in local or world space
  87908. * @param space The space that the returned position is in
  87909. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87910. * @returns The position of the bone
  87911. */
  87912. Bone.prototype.getPosition = function (space, mesh) {
  87913. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87914. if (mesh === void 0) { mesh = null; }
  87915. var pos = BABYLON.Vector3.Zero();
  87916. this.getPositionToRef(space, mesh, pos);
  87917. return pos;
  87918. };
  87919. /**
  87920. * Copy the position of the bone to a vector3 in local or world space
  87921. * @param space The space that the returned position is in
  87922. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87923. * @param result The vector3 to copy the position to
  87924. */
  87925. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  87926. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87927. if (space == BABYLON.Space.LOCAL) {
  87928. var lm = this.getLocalMatrix();
  87929. result.x = lm.m[12];
  87930. result.y = lm.m[13];
  87931. result.z = lm.m[14];
  87932. }
  87933. else {
  87934. var wm = null;
  87935. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87936. if (mesh) {
  87937. wm = mesh.getWorldMatrix();
  87938. }
  87939. this._skeleton.computeAbsoluteTransforms();
  87940. var tmat = Bone._tmpMats[0];
  87941. if (mesh && wm) {
  87942. tmat.copyFrom(this.getAbsoluteTransform());
  87943. tmat.multiplyToRef(wm, tmat);
  87944. }
  87945. else {
  87946. tmat = this.getAbsoluteTransform();
  87947. }
  87948. result.x = tmat.m[12];
  87949. result.y = tmat.m[13];
  87950. result.z = tmat.m[14];
  87951. }
  87952. };
  87953. /**
  87954. * Get the absolute position of the bone (world space)
  87955. * @param mesh The mesh that this bone is attached to
  87956. * @returns The absolute position of the bone
  87957. */
  87958. Bone.prototype.getAbsolutePosition = function (mesh) {
  87959. if (mesh === void 0) { mesh = null; }
  87960. var pos = BABYLON.Vector3.Zero();
  87961. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  87962. return pos;
  87963. };
  87964. /**
  87965. * Copy the absolute position of the bone (world space) to the result param
  87966. * @param mesh The mesh that this bone is attached to
  87967. * @param result The vector3 to copy the absolute position to
  87968. */
  87969. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  87970. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  87971. };
  87972. /**
  87973. * Compute the absolute transforms of this bone and its children
  87974. */
  87975. Bone.prototype.computeAbsoluteTransforms = function () {
  87976. this._compose();
  87977. if (this._parent) {
  87978. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87979. }
  87980. else {
  87981. this._absoluteTransform.copyFrom(this._localMatrix);
  87982. var poseMatrix = this._skeleton.getPoseMatrix();
  87983. if (poseMatrix) {
  87984. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  87985. }
  87986. }
  87987. var children = this.children;
  87988. var len = children.length;
  87989. for (var i = 0; i < len; i++) {
  87990. children[i].computeAbsoluteTransforms();
  87991. }
  87992. };
  87993. /**
  87994. * Get the world direction from an axis that is in the local space of the bone
  87995. * @param localAxis The local direction that is used to compute the world direction
  87996. * @param mesh The mesh that this bone is attached to
  87997. * @returns The world direction
  87998. */
  87999. Bone.prototype.getDirection = function (localAxis, mesh) {
  88000. if (mesh === void 0) { mesh = null; }
  88001. var result = BABYLON.Vector3.Zero();
  88002. this.getDirectionToRef(localAxis, mesh, result);
  88003. return result;
  88004. };
  88005. /**
  88006. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  88007. * @param localAxis The local direction that is used to compute the world direction
  88008. * @param mesh The mesh that this bone is attached to
  88009. * @param result The vector3 that the world direction will be copied to
  88010. */
  88011. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  88012. if (mesh === void 0) { mesh = null; }
  88013. var wm = null;
  88014. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88015. if (mesh) {
  88016. wm = mesh.getWorldMatrix();
  88017. }
  88018. this._skeleton.computeAbsoluteTransforms();
  88019. var mat = Bone._tmpMats[0];
  88020. mat.copyFrom(this.getAbsoluteTransform());
  88021. if (mesh && wm) {
  88022. mat.multiplyToRef(wm, mat);
  88023. }
  88024. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  88025. result.normalize();
  88026. };
  88027. /**
  88028. * Get the euler rotation of the bone in local or world space
  88029. * @param space The space that the rotation should be in
  88030. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88031. * @returns The euler rotation
  88032. */
  88033. Bone.prototype.getRotation = function (space, mesh) {
  88034. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88035. if (mesh === void 0) { mesh = null; }
  88036. var result = BABYLON.Vector3.Zero();
  88037. this.getRotationToRef(space, mesh, result);
  88038. return result;
  88039. };
  88040. /**
  88041. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  88042. * @param space The space that the rotation should be in
  88043. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88044. * @param result The vector3 that the rotation should be copied to
  88045. */
  88046. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  88047. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88048. if (mesh === void 0) { mesh = null; }
  88049. var quat = Bone._tmpQuat;
  88050. this.getRotationQuaternionToRef(space, mesh, quat);
  88051. quat.toEulerAnglesToRef(result);
  88052. };
  88053. /**
  88054. * Get the quaternion rotation of the bone in either local or world space
  88055. * @param space The space that the rotation should be in
  88056. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88057. * @returns The quaternion rotation
  88058. */
  88059. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  88060. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88061. if (mesh === void 0) { mesh = null; }
  88062. var result = BABYLON.Quaternion.Identity();
  88063. this.getRotationQuaternionToRef(space, mesh, result);
  88064. return result;
  88065. };
  88066. /**
  88067. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  88068. * @param space The space that the rotation should be in
  88069. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88070. * @param result The quaternion that the rotation should be copied to
  88071. */
  88072. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  88073. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88074. if (mesh === void 0) { mesh = null; }
  88075. if (space == BABYLON.Space.LOCAL) {
  88076. this._decompose();
  88077. result.copyFrom(this._localRotation);
  88078. }
  88079. else {
  88080. var mat = Bone._tmpMats[0];
  88081. var amat = this.getAbsoluteTransform();
  88082. if (mesh) {
  88083. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  88084. }
  88085. else {
  88086. mat.copyFrom(amat);
  88087. }
  88088. mat.m[0] *= this._scalingDeterminant;
  88089. mat.m[1] *= this._scalingDeterminant;
  88090. mat.m[2] *= this._scalingDeterminant;
  88091. mat.decompose(undefined, result, undefined);
  88092. }
  88093. };
  88094. /**
  88095. * Get the rotation matrix of the bone in local or world space
  88096. * @param space The space that the rotation should be in
  88097. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88098. * @returns The rotation matrix
  88099. */
  88100. Bone.prototype.getRotationMatrix = function (space, mesh) {
  88101. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88102. var result = BABYLON.Matrix.Identity();
  88103. this.getRotationMatrixToRef(space, mesh, result);
  88104. return result;
  88105. };
  88106. /**
  88107. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  88108. * @param space The space that the rotation should be in
  88109. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88110. * @param result The quaternion that the rotation should be copied to
  88111. */
  88112. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  88113. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88114. if (space == BABYLON.Space.LOCAL) {
  88115. this.getLocalMatrix().getRotationMatrixToRef(result);
  88116. }
  88117. else {
  88118. var mat = Bone._tmpMats[0];
  88119. var amat = this.getAbsoluteTransform();
  88120. if (mesh) {
  88121. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  88122. }
  88123. else {
  88124. mat.copyFrom(amat);
  88125. }
  88126. mat.m[0] *= this._scalingDeterminant;
  88127. mat.m[1] *= this._scalingDeterminant;
  88128. mat.m[2] *= this._scalingDeterminant;
  88129. mat.getRotationMatrixToRef(result);
  88130. }
  88131. };
  88132. /**
  88133. * Get the world position of a point that is in the local space of the bone
  88134. * @param position The local position
  88135. * @param mesh The mesh that this bone is attached to
  88136. * @returns The world position
  88137. */
  88138. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  88139. if (mesh === void 0) { mesh = null; }
  88140. var result = BABYLON.Vector3.Zero();
  88141. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  88142. return result;
  88143. };
  88144. /**
  88145. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  88146. * @param position The local position
  88147. * @param mesh The mesh that this bone is attached to
  88148. * @param result The vector3 that the world position should be copied to
  88149. */
  88150. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  88151. if (mesh === void 0) { mesh = null; }
  88152. var wm = null;
  88153. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88154. if (mesh) {
  88155. wm = mesh.getWorldMatrix();
  88156. }
  88157. this._skeleton.computeAbsoluteTransforms();
  88158. var tmat = Bone._tmpMats[0];
  88159. if (mesh && wm) {
  88160. tmat.copyFrom(this.getAbsoluteTransform());
  88161. tmat.multiplyToRef(wm, tmat);
  88162. }
  88163. else {
  88164. tmat = this.getAbsoluteTransform();
  88165. }
  88166. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  88167. };
  88168. /**
  88169. * Get the local position of a point that is in world space
  88170. * @param position The world position
  88171. * @param mesh The mesh that this bone is attached to
  88172. * @returns The local position
  88173. */
  88174. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  88175. if (mesh === void 0) { mesh = null; }
  88176. var result = BABYLON.Vector3.Zero();
  88177. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  88178. return result;
  88179. };
  88180. /**
  88181. * Get the local position of a point that is in world space and copy it to the result param
  88182. * @param position The world position
  88183. * @param mesh The mesh that this bone is attached to
  88184. * @param result The vector3 that the local position should be copied to
  88185. */
  88186. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  88187. if (mesh === void 0) { mesh = null; }
  88188. var wm = null;
  88189. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88190. if (mesh) {
  88191. wm = mesh.getWorldMatrix();
  88192. }
  88193. this._skeleton.computeAbsoluteTransforms();
  88194. var tmat = Bone._tmpMats[0];
  88195. tmat.copyFrom(this.getAbsoluteTransform());
  88196. if (mesh && wm) {
  88197. tmat.multiplyToRef(wm, tmat);
  88198. }
  88199. tmat.invert();
  88200. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  88201. };
  88202. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88203. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  88204. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88205. return Bone;
  88206. }(BABYLON.Node));
  88207. BABYLON.Bone = Bone;
  88208. })(BABYLON || (BABYLON = {}));
  88209. //# sourceMappingURL=babylon.bone.js.map
  88210. var BABYLON;
  88211. (function (BABYLON) {
  88212. /**
  88213. * Class used to apply inverse kinematics to bones
  88214. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  88215. */
  88216. var BoneIKController = /** @class */ (function () {
  88217. /**
  88218. * Creates a new BoneIKController
  88219. * @param mesh defines the mesh to control
  88220. * @param bone defines the bone to control
  88221. * @param options defines options to set up the controller
  88222. */
  88223. function BoneIKController(mesh, bone, options) {
  88224. /**
  88225. * Gets or sets the target position
  88226. */
  88227. this.targetPosition = BABYLON.Vector3.Zero();
  88228. /**
  88229. * Gets or sets the pole target position
  88230. */
  88231. this.poleTargetPosition = BABYLON.Vector3.Zero();
  88232. /**
  88233. * Gets or sets the pole target local offset
  88234. */
  88235. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  88236. /**
  88237. * Gets or sets the pole angle
  88238. */
  88239. this.poleAngle = 0;
  88240. /**
  88241. * 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)
  88242. */
  88243. this.slerpAmount = 1;
  88244. this._bone1Quat = BABYLON.Quaternion.Identity();
  88245. this._bone1Mat = BABYLON.Matrix.Identity();
  88246. this._bone2Ang = Math.PI;
  88247. this._maxAngle = Math.PI;
  88248. this._rightHandedSystem = false;
  88249. this._bendAxis = BABYLON.Vector3.Right();
  88250. this._slerping = false;
  88251. this._adjustRoll = 0;
  88252. this._bone2 = bone;
  88253. this._bone1 = bone.getParent();
  88254. if (!this._bone1) {
  88255. return;
  88256. }
  88257. this.mesh = mesh;
  88258. var bonePos = bone.getPosition();
  88259. if (bone.getAbsoluteTransform().determinant() > 0) {
  88260. this._rightHandedSystem = true;
  88261. this._bendAxis.x = 0;
  88262. this._bendAxis.y = 0;
  88263. this._bendAxis.z = -1;
  88264. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  88265. this._adjustRoll = Math.PI * .5;
  88266. this._bendAxis.z = 1;
  88267. }
  88268. }
  88269. if (this._bone1.length) {
  88270. var boneScale1 = this._bone1.getScale();
  88271. var boneScale2 = this._bone2.getScale();
  88272. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  88273. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  88274. }
  88275. else if (this._bone1.children[0]) {
  88276. mesh.computeWorldMatrix(true);
  88277. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  88278. var pos2 = this._bone2.getAbsolutePosition(mesh);
  88279. var pos3 = this._bone1.getAbsolutePosition(mesh);
  88280. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  88281. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  88282. }
  88283. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  88284. this.maxAngle = Math.PI;
  88285. if (options) {
  88286. if (options.targetMesh) {
  88287. this.targetMesh = options.targetMesh;
  88288. this.targetMesh.computeWorldMatrix(true);
  88289. }
  88290. if (options.poleTargetMesh) {
  88291. this.poleTargetMesh = options.poleTargetMesh;
  88292. this.poleTargetMesh.computeWorldMatrix(true);
  88293. }
  88294. else if (options.poleTargetBone) {
  88295. this.poleTargetBone = options.poleTargetBone;
  88296. }
  88297. else if (this._bone1.getParent()) {
  88298. this.poleTargetBone = this._bone1.getParent();
  88299. }
  88300. if (options.poleTargetLocalOffset) {
  88301. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  88302. }
  88303. if (options.poleAngle) {
  88304. this.poleAngle = options.poleAngle;
  88305. }
  88306. if (options.bendAxis) {
  88307. this._bendAxis.copyFrom(options.bendAxis);
  88308. }
  88309. if (options.maxAngle) {
  88310. this.maxAngle = options.maxAngle;
  88311. }
  88312. if (options.slerpAmount) {
  88313. this.slerpAmount = options.slerpAmount;
  88314. }
  88315. }
  88316. }
  88317. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  88318. /**
  88319. * Gets or sets maximum allowed angle
  88320. */
  88321. get: function () {
  88322. return this._maxAngle;
  88323. },
  88324. set: function (value) {
  88325. this._setMaxAngle(value);
  88326. },
  88327. enumerable: true,
  88328. configurable: true
  88329. });
  88330. BoneIKController.prototype._setMaxAngle = function (ang) {
  88331. if (ang < 0) {
  88332. ang = 0;
  88333. }
  88334. if (ang > Math.PI || ang == undefined) {
  88335. ang = Math.PI;
  88336. }
  88337. this._maxAngle = ang;
  88338. var a = this._bone1Length;
  88339. var b = this._bone2Length;
  88340. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  88341. };
  88342. /**
  88343. * Force the controller to update the bones
  88344. */
  88345. BoneIKController.prototype.update = function () {
  88346. var bone1 = this._bone1;
  88347. if (!bone1) {
  88348. return;
  88349. }
  88350. var target = this.targetPosition;
  88351. var poleTarget = this.poleTargetPosition;
  88352. var mat1 = BoneIKController._tmpMats[0];
  88353. var mat2 = BoneIKController._tmpMats[1];
  88354. if (this.targetMesh) {
  88355. target.copyFrom(this.targetMesh.getAbsolutePosition());
  88356. }
  88357. if (this.poleTargetBone) {
  88358. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  88359. }
  88360. else if (this.poleTargetMesh) {
  88361. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  88362. }
  88363. var bonePos = BoneIKController._tmpVecs[0];
  88364. var zaxis = BoneIKController._tmpVecs[1];
  88365. var xaxis = BoneIKController._tmpVecs[2];
  88366. var yaxis = BoneIKController._tmpVecs[3];
  88367. var upAxis = BoneIKController._tmpVecs[4];
  88368. var _tmpQuat = BoneIKController._tmpQuat;
  88369. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  88370. poleTarget.subtractToRef(bonePos, upAxis);
  88371. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  88372. upAxis.y = 1;
  88373. }
  88374. else {
  88375. upAxis.normalize();
  88376. }
  88377. target.subtractToRef(bonePos, yaxis);
  88378. yaxis.normalize();
  88379. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  88380. zaxis.normalize();
  88381. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  88382. xaxis.normalize();
  88383. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  88384. var a = this._bone1Length;
  88385. var b = this._bone2Length;
  88386. var c = BABYLON.Vector3.Distance(bonePos, target);
  88387. if (this._maxReach > 0) {
  88388. c = Math.min(this._maxReach, c);
  88389. }
  88390. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  88391. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  88392. if (acosa > 1) {
  88393. acosa = 1;
  88394. }
  88395. if (acosb > 1) {
  88396. acosb = 1;
  88397. }
  88398. if (acosa < -1) {
  88399. acosa = -1;
  88400. }
  88401. if (acosb < -1) {
  88402. acosb = -1;
  88403. }
  88404. var angA = Math.acos(acosa);
  88405. var angB = Math.acos(acosb);
  88406. var angC = -angA - angB;
  88407. if (this._rightHandedSystem) {
  88408. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  88409. mat2.multiplyToRef(mat1, mat1);
  88410. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  88411. mat2.multiplyToRef(mat1, mat1);
  88412. }
  88413. else {
  88414. var _tmpVec = BoneIKController._tmpVecs[5];
  88415. _tmpVec.copyFrom(this._bendAxis);
  88416. _tmpVec.x *= -1;
  88417. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  88418. mat2.multiplyToRef(mat1, mat1);
  88419. }
  88420. if (this.poleAngle) {
  88421. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  88422. mat1.multiplyToRef(mat2, mat1);
  88423. }
  88424. if (this._bone1) {
  88425. if (this.slerpAmount < 1) {
  88426. if (!this._slerping) {
  88427. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  88428. }
  88429. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  88430. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  88431. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  88432. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  88433. this._slerping = true;
  88434. }
  88435. else {
  88436. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  88437. this._bone1Mat.copyFrom(mat1);
  88438. this._slerping = false;
  88439. }
  88440. }
  88441. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  88442. this._bone2Ang = angC;
  88443. };
  88444. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88445. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  88446. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88447. return BoneIKController;
  88448. }());
  88449. BABYLON.BoneIKController = BoneIKController;
  88450. })(BABYLON || (BABYLON = {}));
  88451. //# sourceMappingURL=babylon.boneIKController.js.map
  88452. var BABYLON;
  88453. (function (BABYLON) {
  88454. /**
  88455. * Class used to make a bone look toward a point in space
  88456. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  88457. */
  88458. var BoneLookController = /** @class */ (function () {
  88459. /**
  88460. * Create a BoneLookController
  88461. * @param mesh the mesh that the bone belongs to
  88462. * @param bone the bone that will be looking to the target
  88463. * @param target the target Vector3 to look at
  88464. * @param settings optional settings:
  88465. * * maxYaw: the maximum angle the bone will yaw to
  88466. * * minYaw: the minimum angle the bone will yaw to
  88467. * * maxPitch: the maximum angle the bone will pitch to
  88468. * * minPitch: the minimum angle the bone will yaw to
  88469. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  88470. * * upAxis: the up axis of the coordinate system
  88471. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  88472. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  88473. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  88474. * * adjustYaw: used to make an adjustment to the yaw of the bone
  88475. * * adjustPitch: used to make an adjustment to the pitch of the bone
  88476. * * adjustRoll: used to make an adjustment to the roll of the bone
  88477. **/
  88478. function BoneLookController(mesh, bone, target, options) {
  88479. /**
  88480. * The up axis of the coordinate system that is used when the bone is rotated
  88481. */
  88482. this.upAxis = BABYLON.Vector3.Up();
  88483. /**
  88484. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  88485. */
  88486. this.upAxisSpace = BABYLON.Space.LOCAL;
  88487. /**
  88488. * Used to make an adjustment to the yaw of the bone
  88489. */
  88490. this.adjustYaw = 0;
  88491. /**
  88492. * Used to make an adjustment to the pitch of the bone
  88493. */
  88494. this.adjustPitch = 0;
  88495. /**
  88496. * Used to make an adjustment to the roll of the bone
  88497. */
  88498. this.adjustRoll = 0;
  88499. /**
  88500. * 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)
  88501. */
  88502. this.slerpAmount = 1;
  88503. this._boneQuat = BABYLON.Quaternion.Identity();
  88504. this._slerping = false;
  88505. this._firstFrameSkipped = false;
  88506. this._fowardAxis = BABYLON.Vector3.Forward();
  88507. this.mesh = mesh;
  88508. this.bone = bone;
  88509. this.target = target;
  88510. if (options) {
  88511. if (options.adjustYaw) {
  88512. this.adjustYaw = options.adjustYaw;
  88513. }
  88514. if (options.adjustPitch) {
  88515. this.adjustPitch = options.adjustPitch;
  88516. }
  88517. if (options.adjustRoll) {
  88518. this.adjustRoll = options.adjustRoll;
  88519. }
  88520. if (options.maxYaw != null) {
  88521. this.maxYaw = options.maxYaw;
  88522. }
  88523. else {
  88524. this.maxYaw = Math.PI;
  88525. }
  88526. if (options.minYaw != null) {
  88527. this.minYaw = options.minYaw;
  88528. }
  88529. else {
  88530. this.minYaw = -Math.PI;
  88531. }
  88532. if (options.maxPitch != null) {
  88533. this.maxPitch = options.maxPitch;
  88534. }
  88535. else {
  88536. this.maxPitch = Math.PI;
  88537. }
  88538. if (options.minPitch != null) {
  88539. this.minPitch = options.minPitch;
  88540. }
  88541. else {
  88542. this.minPitch = -Math.PI;
  88543. }
  88544. if (options.slerpAmount != null) {
  88545. this.slerpAmount = options.slerpAmount;
  88546. }
  88547. if (options.upAxis != null) {
  88548. this.upAxis = options.upAxis;
  88549. }
  88550. if (options.upAxisSpace != null) {
  88551. this.upAxisSpace = options.upAxisSpace;
  88552. }
  88553. if (options.yawAxis != null || options.pitchAxis != null) {
  88554. var newYawAxis = BABYLON.Axis.Y;
  88555. var newPitchAxis = BABYLON.Axis.X;
  88556. if (options.yawAxis != null) {
  88557. newYawAxis = options.yawAxis.clone();
  88558. newYawAxis.normalize();
  88559. }
  88560. if (options.pitchAxis != null) {
  88561. newPitchAxis = options.pitchAxis.clone();
  88562. newPitchAxis.normalize();
  88563. }
  88564. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  88565. this._transformYawPitch = BABYLON.Matrix.Identity();
  88566. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  88567. this._transformYawPitchInv = this._transformYawPitch.clone();
  88568. this._transformYawPitch.invert();
  88569. }
  88570. }
  88571. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  88572. this.upAxisSpace = BABYLON.Space.LOCAL;
  88573. }
  88574. }
  88575. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  88576. /**
  88577. * Gets or sets the minimum yaw angle that the bone can look to
  88578. */
  88579. get: function () {
  88580. return this._minYaw;
  88581. },
  88582. set: function (value) {
  88583. this._minYaw = value;
  88584. this._minYawSin = Math.sin(value);
  88585. this._minYawCos = Math.cos(value);
  88586. if (this._maxYaw != null) {
  88587. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88588. this._yawRange = this._maxYaw - this._minYaw;
  88589. }
  88590. },
  88591. enumerable: true,
  88592. configurable: true
  88593. });
  88594. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  88595. /**
  88596. * Gets or sets the maximum yaw angle that the bone can look to
  88597. */
  88598. get: function () {
  88599. return this._maxYaw;
  88600. },
  88601. set: function (value) {
  88602. this._maxYaw = value;
  88603. this._maxYawSin = Math.sin(value);
  88604. this._maxYawCos = Math.cos(value);
  88605. if (this._minYaw != null) {
  88606. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88607. this._yawRange = this._maxYaw - this._minYaw;
  88608. }
  88609. },
  88610. enumerable: true,
  88611. configurable: true
  88612. });
  88613. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  88614. /**
  88615. * Gets or sets the minimum pitch angle that the bone can look to
  88616. */
  88617. get: function () {
  88618. return this._minPitch;
  88619. },
  88620. set: function (value) {
  88621. this._minPitch = value;
  88622. this._minPitchTan = Math.tan(value);
  88623. },
  88624. enumerable: true,
  88625. configurable: true
  88626. });
  88627. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  88628. /**
  88629. * Gets or sets the maximum pitch angle that the bone can look to
  88630. */
  88631. get: function () {
  88632. return this._maxPitch;
  88633. },
  88634. set: function (value) {
  88635. this._maxPitch = value;
  88636. this._maxPitchTan = Math.tan(value);
  88637. },
  88638. enumerable: true,
  88639. configurable: true
  88640. });
  88641. /**
  88642. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  88643. */
  88644. BoneLookController.prototype.update = function () {
  88645. //skip the first frame when slerping so that the mesh rotation is correct
  88646. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  88647. this._firstFrameSkipped = true;
  88648. return;
  88649. }
  88650. var bone = this.bone;
  88651. var bonePos = BoneLookController._tmpVecs[0];
  88652. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  88653. var target = this.target;
  88654. var _tmpMat1 = BoneLookController._tmpMats[0];
  88655. var _tmpMat2 = BoneLookController._tmpMats[1];
  88656. var mesh = this.mesh;
  88657. var parentBone = bone.getParent();
  88658. var upAxis = BoneLookController._tmpVecs[1];
  88659. upAxis.copyFrom(this.upAxis);
  88660. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  88661. if (this._transformYawPitch) {
  88662. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  88663. }
  88664. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  88665. }
  88666. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  88667. mesh.getDirectionToRef(upAxis, upAxis);
  88668. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  88669. upAxis.normalize();
  88670. }
  88671. }
  88672. var checkYaw = false;
  88673. var checkPitch = false;
  88674. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  88675. checkYaw = true;
  88676. }
  88677. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  88678. checkPitch = true;
  88679. }
  88680. if (checkYaw || checkPitch) {
  88681. var spaceMat = BoneLookController._tmpMats[2];
  88682. var spaceMatInv = BoneLookController._tmpMats[3];
  88683. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  88684. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  88685. }
  88686. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  88687. spaceMat.copyFrom(mesh.getWorldMatrix());
  88688. }
  88689. else {
  88690. var forwardAxis = BoneLookController._tmpVecs[2];
  88691. forwardAxis.copyFrom(this._fowardAxis);
  88692. if (this._transformYawPitch) {
  88693. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  88694. }
  88695. if (parentBone) {
  88696. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  88697. }
  88698. else {
  88699. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  88700. }
  88701. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  88702. rightAxis.normalize();
  88703. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  88704. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  88705. }
  88706. spaceMat.invertToRef(spaceMatInv);
  88707. var xzlen = null;
  88708. if (checkPitch) {
  88709. var localTarget = BoneLookController._tmpVecs[3];
  88710. target.subtractToRef(bonePos, localTarget);
  88711. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88712. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88713. var pitch = Math.atan2(localTarget.y, xzlen);
  88714. var newPitch = pitch;
  88715. if (pitch > this._maxPitch) {
  88716. localTarget.y = this._maxPitchTan * xzlen;
  88717. newPitch = this._maxPitch;
  88718. }
  88719. else if (pitch < this._minPitch) {
  88720. localTarget.y = this._minPitchTan * xzlen;
  88721. newPitch = this._minPitch;
  88722. }
  88723. if (pitch != newPitch) {
  88724. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88725. localTarget.addInPlace(bonePos);
  88726. target = localTarget;
  88727. }
  88728. }
  88729. if (checkYaw) {
  88730. var localTarget = BoneLookController._tmpVecs[4];
  88731. target.subtractToRef(bonePos, localTarget);
  88732. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88733. var yaw = Math.atan2(localTarget.x, localTarget.z);
  88734. var newYaw = yaw;
  88735. if (yaw > this._maxYaw || yaw < this._minYaw) {
  88736. if (xzlen == null) {
  88737. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88738. }
  88739. if (this._yawRange > Math.PI) {
  88740. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  88741. localTarget.z = this._maxYawCos * xzlen;
  88742. localTarget.x = this._maxYawSin * xzlen;
  88743. newYaw = this._maxYaw;
  88744. }
  88745. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  88746. localTarget.z = this._minYawCos * xzlen;
  88747. localTarget.x = this._minYawSin * xzlen;
  88748. newYaw = this._minYaw;
  88749. }
  88750. }
  88751. else {
  88752. if (yaw > this._maxYaw) {
  88753. localTarget.z = this._maxYawCos * xzlen;
  88754. localTarget.x = this._maxYawSin * xzlen;
  88755. newYaw = this._maxYaw;
  88756. }
  88757. else if (yaw < this._minYaw) {
  88758. localTarget.z = this._minYawCos * xzlen;
  88759. localTarget.x = this._minYawSin * xzlen;
  88760. newYaw = this._minYaw;
  88761. }
  88762. }
  88763. }
  88764. if (this._slerping && this._yawRange > Math.PI) {
  88765. //are we going to be crossing into the min/max region?
  88766. var boneFwd = BoneLookController._tmpVecs[8];
  88767. boneFwd.copyFrom(BABYLON.Axis.Z);
  88768. if (this._transformYawPitch) {
  88769. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  88770. }
  88771. var boneRotMat = BoneLookController._tmpMats[4];
  88772. this._boneQuat.toRotationMatrix(boneRotMat);
  88773. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  88774. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  88775. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  88776. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  88777. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  88778. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  88779. if (angBtwTar > angBtwMidYaw) {
  88780. if (xzlen == null) {
  88781. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88782. }
  88783. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  88784. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  88785. if (angBtwMin < angBtwMax) {
  88786. newYaw = boneYaw + Math.PI * .75;
  88787. localTarget.z = Math.cos(newYaw) * xzlen;
  88788. localTarget.x = Math.sin(newYaw) * xzlen;
  88789. }
  88790. else {
  88791. newYaw = boneYaw - Math.PI * .75;
  88792. localTarget.z = Math.cos(newYaw) * xzlen;
  88793. localTarget.x = Math.sin(newYaw) * xzlen;
  88794. }
  88795. }
  88796. }
  88797. if (yaw != newYaw) {
  88798. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88799. localTarget.addInPlace(bonePos);
  88800. target = localTarget;
  88801. }
  88802. }
  88803. }
  88804. var zaxis = BoneLookController._tmpVecs[5];
  88805. var xaxis = BoneLookController._tmpVecs[6];
  88806. var yaxis = BoneLookController._tmpVecs[7];
  88807. var _tmpQuat = BoneLookController._tmpQuat;
  88808. target.subtractToRef(bonePos, zaxis);
  88809. zaxis.normalize();
  88810. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  88811. xaxis.normalize();
  88812. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  88813. yaxis.normalize();
  88814. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  88815. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  88816. return;
  88817. }
  88818. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  88819. return;
  88820. }
  88821. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  88822. return;
  88823. }
  88824. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  88825. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  88826. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  88827. }
  88828. if (this.slerpAmount < 1) {
  88829. if (!this._slerping) {
  88830. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  88831. }
  88832. if (this._transformYawPitch) {
  88833. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88834. }
  88835. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  88836. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  88837. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  88838. this._slerping = true;
  88839. }
  88840. else {
  88841. if (this._transformYawPitch) {
  88842. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88843. }
  88844. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  88845. this._slerping = false;
  88846. }
  88847. };
  88848. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  88849. var angDiff = ang2 - ang1;
  88850. angDiff %= Math.PI * 2;
  88851. if (angDiff > Math.PI) {
  88852. angDiff -= Math.PI * 2;
  88853. }
  88854. else if (angDiff < -Math.PI) {
  88855. angDiff += Math.PI * 2;
  88856. }
  88857. return angDiff;
  88858. };
  88859. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  88860. ang1 %= (2 * Math.PI);
  88861. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88862. ang2 %= (2 * Math.PI);
  88863. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88864. var ab = 0;
  88865. if (ang1 < ang2) {
  88866. ab = ang2 - ang1;
  88867. }
  88868. else {
  88869. ab = ang1 - ang2;
  88870. }
  88871. if (ab > Math.PI) {
  88872. ab = Math.PI * 2 - ab;
  88873. }
  88874. return ab;
  88875. };
  88876. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  88877. ang %= (2 * Math.PI);
  88878. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  88879. ang1 %= (2 * Math.PI);
  88880. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88881. ang2 %= (2 * Math.PI);
  88882. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88883. if (ang1 < ang2) {
  88884. if (ang > ang1 && ang < ang2) {
  88885. return true;
  88886. }
  88887. }
  88888. else {
  88889. if (ang > ang2 && ang < ang1) {
  88890. return true;
  88891. }
  88892. }
  88893. return false;
  88894. };
  88895. 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()];
  88896. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  88897. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88898. return BoneLookController;
  88899. }());
  88900. BABYLON.BoneLookController = BoneLookController;
  88901. })(BABYLON || (BABYLON = {}));
  88902. //# sourceMappingURL=babylon.boneLookController.js.map
  88903. var BABYLON;
  88904. (function (BABYLON) {
  88905. /**
  88906. * Class used to handle skinning animations
  88907. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88908. */
  88909. var Skeleton = /** @class */ (function () {
  88910. /**
  88911. * Creates a new skeleton
  88912. * @param name defines the skeleton name
  88913. * @param id defines the skeleton Id
  88914. * @param scene defines the hosting scene
  88915. */
  88916. function Skeleton(
  88917. /** defines the skeleton name */
  88918. name,
  88919. /** defines the skeleton Id */
  88920. id, scene) {
  88921. this.name = name;
  88922. this.id = id;
  88923. /**
  88924. * Gets the list of child bones
  88925. */
  88926. this.bones = new Array();
  88927. /**
  88928. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  88929. */
  88930. this.needInitialSkinMatrix = false;
  88931. this._isDirty = true;
  88932. this._meshesWithPoseMatrix = new Array();
  88933. this._identity = BABYLON.Matrix.Identity();
  88934. this._ranges = {};
  88935. this._lastAbsoluteTransformsUpdateId = -1;
  88936. /**
  88937. * Specifies if the skeleton should be serialized
  88938. */
  88939. this.doNotSerialize = false;
  88940. this._animationPropertiesOverride = null;
  88941. // Events
  88942. /**
  88943. * An observable triggered before computing the skeleton's matrices
  88944. */
  88945. this.onBeforeComputeObservable = new BABYLON.Observable();
  88946. this.bones = [];
  88947. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88948. scene.skeletons.push(this);
  88949. //make sure it will recalculate the matrix next time prepare is called.
  88950. this._isDirty = true;
  88951. }
  88952. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  88953. /**
  88954. * Gets or sets the animation properties override
  88955. */
  88956. get: function () {
  88957. if (!this._animationPropertiesOverride) {
  88958. return this._scene.animationPropertiesOverride;
  88959. }
  88960. return this._animationPropertiesOverride;
  88961. },
  88962. set: function (value) {
  88963. this._animationPropertiesOverride = value;
  88964. },
  88965. enumerable: true,
  88966. configurable: true
  88967. });
  88968. // Members
  88969. /**
  88970. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  88971. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  88972. * @returns a Float32Array containing matrices data
  88973. */
  88974. Skeleton.prototype.getTransformMatrices = function (mesh) {
  88975. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  88976. return mesh._bonesTransformMatrices;
  88977. }
  88978. if (!this._transformMatrices) {
  88979. this.prepare();
  88980. }
  88981. return this._transformMatrices;
  88982. };
  88983. /**
  88984. * Gets the current hosting scene
  88985. * @returns a scene object
  88986. */
  88987. Skeleton.prototype.getScene = function () {
  88988. return this._scene;
  88989. };
  88990. // Methods
  88991. /**
  88992. * Gets a string representing the current skeleton data
  88993. * @param fullDetails defines a boolean indicating if we want a verbose version
  88994. * @returns a string representing the current skeleton data
  88995. */
  88996. Skeleton.prototype.toString = function (fullDetails) {
  88997. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  88998. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  88999. if (fullDetails) {
  89000. ret += ", Ranges: {";
  89001. var first = true;
  89002. for (var name_1 in this._ranges) {
  89003. if (first) {
  89004. ret += ", ";
  89005. first = false;
  89006. }
  89007. ret += name_1;
  89008. }
  89009. ret += "}";
  89010. }
  89011. return ret;
  89012. };
  89013. /**
  89014. * Get bone's index searching by name
  89015. * @param name defines bone's name to search for
  89016. * @return the indice of the bone. Returns -1 if not found
  89017. */
  89018. Skeleton.prototype.getBoneIndexByName = function (name) {
  89019. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  89020. if (this.bones[boneIndex].name === name) {
  89021. return boneIndex;
  89022. }
  89023. }
  89024. return -1;
  89025. };
  89026. /**
  89027. * Creater a new animation range
  89028. * @param name defines the name of the range
  89029. * @param from defines the start key
  89030. * @param to defines the end key
  89031. */
  89032. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  89033. // check name not already in use
  89034. if (!this._ranges[name]) {
  89035. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  89036. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89037. if (this.bones[i].animations[0]) {
  89038. this.bones[i].animations[0].createRange(name, from, to);
  89039. }
  89040. }
  89041. }
  89042. };
  89043. /**
  89044. * Delete a specific animation range
  89045. * @param name defines the name of the range
  89046. * @param deleteFrames defines if frames must be removed as well
  89047. */
  89048. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  89049. if (deleteFrames === void 0) { deleteFrames = true; }
  89050. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89051. if (this.bones[i].animations[0]) {
  89052. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  89053. }
  89054. }
  89055. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  89056. };
  89057. /**
  89058. * Gets a specific animation range
  89059. * @param name defines the name of the range to look for
  89060. * @returns the requested animation range or null if not found
  89061. */
  89062. Skeleton.prototype.getAnimationRange = function (name) {
  89063. return this._ranges[name];
  89064. };
  89065. /**
  89066. * Gets the list of all animation ranges defined on this skeleton
  89067. * @returns an array
  89068. */
  89069. Skeleton.prototype.getAnimationRanges = function () {
  89070. var animationRanges = [];
  89071. var name;
  89072. var i = 0;
  89073. for (name in this._ranges) {
  89074. animationRanges[i] = this._ranges[name];
  89075. i++;
  89076. }
  89077. return animationRanges;
  89078. };
  89079. /**
  89080. * Copy animation range from a source skeleton.
  89081. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  89082. * @param source defines the source skeleton
  89083. * @param name defines the name of the range to copy
  89084. * @param rescaleAsRequired defines if rescaling must be applied if required
  89085. * @returns true if operation was successful
  89086. */
  89087. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  89088. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  89089. if (this._ranges[name] || !source.getAnimationRange(name)) {
  89090. return false;
  89091. }
  89092. var ret = true;
  89093. var frameOffset = this._getHighestAnimationFrame() + 1;
  89094. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  89095. var boneDict = {};
  89096. var sourceBones = source.bones;
  89097. var nBones;
  89098. var i;
  89099. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  89100. boneDict[sourceBones[i].name] = sourceBones[i];
  89101. }
  89102. if (this.bones.length !== sourceBones.length) {
  89103. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  89104. ret = false;
  89105. }
  89106. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  89107. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  89108. var boneName = this.bones[i].name;
  89109. var sourceBone = boneDict[boneName];
  89110. if (sourceBone) {
  89111. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  89112. }
  89113. else {
  89114. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  89115. ret = false;
  89116. }
  89117. }
  89118. // do not call createAnimationRange(), since it also is done to bones, which was already done
  89119. var range = source.getAnimationRange(name);
  89120. if (range) {
  89121. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  89122. }
  89123. return ret;
  89124. };
  89125. /**
  89126. * Forces the skeleton to go to rest pose
  89127. */
  89128. Skeleton.prototype.returnToRest = function () {
  89129. for (var index = 0; index < this.bones.length; index++) {
  89130. this.bones[index].returnToRest();
  89131. }
  89132. };
  89133. Skeleton.prototype._getHighestAnimationFrame = function () {
  89134. var ret = 0;
  89135. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89136. if (this.bones[i].animations[0]) {
  89137. var highest = this.bones[i].animations[0].getHighestFrame();
  89138. if (ret < highest) {
  89139. ret = highest;
  89140. }
  89141. }
  89142. }
  89143. return ret;
  89144. };
  89145. /**
  89146. * Begin a specific animation range
  89147. * @param name defines the name of the range to start
  89148. * @param loop defines if looping must be turned on (false by default)
  89149. * @param speedRatio defines the speed ratio to apply (1 by default)
  89150. * @param onAnimationEnd defines a callback which will be called when animation will end
  89151. * @returns a new animatable
  89152. */
  89153. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  89154. var range = this.getAnimationRange(name);
  89155. if (!range) {
  89156. return null;
  89157. }
  89158. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  89159. };
  89160. /** @hidden */
  89161. Skeleton.prototype._markAsDirty = function () {
  89162. this._isDirty = true;
  89163. };
  89164. /** @hidden */
  89165. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  89166. this._meshesWithPoseMatrix.push(mesh);
  89167. };
  89168. /** @hidden */
  89169. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  89170. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  89171. if (index > -1) {
  89172. this._meshesWithPoseMatrix.splice(index, 1);
  89173. }
  89174. };
  89175. /** @hidden */
  89176. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  89177. this.onBeforeComputeObservable.notifyObservers(this);
  89178. for (var index = 0; index < this.bones.length; index++) {
  89179. var bone = this.bones[index];
  89180. var parentBone = bone.getParent();
  89181. if (parentBone) {
  89182. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  89183. }
  89184. else {
  89185. if (initialSkinMatrix) {
  89186. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  89187. }
  89188. else {
  89189. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  89190. }
  89191. }
  89192. if (bone._index !== -1) {
  89193. var mappedIndex = bone._index === null ? index : bone._index;
  89194. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  89195. }
  89196. }
  89197. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  89198. };
  89199. /**
  89200. * Build all resources required to render a skeleton
  89201. */
  89202. Skeleton.prototype.prepare = function () {
  89203. if (!this._isDirty) {
  89204. return;
  89205. }
  89206. if (this.needInitialSkinMatrix) {
  89207. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  89208. var mesh = this._meshesWithPoseMatrix[index];
  89209. var poseMatrix = mesh.getPoseMatrix();
  89210. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  89211. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  89212. }
  89213. if (this._synchronizedWithMesh !== mesh) {
  89214. this._synchronizedWithMesh = mesh;
  89215. // Prepare bones
  89216. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  89217. var bone = this.bones[boneIndex];
  89218. if (!bone.getParent()) {
  89219. var matrix = bone.getBaseMatrix();
  89220. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  89221. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  89222. }
  89223. }
  89224. }
  89225. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  89226. }
  89227. }
  89228. else {
  89229. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  89230. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  89231. }
  89232. this._computeTransformMatrices(this._transformMatrices, null);
  89233. }
  89234. this._isDirty = false;
  89235. this._scene._activeBones.addCount(this.bones.length, false);
  89236. };
  89237. /**
  89238. * Gets the list of animatables currently running for this skeleton
  89239. * @returns an array of animatables
  89240. */
  89241. Skeleton.prototype.getAnimatables = function () {
  89242. if (!this._animatables || this._animatables.length !== this.bones.length) {
  89243. this._animatables = [];
  89244. for (var index = 0; index < this.bones.length; index++) {
  89245. this._animatables.push(this.bones[index]);
  89246. }
  89247. }
  89248. return this._animatables;
  89249. };
  89250. /**
  89251. * Clone the current skeleton
  89252. * @param name defines the name of the new skeleton
  89253. * @param id defines the id of the enw skeleton
  89254. * @returns the new skeleton
  89255. */
  89256. Skeleton.prototype.clone = function (name, id) {
  89257. var result = new Skeleton(name, id || name, this._scene);
  89258. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  89259. for (var index = 0; index < this.bones.length; index++) {
  89260. var source = this.bones[index];
  89261. var parentBone = null;
  89262. var parent_1 = source.getParent();
  89263. if (parent_1) {
  89264. var parentIndex = this.bones.indexOf(parent_1);
  89265. parentBone = result.bones[parentIndex];
  89266. }
  89267. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  89268. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  89269. }
  89270. if (this._ranges) {
  89271. result._ranges = {};
  89272. for (var rangeName in this._ranges) {
  89273. var range = this._ranges[rangeName];
  89274. if (range) {
  89275. result._ranges[rangeName] = range.clone();
  89276. }
  89277. }
  89278. }
  89279. this._isDirty = true;
  89280. return result;
  89281. };
  89282. /**
  89283. * Enable animation blending for this skeleton
  89284. * @param blendingSpeed defines the blending speed to apply
  89285. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  89286. */
  89287. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  89288. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  89289. this.bones.forEach(function (bone) {
  89290. bone.animations.forEach(function (animation) {
  89291. animation.enableBlending = true;
  89292. animation.blendingSpeed = blendingSpeed;
  89293. });
  89294. });
  89295. };
  89296. /**
  89297. * Releases all resources associated with the current skeleton
  89298. */
  89299. Skeleton.prototype.dispose = function () {
  89300. this._meshesWithPoseMatrix = [];
  89301. // Animations
  89302. this.getScene().stopAnimation(this);
  89303. // Remove from scene
  89304. this.getScene().removeSkeleton(this);
  89305. };
  89306. /**
  89307. * Serialize the skeleton in a JSON object
  89308. * @returns a JSON object
  89309. */
  89310. Skeleton.prototype.serialize = function () {
  89311. var serializationObject = {};
  89312. serializationObject.name = this.name;
  89313. serializationObject.id = this.id;
  89314. if (this.dimensionsAtRest) {
  89315. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  89316. }
  89317. serializationObject.bones = [];
  89318. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  89319. for (var index = 0; index < this.bones.length; index++) {
  89320. var bone = this.bones[index];
  89321. var parent_2 = bone.getParent();
  89322. var serializedBone = {
  89323. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  89324. name: bone.name,
  89325. matrix: bone.getBaseMatrix().toArray(),
  89326. rest: bone.getRestPose().toArray()
  89327. };
  89328. serializationObject.bones.push(serializedBone);
  89329. if (bone.length) {
  89330. serializedBone.length = bone.length;
  89331. }
  89332. if (bone.metadata) {
  89333. serializedBone.metadata = bone.metadata;
  89334. }
  89335. if (bone.animations && bone.animations.length > 0) {
  89336. serializedBone.animation = bone.animations[0].serialize();
  89337. }
  89338. serializationObject.ranges = [];
  89339. for (var name in this._ranges) {
  89340. var source = this._ranges[name];
  89341. if (!source) {
  89342. continue;
  89343. }
  89344. var range = {};
  89345. range.name = name;
  89346. range.from = source.from;
  89347. range.to = source.to;
  89348. serializationObject.ranges.push(range);
  89349. }
  89350. }
  89351. return serializationObject;
  89352. };
  89353. /**
  89354. * Creates a new skeleton from serialized data
  89355. * @param parsedSkeleton defines the serialized data
  89356. * @param scene defines the hosting scene
  89357. * @returns a new skeleton
  89358. */
  89359. Skeleton.Parse = function (parsedSkeleton, scene) {
  89360. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  89361. if (parsedSkeleton.dimensionsAtRest) {
  89362. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  89363. }
  89364. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  89365. var index;
  89366. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  89367. var parsedBone = parsedSkeleton.bones[index];
  89368. var parentBone = null;
  89369. if (parsedBone.parentBoneIndex > -1) {
  89370. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  89371. }
  89372. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  89373. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  89374. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  89375. bone.id = parsedBone.id;
  89376. }
  89377. if (parsedBone.length) {
  89378. bone.length = parsedBone.length;
  89379. }
  89380. if (parsedBone.metadata) {
  89381. bone.metadata = parsedBone.metadata;
  89382. }
  89383. if (parsedBone.animation) {
  89384. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  89385. }
  89386. }
  89387. // placed after bones, so createAnimationRange can cascade down
  89388. if (parsedSkeleton.ranges) {
  89389. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  89390. var data = parsedSkeleton.ranges[index];
  89391. skeleton.createAnimationRange(data.name, data.from, data.to);
  89392. }
  89393. }
  89394. return skeleton;
  89395. };
  89396. /**
  89397. * Compute all node absolute transforms
  89398. * @param forceUpdate defines if computation must be done even if cache is up to date
  89399. */
  89400. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  89401. if (forceUpdate === void 0) { forceUpdate = false; }
  89402. var renderId = this._scene.getRenderId();
  89403. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  89404. this.bones[0].computeAbsoluteTransforms();
  89405. this._lastAbsoluteTransformsUpdateId = renderId;
  89406. }
  89407. };
  89408. /**
  89409. * Gets the root pose matrix
  89410. * @returns a matrix
  89411. */
  89412. Skeleton.prototype.getPoseMatrix = function () {
  89413. var poseMatrix = null;
  89414. if (this._meshesWithPoseMatrix.length > 0) {
  89415. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  89416. }
  89417. return poseMatrix;
  89418. };
  89419. /**
  89420. * Sorts bones per internal index
  89421. */
  89422. Skeleton.prototype.sortBones = function () {
  89423. var bones = new Array();
  89424. var visited = new Array(this.bones.length);
  89425. for (var index = 0; index < this.bones.length; index++) {
  89426. this._sortBones(index, bones, visited);
  89427. }
  89428. this.bones = bones;
  89429. };
  89430. Skeleton.prototype._sortBones = function (index, bones, visited) {
  89431. if (visited[index]) {
  89432. return;
  89433. }
  89434. visited[index] = true;
  89435. var bone = this.bones[index];
  89436. if (bone._index === undefined) {
  89437. bone._index = index;
  89438. }
  89439. var parentBone = bone.getParent();
  89440. if (parentBone) {
  89441. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  89442. }
  89443. bones.push(bone);
  89444. };
  89445. return Skeleton;
  89446. }());
  89447. BABYLON.Skeleton = Skeleton;
  89448. })(BABYLON || (BABYLON = {}));
  89449. //# sourceMappingURL=babylon.skeleton.js.map
  89450. var BABYLON;
  89451. (function (BABYLON) {
  89452. ;
  89453. /**
  89454. * This groups tools to convert HDR texture to native colors array.
  89455. */
  89456. var HDRTools = /** @class */ (function () {
  89457. function HDRTools() {
  89458. }
  89459. HDRTools.Ldexp = function (mantissa, exponent) {
  89460. if (exponent > 1023) {
  89461. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  89462. }
  89463. if (exponent < -1074) {
  89464. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  89465. }
  89466. return mantissa * Math.pow(2, exponent);
  89467. };
  89468. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  89469. if (exponent > 0) { /*nonzero pixel*/
  89470. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  89471. float32array[index + 0] = red * exponent;
  89472. float32array[index + 1] = green * exponent;
  89473. float32array[index + 2] = blue * exponent;
  89474. }
  89475. else {
  89476. float32array[index + 0] = 0;
  89477. float32array[index + 1] = 0;
  89478. float32array[index + 2] = 0;
  89479. }
  89480. };
  89481. HDRTools.readStringLine = function (uint8array, startIndex) {
  89482. var line = "";
  89483. var character = "";
  89484. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  89485. character = String.fromCharCode(uint8array[i]);
  89486. if (character == "\n") {
  89487. break;
  89488. }
  89489. line += character;
  89490. }
  89491. return line;
  89492. };
  89493. /**
  89494. * Reads header information from an RGBE texture stored in a native array.
  89495. * More information on this format are available here:
  89496. * https://en.wikipedia.org/wiki/RGBE_image_format
  89497. *
  89498. * @param uint8array The binary file stored in native array.
  89499. * @return The header information.
  89500. */
  89501. HDRTools.RGBE_ReadHeader = function (uint8array) {
  89502. var height = 0;
  89503. var width = 0;
  89504. var line = this.readStringLine(uint8array, 0);
  89505. if (line[0] != '#' || line[1] != '?') {
  89506. throw "Bad HDR Format.";
  89507. }
  89508. var endOfHeader = false;
  89509. var findFormat = false;
  89510. var lineIndex = 0;
  89511. do {
  89512. lineIndex += (line.length + 1);
  89513. line = this.readStringLine(uint8array, lineIndex);
  89514. if (line == "FORMAT=32-bit_rle_rgbe") {
  89515. findFormat = true;
  89516. }
  89517. else if (line.length == 0) {
  89518. endOfHeader = true;
  89519. }
  89520. } while (!endOfHeader);
  89521. if (!findFormat) {
  89522. throw "HDR Bad header format, unsupported FORMAT";
  89523. }
  89524. lineIndex += (line.length + 1);
  89525. line = this.readStringLine(uint8array, lineIndex);
  89526. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  89527. var match = sizeRegexp.exec(line);
  89528. // TODO. Support +Y and -X if needed.
  89529. if (!match || match.length < 3) {
  89530. throw "HDR Bad header format, no size";
  89531. }
  89532. width = parseInt(match[2]);
  89533. height = parseInt(match[1]);
  89534. if (width < 8 || width > 0x7fff) {
  89535. throw "HDR Bad header format, unsupported size";
  89536. }
  89537. lineIndex += (line.length + 1);
  89538. return {
  89539. height: height,
  89540. width: width,
  89541. dataPosition: lineIndex
  89542. };
  89543. };
  89544. /**
  89545. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  89546. * This RGBE texture needs to store the information as a panorama.
  89547. *
  89548. * More information on this format are available here:
  89549. * https://en.wikipedia.org/wiki/RGBE_image_format
  89550. *
  89551. * @param buffer The binary file stored in an array buffer.
  89552. * @param size The expected size of the extracted cubemap.
  89553. * @return The Cube Map information.
  89554. */
  89555. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  89556. var uint8array = new Uint8Array(buffer);
  89557. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  89558. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89559. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  89560. return cubeMapData;
  89561. };
  89562. /**
  89563. * Returns the pixels data extracted from an RGBE texture.
  89564. * This pixels will be stored left to right up to down in the R G B order in one array.
  89565. *
  89566. * More information on this format are available here:
  89567. * https://en.wikipedia.org/wiki/RGBE_image_format
  89568. *
  89569. * @param uint8array The binary file stored in an array buffer.
  89570. * @param hdrInfo The header information of the file.
  89571. * @return The pixels data in RGB right to left up to down order.
  89572. */
  89573. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  89574. // Keep for multi format supports.
  89575. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89576. };
  89577. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  89578. var num_scanlines = hdrInfo.height;
  89579. var scanline_width = hdrInfo.width;
  89580. var a, b, c, d, count;
  89581. var dataIndex = hdrInfo.dataPosition;
  89582. var index = 0, endIndex = 0, i = 0;
  89583. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  89584. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  89585. // 3 channels of 4 bytes per pixel in float.
  89586. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  89587. var resultArray = new Float32Array(resultBuffer);
  89588. // read in each successive scanline
  89589. while (num_scanlines > 0) {
  89590. a = uint8array[dataIndex++];
  89591. b = uint8array[dataIndex++];
  89592. c = uint8array[dataIndex++];
  89593. d = uint8array[dataIndex++];
  89594. if (a != 2 || b != 2 || (c & 0x80)) {
  89595. // this file is not run length encoded
  89596. throw "HDR Bad header format, not RLE";
  89597. }
  89598. if (((c << 8) | d) != scanline_width) {
  89599. throw "HDR Bad header format, wrong scan line width";
  89600. }
  89601. index = 0;
  89602. // read each of the four channels for the scanline into the buffer
  89603. for (i = 0; i < 4; i++) {
  89604. endIndex = (i + 1) * scanline_width;
  89605. while (index < endIndex) {
  89606. a = uint8array[dataIndex++];
  89607. b = uint8array[dataIndex++];
  89608. if (a > 128) {
  89609. // a run of the same value
  89610. count = a - 128;
  89611. if ((count == 0) || (count > endIndex - index)) {
  89612. throw "HDR Bad Format, bad scanline data (run)";
  89613. }
  89614. while (count-- > 0) {
  89615. scanLineArray[index++] = b;
  89616. }
  89617. }
  89618. else {
  89619. // a non-run
  89620. count = a;
  89621. if ((count == 0) || (count > endIndex - index)) {
  89622. throw "HDR Bad Format, bad scanline data (non-run)";
  89623. }
  89624. scanLineArray[index++] = b;
  89625. if (--count > 0) {
  89626. for (var j = 0; j < count; j++) {
  89627. scanLineArray[index++] = uint8array[dataIndex++];
  89628. }
  89629. }
  89630. }
  89631. }
  89632. }
  89633. // now convert data from buffer into floats
  89634. for (i = 0; i < scanline_width; i++) {
  89635. a = scanLineArray[i];
  89636. b = scanLineArray[i + scanline_width];
  89637. c = scanLineArray[i + 2 * scanline_width];
  89638. d = scanLineArray[i + 3 * scanline_width];
  89639. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  89640. }
  89641. num_scanlines--;
  89642. }
  89643. return resultArray;
  89644. };
  89645. return HDRTools;
  89646. }());
  89647. BABYLON.HDRTools = HDRTools;
  89648. })(BABYLON || (BABYLON = {}));
  89649. //# sourceMappingURL=babylon.hdr.js.map
  89650. var BABYLON;
  89651. (function (BABYLON) {
  89652. /**
  89653. * This represents a texture coming from an HDR input.
  89654. *
  89655. * The only supported format is currently panorama picture stored in RGBE format.
  89656. * Example of such files can be found on HDRLib: http://hdrlib.com/
  89657. */
  89658. var HDRCubeTexture = /** @class */ (function (_super) {
  89659. __extends(HDRCubeTexture, _super);
  89660. /**
  89661. * Instantiates an HDRTexture from the following parameters.
  89662. *
  89663. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  89664. * @param scene The scene the texture will be used in
  89665. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  89666. * @param noMipmap Forces to not generate the mipmap if true
  89667. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  89668. * @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)
  89669. * @param reserved Reserved flag for internal use.
  89670. */
  89671. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  89672. if (noMipmap === void 0) { noMipmap = false; }
  89673. if (generateHarmonics === void 0) { generateHarmonics = true; }
  89674. if (gammaSpace === void 0) { gammaSpace = false; }
  89675. if (reserved === void 0) { reserved = false; }
  89676. if (onLoad === void 0) { onLoad = null; }
  89677. if (onError === void 0) { onError = null; }
  89678. var _this = _super.call(this, scene) || this;
  89679. _this._generateHarmonics = true;
  89680. _this._onLoad = null;
  89681. _this._onError = null;
  89682. /**
  89683. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  89684. */
  89685. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  89686. _this._isBlocking = true;
  89687. _this._rotationY = 0;
  89688. /**
  89689. * Gets or sets the center of the bounding box associated with the cube texture
  89690. * It must define where the camera used to render the texture was set
  89691. */
  89692. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  89693. if (!url) {
  89694. return _this;
  89695. }
  89696. _this.name = url;
  89697. _this.url = url;
  89698. _this.hasAlpha = false;
  89699. _this.isCube = true;
  89700. _this._textureMatrix = BABYLON.Matrix.Identity();
  89701. _this._onLoad = onLoad;
  89702. _this._onError = onError;
  89703. _this.gammaSpace = gammaSpace;
  89704. _this._noMipmap = noMipmap;
  89705. _this._size = size;
  89706. _this._texture = _this._getFromCache(url, _this._noMipmap);
  89707. if (!_this._texture) {
  89708. if (!scene.useDelayedTextureLoading) {
  89709. _this.loadTexture();
  89710. }
  89711. else {
  89712. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89713. }
  89714. }
  89715. return _this;
  89716. }
  89717. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  89718. /**
  89719. * Gets wether or not the texture is blocking during loading.
  89720. */
  89721. get: function () {
  89722. return this._isBlocking;
  89723. },
  89724. /**
  89725. * Sets wether or not the texture is blocking during loading.
  89726. */
  89727. set: function (value) {
  89728. this._isBlocking = value;
  89729. },
  89730. enumerable: true,
  89731. configurable: true
  89732. });
  89733. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  89734. /**
  89735. * Gets texture matrix rotation angle around Y axis radians.
  89736. */
  89737. get: function () {
  89738. return this._rotationY;
  89739. },
  89740. /**
  89741. * Sets texture matrix rotation angle around Y axis in radians.
  89742. */
  89743. set: function (value) {
  89744. this._rotationY = value;
  89745. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  89746. },
  89747. enumerable: true,
  89748. configurable: true
  89749. });
  89750. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  89751. get: function () {
  89752. return this._boundingBoxSize;
  89753. },
  89754. /**
  89755. * Gets or sets the size of the bounding box associated with the cube texture
  89756. * When defined, the cubemap will switch to local mode
  89757. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  89758. * @example https://www.babylonjs-playground.com/#RNASML
  89759. */
  89760. set: function (value) {
  89761. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  89762. return;
  89763. }
  89764. this._boundingBoxSize = value;
  89765. var scene = this.getScene();
  89766. if (scene) {
  89767. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  89768. }
  89769. },
  89770. enumerable: true,
  89771. configurable: true
  89772. });
  89773. /**
  89774. * Occurs when the file is raw .hdr file.
  89775. */
  89776. HDRCubeTexture.prototype.loadTexture = function () {
  89777. var _this = this;
  89778. var callback = function (buffer) {
  89779. _this.lodGenerationOffset = 0.0;
  89780. _this.lodGenerationScale = 0.8;
  89781. var scene = _this.getScene();
  89782. if (!scene) {
  89783. return null;
  89784. }
  89785. // Extract the raw linear data.
  89786. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  89787. // Generate harmonics if needed.
  89788. if (_this._generateHarmonics) {
  89789. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  89790. _this.sphericalPolynomial = sphericalPolynomial;
  89791. }
  89792. var results = [];
  89793. var byteArray = null;
  89794. // Push each faces.
  89795. for (var j = 0; j < 6; j++) {
  89796. // Create uintarray fallback.
  89797. if (!scene.getEngine().getCaps().textureFloat) {
  89798. // 3 channels of 1 bytes per pixel in bytes.
  89799. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  89800. byteArray = new Uint8Array(byteBuffer);
  89801. }
  89802. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  89803. // If special cases.
  89804. if (_this.gammaSpace || byteArray) {
  89805. for (var i = 0; i < _this._size * _this._size; i++) {
  89806. // Put in gamma space if requested.
  89807. if (_this.gammaSpace) {
  89808. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  89809. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  89810. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  89811. }
  89812. // Convert to int texture for fallback.
  89813. if (byteArray) {
  89814. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  89815. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  89816. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  89817. // May use luminance instead if the result is not accurate.
  89818. var max = Math.max(Math.max(r, g), b);
  89819. if (max > 255) {
  89820. var scale = 255 / max;
  89821. r *= scale;
  89822. g *= scale;
  89823. b *= scale;
  89824. }
  89825. byteArray[(i * 3) + 0] = r;
  89826. byteArray[(i * 3) + 1] = g;
  89827. byteArray[(i * 3) + 2] = b;
  89828. }
  89829. }
  89830. }
  89831. if (byteArray) {
  89832. results.push(byteArray);
  89833. }
  89834. else {
  89835. results.push(dataFace);
  89836. }
  89837. }
  89838. return results;
  89839. };
  89840. var scene = this.getScene();
  89841. if (scene) {
  89842. 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);
  89843. }
  89844. };
  89845. HDRCubeTexture.prototype.clone = function () {
  89846. var scene = this.getScene();
  89847. if (!scene) {
  89848. return this;
  89849. }
  89850. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  89851. // Base texture
  89852. newTexture.level = this.level;
  89853. newTexture.wrapU = this.wrapU;
  89854. newTexture.wrapV = this.wrapV;
  89855. newTexture.coordinatesIndex = this.coordinatesIndex;
  89856. newTexture.coordinatesMode = this.coordinatesMode;
  89857. return newTexture;
  89858. };
  89859. // Methods
  89860. HDRCubeTexture.prototype.delayLoad = function () {
  89861. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89862. return;
  89863. }
  89864. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89865. this._texture = this._getFromCache(this.url, this._noMipmap);
  89866. if (!this._texture) {
  89867. this.loadTexture();
  89868. }
  89869. };
  89870. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  89871. return this._textureMatrix;
  89872. };
  89873. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  89874. this._textureMatrix = value;
  89875. };
  89876. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89877. var texture = null;
  89878. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89879. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  89880. texture.name = parsedTexture.name;
  89881. texture.hasAlpha = parsedTexture.hasAlpha;
  89882. texture.level = parsedTexture.level;
  89883. texture.coordinatesMode = parsedTexture.coordinatesMode;
  89884. texture.isBlocking = parsedTexture.isBlocking;
  89885. }
  89886. if (texture) {
  89887. if (parsedTexture.boundingBoxPosition) {
  89888. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  89889. }
  89890. if (parsedTexture.boundingBoxSize) {
  89891. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  89892. }
  89893. if (parsedTexture.rotationY) {
  89894. texture.rotationY = parsedTexture.rotationY;
  89895. }
  89896. }
  89897. return texture;
  89898. };
  89899. HDRCubeTexture.prototype.serialize = function () {
  89900. if (!this.name) {
  89901. return null;
  89902. }
  89903. var serializationObject = {};
  89904. serializationObject.name = this.name;
  89905. serializationObject.hasAlpha = this.hasAlpha;
  89906. serializationObject.isCube = true;
  89907. serializationObject.level = this.level;
  89908. serializationObject.size = this._size;
  89909. serializationObject.coordinatesMode = this.coordinatesMode;
  89910. serializationObject.useInGammaSpace = this.gammaSpace;
  89911. serializationObject.generateHarmonics = this._generateHarmonics;
  89912. serializationObject.customType = "BABYLON.HDRCubeTexture";
  89913. serializationObject.noMipmap = this._noMipmap;
  89914. serializationObject.isBlocking = this._isBlocking;
  89915. serializationObject.rotationY = this._rotationY;
  89916. return serializationObject;
  89917. };
  89918. HDRCubeTexture._facesMapping = [
  89919. "right",
  89920. "left",
  89921. "up",
  89922. "down",
  89923. "front",
  89924. "back"
  89925. ];
  89926. return HDRCubeTexture;
  89927. }(BABYLON.BaseTexture));
  89928. BABYLON.HDRCubeTexture = HDRCubeTexture;
  89929. })(BABYLON || (BABYLON = {}));
  89930. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  89931. var BABYLON;
  89932. (function (BABYLON) {
  89933. /**
  89934. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  89935. */
  89936. var PanoramaToCubeMapTools = /** @class */ (function () {
  89937. function PanoramaToCubeMapTools() {
  89938. }
  89939. /**
  89940. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  89941. *
  89942. * @param float32Array The source data.
  89943. * @param inputWidth The width of the input panorama.
  89944. * @param inputhHeight The height of the input panorama.
  89945. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  89946. * @return The cubemap data
  89947. */
  89948. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  89949. if (!float32Array) {
  89950. throw "ConvertPanoramaToCubemap: input cannot be null";
  89951. }
  89952. if (float32Array.length != inputWidth * inputHeight * 3) {
  89953. throw "ConvertPanoramaToCubemap: input size is wrong";
  89954. }
  89955. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  89956. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  89957. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  89958. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  89959. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  89960. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  89961. return {
  89962. front: textureFront,
  89963. back: textureBack,
  89964. left: textureLeft,
  89965. right: textureRight,
  89966. up: textureUp,
  89967. down: textureDown,
  89968. size: size,
  89969. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89970. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  89971. gammaSpace: false,
  89972. };
  89973. };
  89974. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  89975. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  89976. var textureArray = new Float32Array(buffer);
  89977. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  89978. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  89979. var dy = 1 / texSize;
  89980. var fy = 0;
  89981. for (var y = 0; y < texSize; y++) {
  89982. var xv1 = faceData[0];
  89983. var xv2 = faceData[2];
  89984. for (var x = 0; x < texSize; x++) {
  89985. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  89986. v.normalize();
  89987. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  89988. // 3 channels per pixels
  89989. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  89990. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  89991. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  89992. xv1 = xv1.add(rotDX1);
  89993. xv2 = xv2.add(rotDX2);
  89994. }
  89995. fy += dy;
  89996. }
  89997. return textureArray;
  89998. };
  89999. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  90000. var theta = Math.atan2(vDir.z, vDir.x);
  90001. var phi = Math.acos(vDir.y);
  90002. while (theta < -Math.PI)
  90003. theta += 2 * Math.PI;
  90004. while (theta > Math.PI)
  90005. theta -= 2 * Math.PI;
  90006. var dx = theta / Math.PI;
  90007. var dy = phi / Math.PI;
  90008. // recenter.
  90009. dx = dx * 0.5 + 0.5;
  90010. var px = Math.round(dx * inputWidth);
  90011. if (px < 0)
  90012. px = 0;
  90013. else if (px >= inputWidth)
  90014. px = inputWidth - 1;
  90015. var py = Math.round(dy * inputHeight);
  90016. if (py < 0)
  90017. py = 0;
  90018. else if (py >= inputHeight)
  90019. py = inputHeight - 1;
  90020. var inputY = (inputHeight - py - 1);
  90021. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  90022. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  90023. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  90024. return {
  90025. r: r,
  90026. g: g,
  90027. b: b
  90028. };
  90029. };
  90030. PanoramaToCubeMapTools.FACE_FRONT = [
  90031. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90032. new BABYLON.Vector3(1.0, -1.0, -1.0),
  90033. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  90034. new BABYLON.Vector3(1.0, 1.0, -1.0)
  90035. ];
  90036. PanoramaToCubeMapTools.FACE_BACK = [
  90037. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90038. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90039. new BABYLON.Vector3(1.0, 1.0, 1.0),
  90040. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  90041. ];
  90042. PanoramaToCubeMapTools.FACE_RIGHT = [
  90043. new BABYLON.Vector3(1.0, -1.0, -1.0),
  90044. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90045. new BABYLON.Vector3(1.0, 1.0, -1.0),
  90046. new BABYLON.Vector3(1.0, 1.0, 1.0)
  90047. ];
  90048. PanoramaToCubeMapTools.FACE_LEFT = [
  90049. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90050. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90051. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  90052. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  90053. ];
  90054. PanoramaToCubeMapTools.FACE_DOWN = [
  90055. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  90056. new BABYLON.Vector3(1.0, 1.0, -1.0),
  90057. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  90058. new BABYLON.Vector3(1.0, 1.0, 1.0)
  90059. ];
  90060. PanoramaToCubeMapTools.FACE_UP = [
  90061. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90062. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90063. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90064. new BABYLON.Vector3(1.0, -1.0, -1.0)
  90065. ];
  90066. return PanoramaToCubeMapTools;
  90067. }());
  90068. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  90069. })(BABYLON || (BABYLON = {}));
  90070. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  90071. var BABYLON;
  90072. (function (BABYLON) {
  90073. var IndexedVector2 = /** @class */ (function (_super) {
  90074. __extends(IndexedVector2, _super);
  90075. function IndexedVector2(original, index) {
  90076. var _this = _super.call(this, original.x, original.y) || this;
  90077. _this.index = index;
  90078. return _this;
  90079. }
  90080. return IndexedVector2;
  90081. }(BABYLON.Vector2));
  90082. var PolygonPoints = /** @class */ (function () {
  90083. function PolygonPoints() {
  90084. this.elements = new Array();
  90085. }
  90086. PolygonPoints.prototype.add = function (originalPoints) {
  90087. var _this = this;
  90088. var result = new Array();
  90089. originalPoints.forEach(function (point) {
  90090. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  90091. var newPoint = new IndexedVector2(point, _this.elements.length);
  90092. result.push(newPoint);
  90093. _this.elements.push(newPoint);
  90094. }
  90095. });
  90096. return result;
  90097. };
  90098. PolygonPoints.prototype.computeBounds = function () {
  90099. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  90100. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  90101. this.elements.forEach(function (point) {
  90102. // x
  90103. if (point.x < lmin.x) {
  90104. lmin.x = point.x;
  90105. }
  90106. else if (point.x > lmax.x) {
  90107. lmax.x = point.x;
  90108. }
  90109. // y
  90110. if (point.y < lmin.y) {
  90111. lmin.y = point.y;
  90112. }
  90113. else if (point.y > lmax.y) {
  90114. lmax.y = point.y;
  90115. }
  90116. });
  90117. return {
  90118. min: lmin,
  90119. max: lmax,
  90120. width: lmax.x - lmin.x,
  90121. height: lmax.y - lmin.y
  90122. };
  90123. };
  90124. return PolygonPoints;
  90125. }());
  90126. var Polygon = /** @class */ (function () {
  90127. function Polygon() {
  90128. }
  90129. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  90130. return [
  90131. new BABYLON.Vector2(xmin, ymin),
  90132. new BABYLON.Vector2(xmax, ymin),
  90133. new BABYLON.Vector2(xmax, ymax),
  90134. new BABYLON.Vector2(xmin, ymax)
  90135. ];
  90136. };
  90137. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  90138. if (cx === void 0) { cx = 0; }
  90139. if (cy === void 0) { cy = 0; }
  90140. if (numberOfSides === void 0) { numberOfSides = 32; }
  90141. var result = new Array();
  90142. var angle = 0;
  90143. var increment = (Math.PI * 2) / numberOfSides;
  90144. for (var i = 0; i < numberOfSides; i++) {
  90145. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  90146. angle -= increment;
  90147. }
  90148. return result;
  90149. };
  90150. Polygon.Parse = function (input) {
  90151. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  90152. var i, result = [];
  90153. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  90154. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  90155. }
  90156. return result;
  90157. };
  90158. Polygon.StartingAt = function (x, y) {
  90159. return BABYLON.Path2.StartingAt(x, y);
  90160. };
  90161. return Polygon;
  90162. }());
  90163. BABYLON.Polygon = Polygon;
  90164. var PolygonMeshBuilder = /** @class */ (function () {
  90165. function PolygonMeshBuilder(name, contours, scene) {
  90166. this._points = new PolygonPoints();
  90167. this._outlinepoints = new PolygonPoints();
  90168. this._holes = new Array();
  90169. this._epoints = new Array();
  90170. this._eholes = new Array();
  90171. this._name = name;
  90172. this._scene = scene;
  90173. var points;
  90174. if (contours instanceof BABYLON.Path2) {
  90175. points = contours.getPoints();
  90176. }
  90177. else {
  90178. points = contours;
  90179. }
  90180. this._addToepoint(points);
  90181. this._points.add(points);
  90182. this._outlinepoints.add(points);
  90183. if (typeof earcut === 'undefined') {
  90184. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  90185. }
  90186. }
  90187. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  90188. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  90189. var p = points_1[_i];
  90190. this._epoints.push(p.x, p.y);
  90191. }
  90192. };
  90193. PolygonMeshBuilder.prototype.addHole = function (hole) {
  90194. this._points.add(hole);
  90195. var holepoints = new PolygonPoints();
  90196. holepoints.add(hole);
  90197. this._holes.push(holepoints);
  90198. this._eholes.push(this._epoints.length / 2);
  90199. this._addToepoint(hole);
  90200. return this;
  90201. };
  90202. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  90203. var _this = this;
  90204. if (updatable === void 0) { updatable = false; }
  90205. if (depth === void 0) { depth = 0; }
  90206. var result = new BABYLON.Mesh(this._name, this._scene);
  90207. var normals = new Array();
  90208. var positions = new Array();
  90209. var uvs = new Array();
  90210. var bounds = this._points.computeBounds();
  90211. this._points.elements.forEach(function (p) {
  90212. normals.push(0, 1.0, 0);
  90213. positions.push(p.x, 0, p.y);
  90214. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  90215. });
  90216. var indices = new Array();
  90217. var res = earcut(this._epoints, this._eholes, 2);
  90218. for (var i = 0; i < res.length; i++) {
  90219. indices.push(res[i]);
  90220. }
  90221. if (depth > 0) {
  90222. var positionscount = (positions.length / 3); //get the current pointcount
  90223. this._points.elements.forEach(function (p) {
  90224. normals.push(0, -1.0, 0);
  90225. positions.push(p.x, -depth, p.y);
  90226. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  90227. });
  90228. var totalCount = indices.length;
  90229. for (var i = 0; i < totalCount; i += 3) {
  90230. var i0 = indices[i + 0];
  90231. var i1 = indices[i + 1];
  90232. var i2 = indices[i + 2];
  90233. indices.push(i2 + positionscount);
  90234. indices.push(i1 + positionscount);
  90235. indices.push(i0 + positionscount);
  90236. }
  90237. //Add the sides
  90238. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  90239. this._holes.forEach(function (hole) {
  90240. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  90241. });
  90242. }
  90243. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  90244. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  90245. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  90246. result.setIndices(indices);
  90247. return result;
  90248. };
  90249. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  90250. var StartIndex = positions.length / 3;
  90251. var ulength = 0;
  90252. for (var i = 0; i < points.elements.length; i++) {
  90253. var p = points.elements[i];
  90254. var p1;
  90255. if ((i + 1) > points.elements.length - 1) {
  90256. p1 = points.elements[0];
  90257. }
  90258. else {
  90259. p1 = points.elements[i + 1];
  90260. }
  90261. positions.push(p.x, 0, p.y);
  90262. positions.push(p.x, -depth, p.y);
  90263. positions.push(p1.x, 0, p1.y);
  90264. positions.push(p1.x, -depth, p1.y);
  90265. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  90266. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  90267. var v3 = v2.subtract(v1);
  90268. var v4 = new BABYLON.Vector3(0, 1, 0);
  90269. var vn = BABYLON.Vector3.Cross(v3, v4);
  90270. vn = vn.normalize();
  90271. uvs.push(ulength / bounds.width, 0);
  90272. uvs.push(ulength / bounds.width, 1);
  90273. ulength += v3.length();
  90274. uvs.push((ulength / bounds.width), 0);
  90275. uvs.push((ulength / bounds.width), 1);
  90276. if (!flip) {
  90277. normals.push(-vn.x, -vn.y, -vn.z);
  90278. normals.push(-vn.x, -vn.y, -vn.z);
  90279. normals.push(-vn.x, -vn.y, -vn.z);
  90280. normals.push(-vn.x, -vn.y, -vn.z);
  90281. indices.push(StartIndex);
  90282. indices.push(StartIndex + 1);
  90283. indices.push(StartIndex + 2);
  90284. indices.push(StartIndex + 1);
  90285. indices.push(StartIndex + 3);
  90286. indices.push(StartIndex + 2);
  90287. }
  90288. else {
  90289. normals.push(vn.x, vn.y, vn.z);
  90290. normals.push(vn.x, vn.y, vn.z);
  90291. normals.push(vn.x, vn.y, vn.z);
  90292. normals.push(vn.x, vn.y, vn.z);
  90293. indices.push(StartIndex);
  90294. indices.push(StartIndex + 2);
  90295. indices.push(StartIndex + 1);
  90296. indices.push(StartIndex + 1);
  90297. indices.push(StartIndex + 2);
  90298. indices.push(StartIndex + 3);
  90299. }
  90300. StartIndex += 4;
  90301. }
  90302. ;
  90303. };
  90304. return PolygonMeshBuilder;
  90305. }());
  90306. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  90307. })(BABYLON || (BABYLON = {}));
  90308. //# sourceMappingURL=babylon.polygonMesh.js.map
  90309. var BABYLON;
  90310. (function (BABYLON) {
  90311. /**
  90312. * Unique ID when we import meshes from Babylon to CSG
  90313. */
  90314. var currentCSGMeshId = 0;
  90315. /**
  90316. * Represents a vertex of a polygon. Use your own vertex class instead of this
  90317. * one to provide additional features like texture coordinates and vertex
  90318. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  90319. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  90320. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  90321. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  90322. * is not used anywhere else.
  90323. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  90324. */
  90325. var Vertex = /** @class */ (function () {
  90326. /**
  90327. * Initializes the vertex
  90328. * @param pos The position of the vertex
  90329. * @param normal The normal of the vertex
  90330. * @param uv The texture coordinate of the vertex
  90331. */
  90332. function Vertex(
  90333. /**
  90334. * The position of the vertex
  90335. */
  90336. pos,
  90337. /**
  90338. * The normal of the vertex
  90339. */
  90340. normal,
  90341. /**
  90342. * The texture coordinate of the vertex
  90343. */
  90344. uv) {
  90345. this.pos = pos;
  90346. this.normal = normal;
  90347. this.uv = uv;
  90348. }
  90349. /**
  90350. * Make a clone, or deep copy, of the vertex
  90351. * @returns A new Vertex
  90352. */
  90353. Vertex.prototype.clone = function () {
  90354. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  90355. };
  90356. /**
  90357. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  90358. * orientation of a polygon is flipped.
  90359. */
  90360. Vertex.prototype.flip = function () {
  90361. this.normal = this.normal.scale(-1);
  90362. };
  90363. /**
  90364. * Create a new vertex between this vertex and `other` by linearly
  90365. * interpolating all properties using a parameter of `t`. Subclasses should
  90366. * override this to interpolate additional properties.
  90367. * @param other the vertex to interpolate against
  90368. * @param t The factor used to linearly interpolate between the vertices
  90369. */
  90370. Vertex.prototype.interpolate = function (other, t) {
  90371. 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));
  90372. };
  90373. return Vertex;
  90374. }());
  90375. /**
  90376. * Represents a plane in 3D space.
  90377. */
  90378. var Plane = /** @class */ (function () {
  90379. /**
  90380. * Initializes the plane
  90381. * @param normal The normal for the plane
  90382. * @param w
  90383. */
  90384. function Plane(normal, w) {
  90385. this.normal = normal;
  90386. this.w = w;
  90387. }
  90388. /**
  90389. * Construct a plane from three points
  90390. * @param a Point a
  90391. * @param b Point b
  90392. * @param c Point c
  90393. */
  90394. Plane.FromPoints = function (a, b, c) {
  90395. var v0 = c.subtract(a);
  90396. var v1 = b.subtract(a);
  90397. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  90398. return null;
  90399. }
  90400. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  90401. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  90402. };
  90403. /**
  90404. * Clone, or make a deep copy of the plane
  90405. * @returns a new Plane
  90406. */
  90407. Plane.prototype.clone = function () {
  90408. return new Plane(this.normal.clone(), this.w);
  90409. };
  90410. /**
  90411. * Flip the face of the plane
  90412. */
  90413. Plane.prototype.flip = function () {
  90414. this.normal.scaleInPlace(-1);
  90415. this.w = -this.w;
  90416. };
  90417. /**
  90418. * Split `polygon` by this plane if needed, then put the polygon or polygon
  90419. * fragments in the appropriate lists. Coplanar polygons go into either
  90420. `* coplanarFront` or `coplanarBack` depending on their orientation with
  90421. * respect to this plane. Polygons in front or in back of this plane go into
  90422. * either `front` or `back`
  90423. * @param polygon The polygon to be split
  90424. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  90425. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  90426. * @param front Will contain the polygons in front of the plane
  90427. * @param back Will contain the polygons begind the plane
  90428. */
  90429. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  90430. var COPLANAR = 0;
  90431. var FRONT = 1;
  90432. var BACK = 2;
  90433. var SPANNING = 3;
  90434. // Classify each point as well as the entire polygon into one of the above
  90435. // four classes.
  90436. var polygonType = 0;
  90437. var types = [];
  90438. var i;
  90439. var t;
  90440. for (i = 0; i < polygon.vertices.length; i++) {
  90441. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  90442. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  90443. polygonType |= type;
  90444. types.push(type);
  90445. }
  90446. // Put the polygon in the correct list, splitting it when necessary
  90447. switch (polygonType) {
  90448. case COPLANAR:
  90449. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  90450. break;
  90451. case FRONT:
  90452. front.push(polygon);
  90453. break;
  90454. case BACK:
  90455. back.push(polygon);
  90456. break;
  90457. case SPANNING:
  90458. var f = [], b = [];
  90459. for (i = 0; i < polygon.vertices.length; i++) {
  90460. var j = (i + 1) % polygon.vertices.length;
  90461. var ti = types[i], tj = types[j];
  90462. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  90463. if (ti !== BACK)
  90464. f.push(vi);
  90465. if (ti !== FRONT)
  90466. b.push(ti !== BACK ? vi.clone() : vi);
  90467. if ((ti | tj) === SPANNING) {
  90468. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  90469. var v = vi.interpolate(vj, t);
  90470. f.push(v);
  90471. b.push(v.clone());
  90472. }
  90473. }
  90474. var poly;
  90475. if (f.length >= 3) {
  90476. poly = new Polygon(f, polygon.shared);
  90477. if (poly.plane)
  90478. front.push(poly);
  90479. }
  90480. if (b.length >= 3) {
  90481. poly = new Polygon(b, polygon.shared);
  90482. if (poly.plane)
  90483. back.push(poly);
  90484. }
  90485. break;
  90486. }
  90487. };
  90488. /**
  90489. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  90490. * point is on the plane
  90491. */
  90492. Plane.EPSILON = 1e-5;
  90493. return Plane;
  90494. }());
  90495. /**
  90496. * Represents a convex polygon. The vertices used to initialize a polygon must
  90497. * be coplanar and form a convex loop.
  90498. *
  90499. * Each convex polygon has a `shared` property, which is shared between all
  90500. * polygons that are clones of each other or were split from the same polygon.
  90501. * This can be used to define per-polygon properties (such as surface color)
  90502. */
  90503. var Polygon = /** @class */ (function () {
  90504. /**
  90505. * Initializes the polygon
  90506. * @param vertices The vertices of the polygon
  90507. * @param shared The properties shared across all polygons
  90508. */
  90509. function Polygon(vertices, shared) {
  90510. this.vertices = vertices;
  90511. this.shared = shared;
  90512. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  90513. }
  90514. /**
  90515. * Clones, or makes a deep copy, or the polygon
  90516. */
  90517. Polygon.prototype.clone = function () {
  90518. var vertices = this.vertices.map(function (v) { return v.clone(); });
  90519. return new Polygon(vertices, this.shared);
  90520. };
  90521. /**
  90522. * Flips the faces of the polygon
  90523. */
  90524. Polygon.prototype.flip = function () {
  90525. this.vertices.reverse().map(function (v) { v.flip(); });
  90526. this.plane.flip();
  90527. };
  90528. return Polygon;
  90529. }());
  90530. /**
  90531. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  90532. * by picking a polygon to split along. That polygon (and all other coplanar
  90533. * polygons) are added directly to that node and the other polygons are added to
  90534. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  90535. * no distinction between internal and leaf nodes
  90536. */
  90537. var Node = /** @class */ (function () {
  90538. /**
  90539. * Initializes the node
  90540. * @param polygons A collection of polygons held in the node
  90541. */
  90542. function Node(polygons) {
  90543. this.plane = null;
  90544. this.front = null;
  90545. this.back = null;
  90546. this.polygons = new Array();
  90547. if (polygons) {
  90548. this.build(polygons);
  90549. }
  90550. }
  90551. /**
  90552. * Clones, or makes a deep copy, of the node
  90553. * @returns The cloned node
  90554. */
  90555. Node.prototype.clone = function () {
  90556. var node = new Node();
  90557. node.plane = this.plane && this.plane.clone();
  90558. node.front = this.front && this.front.clone();
  90559. node.back = this.back && this.back.clone();
  90560. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  90561. return node;
  90562. };
  90563. /**
  90564. * Convert solid space to empty space and empty space to solid space
  90565. */
  90566. Node.prototype.invert = function () {
  90567. for (var i = 0; i < this.polygons.length; i++) {
  90568. this.polygons[i].flip();
  90569. }
  90570. if (this.plane) {
  90571. this.plane.flip();
  90572. }
  90573. if (this.front) {
  90574. this.front.invert();
  90575. }
  90576. if (this.back) {
  90577. this.back.invert();
  90578. }
  90579. var temp = this.front;
  90580. this.front = this.back;
  90581. this.back = temp;
  90582. };
  90583. /**
  90584. * Recursively remove all polygons in `polygons` that are inside this BSP
  90585. * tree.
  90586. * @param polygons Polygons to remove from the BSP
  90587. * @returns Polygons clipped from the BSP
  90588. */
  90589. Node.prototype.clipPolygons = function (polygons) {
  90590. if (!this.plane)
  90591. return polygons.slice();
  90592. var front = new Array(), back = new Array();
  90593. for (var i = 0; i < polygons.length; i++) {
  90594. this.plane.splitPolygon(polygons[i], front, back, front, back);
  90595. }
  90596. if (this.front) {
  90597. front = this.front.clipPolygons(front);
  90598. }
  90599. if (this.back) {
  90600. back = this.back.clipPolygons(back);
  90601. }
  90602. else {
  90603. back = [];
  90604. }
  90605. return front.concat(back);
  90606. };
  90607. /**
  90608. * Remove all polygons in this BSP tree that are inside the other BSP tree
  90609. * `bsp`.
  90610. * @param bsp BSP containing polygons to remove from this BSP
  90611. */
  90612. Node.prototype.clipTo = function (bsp) {
  90613. this.polygons = bsp.clipPolygons(this.polygons);
  90614. if (this.front)
  90615. this.front.clipTo(bsp);
  90616. if (this.back)
  90617. this.back.clipTo(bsp);
  90618. };
  90619. /**
  90620. * Return a list of all polygons in this BSP tree
  90621. * @returns List of all polygons in this BSP tree
  90622. */
  90623. Node.prototype.allPolygons = function () {
  90624. var polygons = this.polygons.slice();
  90625. if (this.front)
  90626. polygons = polygons.concat(this.front.allPolygons());
  90627. if (this.back)
  90628. polygons = polygons.concat(this.back.allPolygons());
  90629. return polygons;
  90630. };
  90631. /**
  90632. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  90633. * new polygons are filtered down to the bottom of the tree and become new
  90634. * nodes there. Each set of polygons is partitioned using the first polygon
  90635. * (no heuristic is used to pick a good split)
  90636. * @param polygons Polygons used to construct the BSP tree
  90637. */
  90638. Node.prototype.build = function (polygons) {
  90639. if (!polygons.length)
  90640. return;
  90641. if (!this.plane)
  90642. this.plane = polygons[0].plane.clone();
  90643. var front = new Array(), back = new Array();
  90644. for (var i = 0; i < polygons.length; i++) {
  90645. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  90646. }
  90647. if (front.length) {
  90648. if (!this.front)
  90649. this.front = new Node();
  90650. this.front.build(front);
  90651. }
  90652. if (back.length) {
  90653. if (!this.back)
  90654. this.back = new Node();
  90655. this.back.build(back);
  90656. }
  90657. };
  90658. return Node;
  90659. }());
  90660. /**
  90661. * Class for building Constructive Solid Geometry
  90662. */
  90663. var CSG = /** @class */ (function () {
  90664. function CSG() {
  90665. this.polygons = new Array();
  90666. }
  90667. /**
  90668. * Convert the BABYLON.Mesh to BABYLON.CSG
  90669. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  90670. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  90671. */
  90672. CSG.FromMesh = function (mesh) {
  90673. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  90674. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  90675. if (mesh instanceof BABYLON.Mesh) {
  90676. mesh.computeWorldMatrix(true);
  90677. matrix = mesh.getWorldMatrix();
  90678. meshPosition = mesh.position.clone();
  90679. meshRotation = mesh.rotation.clone();
  90680. if (mesh.rotationQuaternion) {
  90681. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  90682. }
  90683. meshScaling = mesh.scaling.clone();
  90684. }
  90685. else {
  90686. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  90687. }
  90688. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90689. var subMeshes = mesh.subMeshes;
  90690. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  90691. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  90692. vertices = [];
  90693. for (var j = 0; j < 3; j++) {
  90694. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  90695. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  90696. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  90697. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  90698. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  90699. vertex = new Vertex(position, normal, uv);
  90700. vertices.push(vertex);
  90701. }
  90702. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  90703. // To handle the case of degenerated triangle
  90704. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  90705. if (polygon.plane)
  90706. polygons.push(polygon);
  90707. }
  90708. }
  90709. var csg = CSG.FromPolygons(polygons);
  90710. csg.matrix = matrix;
  90711. csg.position = meshPosition;
  90712. csg.rotation = meshRotation;
  90713. csg.scaling = meshScaling;
  90714. csg.rotationQuaternion = meshRotationQuaternion;
  90715. currentCSGMeshId++;
  90716. return csg;
  90717. };
  90718. /**
  90719. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  90720. * @param polygons Polygons used to construct a BABYLON.CSG solid
  90721. */
  90722. CSG.FromPolygons = function (polygons) {
  90723. var csg = new CSG();
  90724. csg.polygons = polygons;
  90725. return csg;
  90726. };
  90727. /**
  90728. * Clones, or makes a deep copy, of the BABYLON.CSG
  90729. * @returns A new BABYLON.CSG
  90730. */
  90731. CSG.prototype.clone = function () {
  90732. var csg = new CSG();
  90733. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  90734. csg.copyTransformAttributes(this);
  90735. return csg;
  90736. };
  90737. /**
  90738. * Unions this CSG with another CSG
  90739. * @param csg The CSG to union against this CSG
  90740. * @returns The unioned CSG
  90741. */
  90742. CSG.prototype.union = function (csg) {
  90743. var a = new Node(this.clone().polygons);
  90744. var b = new Node(csg.clone().polygons);
  90745. a.clipTo(b);
  90746. b.clipTo(a);
  90747. b.invert();
  90748. b.clipTo(a);
  90749. b.invert();
  90750. a.build(b.allPolygons());
  90751. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90752. };
  90753. /**
  90754. * Unions this CSG with another CSG in place
  90755. * @param csg The CSG to union against this CSG
  90756. */
  90757. CSG.prototype.unionInPlace = function (csg) {
  90758. var a = new Node(this.polygons);
  90759. var b = new Node(csg.polygons);
  90760. a.clipTo(b);
  90761. b.clipTo(a);
  90762. b.invert();
  90763. b.clipTo(a);
  90764. b.invert();
  90765. a.build(b.allPolygons());
  90766. this.polygons = a.allPolygons();
  90767. };
  90768. /**
  90769. * Subtracts this CSG with another CSG
  90770. * @param csg The CSG to subtract against this CSG
  90771. * @returns A new BABYLON.CSG
  90772. */
  90773. CSG.prototype.subtract = function (csg) {
  90774. var a = new Node(this.clone().polygons);
  90775. var b = new Node(csg.clone().polygons);
  90776. a.invert();
  90777. a.clipTo(b);
  90778. b.clipTo(a);
  90779. b.invert();
  90780. b.clipTo(a);
  90781. b.invert();
  90782. a.build(b.allPolygons());
  90783. a.invert();
  90784. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90785. };
  90786. /**
  90787. * Subtracts this CSG with another CSG in place
  90788. * @param csg The CSG to subtact against this CSG
  90789. */
  90790. CSG.prototype.subtractInPlace = function (csg) {
  90791. var a = new Node(this.polygons);
  90792. var b = new Node(csg.polygons);
  90793. a.invert();
  90794. a.clipTo(b);
  90795. b.clipTo(a);
  90796. b.invert();
  90797. b.clipTo(a);
  90798. b.invert();
  90799. a.build(b.allPolygons());
  90800. a.invert();
  90801. this.polygons = a.allPolygons();
  90802. };
  90803. /**
  90804. * Intersect this CSG with another CSG
  90805. * @param csg The CSG to intersect against this CSG
  90806. * @returns A new BABYLON.CSG
  90807. */
  90808. CSG.prototype.intersect = function (csg) {
  90809. var a = new Node(this.clone().polygons);
  90810. var b = new Node(csg.clone().polygons);
  90811. a.invert();
  90812. b.clipTo(a);
  90813. b.invert();
  90814. a.clipTo(b);
  90815. b.clipTo(a);
  90816. a.build(b.allPolygons());
  90817. a.invert();
  90818. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90819. };
  90820. /**
  90821. * Intersects this CSG with another CSG in place
  90822. * @param csg The CSG to intersect against this CSG
  90823. */
  90824. CSG.prototype.intersectInPlace = function (csg) {
  90825. var a = new Node(this.polygons);
  90826. var b = new Node(csg.polygons);
  90827. a.invert();
  90828. b.clipTo(a);
  90829. b.invert();
  90830. a.clipTo(b);
  90831. b.clipTo(a);
  90832. a.build(b.allPolygons());
  90833. a.invert();
  90834. this.polygons = a.allPolygons();
  90835. };
  90836. /**
  90837. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  90838. * not modified.
  90839. * @returns A new BABYLON.CSG solid with solid and empty space switched
  90840. */
  90841. CSG.prototype.inverse = function () {
  90842. var csg = this.clone();
  90843. csg.inverseInPlace();
  90844. return csg;
  90845. };
  90846. /**
  90847. * Inverses the BABYLON.CSG in place
  90848. */
  90849. CSG.prototype.inverseInPlace = function () {
  90850. this.polygons.map(function (p) { p.flip(); });
  90851. };
  90852. /**
  90853. * This is used to keep meshes transformations so they can be restored
  90854. * when we build back a Babylon Mesh
  90855. * NB : All CSG operations are performed in world coordinates
  90856. * @param csg The BABYLON.CSG to copy the transform attributes from
  90857. * @returns This BABYLON.CSG
  90858. */
  90859. CSG.prototype.copyTransformAttributes = function (csg) {
  90860. this.matrix = csg.matrix;
  90861. this.position = csg.position;
  90862. this.rotation = csg.rotation;
  90863. this.scaling = csg.scaling;
  90864. this.rotationQuaternion = csg.rotationQuaternion;
  90865. return this;
  90866. };
  90867. /**
  90868. * Build Raw mesh from CSG
  90869. * Coordinates here are in world space
  90870. * @param name The name of the mesh geometry
  90871. * @param scene The BABYLON.Scene
  90872. * @param keepSubMeshes Specifies if the submeshes should be kept
  90873. * @returns A new BABYLON.Mesh
  90874. */
  90875. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  90876. var matrix = this.matrix.clone();
  90877. matrix.invert();
  90878. 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;
  90879. if (keepSubMeshes) {
  90880. // Sort Polygons, since subMeshes are indices range
  90881. polygons.sort(function (a, b) {
  90882. if (a.shared.meshId === b.shared.meshId) {
  90883. return a.shared.subMeshId - b.shared.subMeshId;
  90884. }
  90885. else {
  90886. return a.shared.meshId - b.shared.meshId;
  90887. }
  90888. });
  90889. }
  90890. for (var i = 0, il = polygons.length; i < il; i++) {
  90891. polygon = polygons[i];
  90892. // Building SubMeshes
  90893. if (!subMesh_dict[polygon.shared.meshId]) {
  90894. subMesh_dict[polygon.shared.meshId] = {};
  90895. }
  90896. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  90897. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  90898. indexStart: +Infinity,
  90899. indexEnd: -Infinity,
  90900. materialIndex: polygon.shared.materialIndex
  90901. };
  90902. }
  90903. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  90904. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  90905. polygonIndices[0] = 0;
  90906. polygonIndices[1] = j - 1;
  90907. polygonIndices[2] = j;
  90908. for (var k = 0; k < 3; k++) {
  90909. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  90910. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  90911. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  90912. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  90913. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  90914. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  90915. // Check if 2 points can be merged
  90916. if (!(typeof vertex_idx !== 'undefined' &&
  90917. normals[vertex_idx * 3] === localNormal.x &&
  90918. normals[vertex_idx * 3 + 1] === localNormal.y &&
  90919. normals[vertex_idx * 3 + 2] === localNormal.z &&
  90920. uvs[vertex_idx * 2] === uv.x &&
  90921. uvs[vertex_idx * 2 + 1] === uv.y)) {
  90922. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  90923. uvs.push(uv.x, uv.y);
  90924. normals.push(normal.x, normal.y, normal.z);
  90925. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  90926. }
  90927. indices.push(vertex_idx);
  90928. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  90929. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  90930. currentIndex++;
  90931. }
  90932. }
  90933. }
  90934. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  90935. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  90936. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  90937. mesh.setIndices(indices, null);
  90938. if (keepSubMeshes) {
  90939. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  90940. var materialIndexOffset = 0, materialMaxIndex;
  90941. mesh.subMeshes = new Array();
  90942. for (var m in subMesh_dict) {
  90943. materialMaxIndex = -1;
  90944. for (var sm in subMesh_dict[m]) {
  90945. subMesh_obj = subMesh_dict[m][sm];
  90946. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  90947. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  90948. }
  90949. materialIndexOffset += ++materialMaxIndex;
  90950. }
  90951. }
  90952. return mesh;
  90953. };
  90954. /**
  90955. * Build Mesh from CSG taking material and transforms into account
  90956. * @param name The name of the BABYLON.Mesh
  90957. * @param material The material of the BABYLON.Mesh
  90958. * @param scene The BABYLON.Scene
  90959. * @param keepSubMeshes Specifies if submeshes should be kept
  90960. * @returns The new BABYLON.Mesh
  90961. */
  90962. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  90963. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  90964. mesh.material = material;
  90965. mesh.position.copyFrom(this.position);
  90966. mesh.rotation.copyFrom(this.rotation);
  90967. if (this.rotationQuaternion) {
  90968. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  90969. }
  90970. mesh.scaling.copyFrom(this.scaling);
  90971. mesh.computeWorldMatrix(true);
  90972. return mesh;
  90973. };
  90974. return CSG;
  90975. }());
  90976. BABYLON.CSG = CSG;
  90977. })(BABYLON || (BABYLON = {}));
  90978. //# sourceMappingURL=babylon.csg.js.map
  90979. var BABYLON;
  90980. (function (BABYLON) {
  90981. /**
  90982. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90983. * It controls one of the indiviual texture used in the effect.
  90984. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90985. */
  90986. var LensFlare = /** @class */ (function () {
  90987. /**
  90988. * Instantiates a new Lens Flare.
  90989. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90990. * It controls one of the indiviual texture used in the effect.
  90991. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90992. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  90993. * @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.
  90994. * @param color Define the lens color
  90995. * @param imgUrl Define the lens texture url
  90996. * @param system Define the `lensFlareSystem` this flare is part of
  90997. */
  90998. function LensFlare(
  90999. /**
  91000. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  91001. */
  91002. size,
  91003. /**
  91004. * 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.
  91005. */
  91006. position, color, imgUrl, system) {
  91007. this.size = size;
  91008. this.position = position;
  91009. /**
  91010. * Define the alpha mode to render this particular lens.
  91011. */
  91012. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  91013. this.color = color || new BABYLON.Color3(1, 1, 1);
  91014. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  91015. this._system = system;
  91016. system.lensFlares.push(this);
  91017. }
  91018. /**
  91019. * Creates a new Lens Flare.
  91020. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  91021. * It controls one of the indiviual texture used in the effect.
  91022. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91023. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  91024. * @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.
  91025. * @param color Define the lens color
  91026. * @param imgUrl Define the lens texture url
  91027. * @param system Define the `lensFlareSystem` this flare is part of
  91028. * @returns The newly created Lens Flare
  91029. */
  91030. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  91031. return new LensFlare(size, position, color, imgUrl, system);
  91032. };
  91033. /**
  91034. * Dispose and release the lens flare with its associated resources.
  91035. */
  91036. LensFlare.prototype.dispose = function () {
  91037. if (this.texture) {
  91038. this.texture.dispose();
  91039. }
  91040. // Remove from scene
  91041. var index = this._system.lensFlares.indexOf(this);
  91042. this._system.lensFlares.splice(index, 1);
  91043. };
  91044. ;
  91045. return LensFlare;
  91046. }());
  91047. BABYLON.LensFlare = LensFlare;
  91048. })(BABYLON || (BABYLON = {}));
  91049. //# sourceMappingURL=babylon.lensFlare.js.map
  91050. var BABYLON;
  91051. (function (BABYLON) {
  91052. // Adds the parser to the scene parsers.
  91053. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  91054. // Lens flares
  91055. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  91056. if (!container.lensFlareSystems) {
  91057. container.lensFlareSystems = new Array();
  91058. }
  91059. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  91060. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  91061. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  91062. container.lensFlareSystems.push(lf);
  91063. }
  91064. }
  91065. });
  91066. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  91067. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  91068. if (this.lensFlareSystems[index].name === name) {
  91069. return this.lensFlareSystems[index];
  91070. }
  91071. }
  91072. return null;
  91073. };
  91074. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  91075. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  91076. if (this.lensFlareSystems[index].id === id) {
  91077. return this.lensFlareSystems[index];
  91078. }
  91079. }
  91080. return null;
  91081. };
  91082. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  91083. var index = this.lensFlareSystems.indexOf(toRemove);
  91084. if (index !== -1) {
  91085. this.lensFlareSystems.splice(index, 1);
  91086. }
  91087. return index;
  91088. };
  91089. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  91090. this.lensFlareSystems.push(newLensFlareSystem);
  91091. };
  91092. /**
  91093. * Defines the lens flare scene component responsible to manage any lens flares
  91094. * in a given scene.
  91095. */
  91096. var LensFlareSystemSceneComponent = /** @class */ (function () {
  91097. /**
  91098. * Creates a new instance of the component for the given scene
  91099. * @param scene Defines the scene to register the component in
  91100. */
  91101. function LensFlareSystemSceneComponent(scene) {
  91102. /**
  91103. * The component name helpfull to identify the component in the list of scene components.
  91104. */
  91105. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  91106. this.scene = scene;
  91107. scene.lensFlareSystems = new Array();
  91108. }
  91109. /**
  91110. * Registers the component in a given scene
  91111. */
  91112. LensFlareSystemSceneComponent.prototype.register = function () {
  91113. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  91114. };
  91115. /**
  91116. * Rebuilds the elements related to this component in case of
  91117. * context lost for instance.
  91118. */
  91119. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  91120. // Nothing to do for lens flare
  91121. };
  91122. /**
  91123. * Adds all the element from the container to the scene
  91124. * @param container the container holding the elements
  91125. */
  91126. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  91127. var _this = this;
  91128. if (!container.lensFlareSystems) {
  91129. return;
  91130. }
  91131. container.lensFlareSystems.forEach(function (o) {
  91132. _this.scene.addLensFlareSystem(o);
  91133. });
  91134. };
  91135. /**
  91136. * Removes all the elements in the container from the scene
  91137. * @param container contains the elements to remove
  91138. */
  91139. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  91140. var _this = this;
  91141. if (!container.lensFlareSystems) {
  91142. return;
  91143. }
  91144. container.lensFlareSystems.forEach(function (o) {
  91145. _this.scene.removeLensFlareSystem(o);
  91146. });
  91147. };
  91148. /**
  91149. * Serializes the component data to the specified json object
  91150. * @param serializationObject The object to serialize to
  91151. */
  91152. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  91153. // Lens flares
  91154. serializationObject.lensFlareSystems = [];
  91155. var lensFlareSystems = this.scene.lensFlareSystems;
  91156. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  91157. var lensFlareSystem = lensFlareSystems_1[_i];
  91158. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  91159. }
  91160. };
  91161. /**
  91162. * Disposes the component and the associated ressources.
  91163. */
  91164. LensFlareSystemSceneComponent.prototype.dispose = function () {
  91165. var lensFlareSystems = this.scene.lensFlareSystems;
  91166. while (lensFlareSystems.length) {
  91167. lensFlareSystems[0].dispose();
  91168. }
  91169. };
  91170. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  91171. // Lens flares
  91172. if (this.scene.lensFlaresEnabled) {
  91173. var lensFlareSystems = this.scene.lensFlareSystems;
  91174. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  91175. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  91176. var lensFlareSystem = lensFlareSystems_2[_i];
  91177. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  91178. lensFlareSystem.render();
  91179. }
  91180. }
  91181. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  91182. }
  91183. };
  91184. return LensFlareSystemSceneComponent;
  91185. }());
  91186. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  91187. })(BABYLON || (BABYLON = {}));
  91188. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  91189. var BABYLON;
  91190. (function (BABYLON) {
  91191. /**
  91192. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  91193. * It is usually composed of several `BABYLON.lensFlare`.
  91194. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91195. */
  91196. var LensFlareSystem = /** @class */ (function () {
  91197. /**
  91198. * Instantiates a lens flare system.
  91199. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  91200. * It is usually composed of several `BABYLON.lensFlare`.
  91201. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91202. * @param name Define the name of the lens flare system in the scene
  91203. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  91204. * @param scene Define the scene the lens flare system belongs to
  91205. */
  91206. function LensFlareSystem(
  91207. /**
  91208. * Define the name of the lens flare system
  91209. */
  91210. name, emitter, scene) {
  91211. this.name = name;
  91212. /**
  91213. * List of lens flares used in this system.
  91214. */
  91215. this.lensFlares = new Array();
  91216. /**
  91217. * Define a limit from the border the lens flare can be visible.
  91218. */
  91219. this.borderLimit = 300;
  91220. /**
  91221. * Define a viewport border we do not want to see the lens flare in.
  91222. */
  91223. this.viewportBorder = 0;
  91224. /**
  91225. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  91226. */
  91227. this.layerMask = 0x0FFFFFFF;
  91228. this._vertexBuffers = {};
  91229. this._isEnabled = true;
  91230. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91231. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  91232. if (!component) {
  91233. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  91234. scene._addComponent(component);
  91235. }
  91236. this._emitter = emitter;
  91237. this.id = name;
  91238. scene.lensFlareSystems.push(this);
  91239. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  91240. var engine = scene.getEngine();
  91241. // VBO
  91242. var vertices = [];
  91243. vertices.push(1, 1);
  91244. vertices.push(-1, 1);
  91245. vertices.push(-1, -1);
  91246. vertices.push(1, -1);
  91247. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91248. // Indices
  91249. var indices = [];
  91250. indices.push(0);
  91251. indices.push(1);
  91252. indices.push(2);
  91253. indices.push(0);
  91254. indices.push(2);
  91255. indices.push(3);
  91256. this._indexBuffer = engine.createIndexBuffer(indices);
  91257. // Effects
  91258. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  91259. }
  91260. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  91261. /**
  91262. * Define if the lens flare system is enabled.
  91263. */
  91264. get: function () {
  91265. return this._isEnabled;
  91266. },
  91267. set: function (value) {
  91268. this._isEnabled = value;
  91269. },
  91270. enumerable: true,
  91271. configurable: true
  91272. });
  91273. /**
  91274. * Get the scene the effects belongs to.
  91275. * @returns the scene holding the lens flare system
  91276. */
  91277. LensFlareSystem.prototype.getScene = function () {
  91278. return this._scene;
  91279. };
  91280. /**
  91281. * Get the emitter of the lens flare system.
  91282. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  91283. * @returns the emitter of the lens flare system
  91284. */
  91285. LensFlareSystem.prototype.getEmitter = function () {
  91286. return this._emitter;
  91287. };
  91288. /**
  91289. * Set the emitter of the lens flare system.
  91290. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  91291. * @param newEmitter Define the new emitter of the system
  91292. */
  91293. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  91294. this._emitter = newEmitter;
  91295. };
  91296. /**
  91297. * Get the lens flare system emitter position.
  91298. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  91299. * @returns the position
  91300. */
  91301. LensFlareSystem.prototype.getEmitterPosition = function () {
  91302. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  91303. };
  91304. /**
  91305. * @hidden
  91306. */
  91307. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  91308. var position = this.getEmitterPosition();
  91309. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  91310. this._positionX = position.x;
  91311. this._positionY = position.y;
  91312. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  91313. if (this.viewportBorder > 0) {
  91314. globalViewport.x -= this.viewportBorder;
  91315. globalViewport.y -= this.viewportBorder;
  91316. globalViewport.width += this.viewportBorder * 2;
  91317. globalViewport.height += this.viewportBorder * 2;
  91318. position.x += this.viewportBorder;
  91319. position.y += this.viewportBorder;
  91320. this._positionX += this.viewportBorder;
  91321. this._positionY += this.viewportBorder;
  91322. }
  91323. if (position.z > 0) {
  91324. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  91325. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  91326. return true;
  91327. }
  91328. return true;
  91329. }
  91330. return false;
  91331. };
  91332. /** @hidden */
  91333. LensFlareSystem.prototype._isVisible = function () {
  91334. if (!this._isEnabled || !this._scene.activeCamera) {
  91335. return false;
  91336. }
  91337. var emitterPosition = this.getEmitterPosition();
  91338. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  91339. var distance = direction.length();
  91340. direction.normalize();
  91341. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  91342. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  91343. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  91344. };
  91345. /**
  91346. * @hidden
  91347. */
  91348. LensFlareSystem.prototype.render = function () {
  91349. if (!this._effect.isReady() || !this._scene.activeCamera)
  91350. return false;
  91351. var engine = this._scene.getEngine();
  91352. var viewport = this._scene.activeCamera.viewport;
  91353. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  91354. // Position
  91355. if (!this.computeEffectivePosition(globalViewport)) {
  91356. return false;
  91357. }
  91358. // Visibility
  91359. if (!this._isVisible()) {
  91360. return false;
  91361. }
  91362. // Intensity
  91363. var awayX;
  91364. var awayY;
  91365. if (this._positionX < this.borderLimit + globalViewport.x) {
  91366. awayX = this.borderLimit + globalViewport.x - this._positionX;
  91367. }
  91368. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  91369. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  91370. }
  91371. else {
  91372. awayX = 0;
  91373. }
  91374. if (this._positionY < this.borderLimit + globalViewport.y) {
  91375. awayY = this.borderLimit + globalViewport.y - this._positionY;
  91376. }
  91377. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  91378. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  91379. }
  91380. else {
  91381. awayY = 0;
  91382. }
  91383. var away = (awayX > awayY) ? awayX : awayY;
  91384. away -= this.viewportBorder;
  91385. if (away > this.borderLimit) {
  91386. away = this.borderLimit;
  91387. }
  91388. var intensity = 1.0 - (away / this.borderLimit);
  91389. if (intensity < 0) {
  91390. return false;
  91391. }
  91392. if (intensity > 1.0) {
  91393. intensity = 1.0;
  91394. }
  91395. if (this.viewportBorder > 0) {
  91396. globalViewport.x += this.viewportBorder;
  91397. globalViewport.y += this.viewportBorder;
  91398. globalViewport.width -= this.viewportBorder * 2;
  91399. globalViewport.height -= this.viewportBorder * 2;
  91400. this._positionX -= this.viewportBorder;
  91401. this._positionY -= this.viewportBorder;
  91402. }
  91403. // Position
  91404. var centerX = globalViewport.x + globalViewport.width / 2;
  91405. var centerY = globalViewport.y + globalViewport.height / 2;
  91406. var distX = centerX - this._positionX;
  91407. var distY = centerY - this._positionY;
  91408. // Effects
  91409. engine.enableEffect(this._effect);
  91410. engine.setState(false);
  91411. engine.setDepthBuffer(false);
  91412. // VBOs
  91413. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  91414. // Flares
  91415. for (var index = 0; index < this.lensFlares.length; index++) {
  91416. var flare = this.lensFlares[index];
  91417. engine.setAlphaMode(flare.alphaMode);
  91418. var x = centerX - (distX * flare.position);
  91419. var y = centerY - (distY * flare.position);
  91420. var cw = flare.size;
  91421. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  91422. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  91423. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  91424. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  91425. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  91426. // Texture
  91427. this._effect.setTexture("textureSampler", flare.texture);
  91428. // Color
  91429. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  91430. // Draw order
  91431. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91432. }
  91433. engine.setDepthBuffer(true);
  91434. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  91435. return true;
  91436. };
  91437. /**
  91438. * Dispose and release the lens flare with its associated resources.
  91439. */
  91440. LensFlareSystem.prototype.dispose = function () {
  91441. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91442. if (vertexBuffer) {
  91443. vertexBuffer.dispose();
  91444. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91445. }
  91446. if (this._indexBuffer) {
  91447. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91448. this._indexBuffer = null;
  91449. }
  91450. while (this.lensFlares.length) {
  91451. this.lensFlares[0].dispose();
  91452. }
  91453. // Remove from scene
  91454. var index = this._scene.lensFlareSystems.indexOf(this);
  91455. this._scene.lensFlareSystems.splice(index, 1);
  91456. };
  91457. /**
  91458. * Parse a lens flare system from a JSON repressentation
  91459. * @param parsedLensFlareSystem Define the JSON to parse
  91460. * @param scene Define the scene the parsed system should be instantiated in
  91461. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  91462. * @returns the parsed system
  91463. */
  91464. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  91465. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  91466. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  91467. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  91468. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  91469. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  91470. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  91471. var parsedFlare = parsedLensFlareSystem.flares[index];
  91472. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  91473. }
  91474. return lensFlareSystem;
  91475. };
  91476. /**
  91477. * Serialize the current Lens Flare System into a JSON representation.
  91478. * @returns the serialized JSON
  91479. */
  91480. LensFlareSystem.prototype.serialize = function () {
  91481. var serializationObject = {};
  91482. serializationObject.id = this.id;
  91483. serializationObject.name = this.name;
  91484. serializationObject.emitterId = this.getEmitter().id;
  91485. serializationObject.borderLimit = this.borderLimit;
  91486. serializationObject.flares = [];
  91487. for (var index = 0; index < this.lensFlares.length; index++) {
  91488. var flare = this.lensFlares[index];
  91489. serializationObject.flares.push({
  91490. size: flare.size,
  91491. position: flare.position,
  91492. color: flare.color.asArray(),
  91493. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  91494. });
  91495. }
  91496. return serializationObject;
  91497. };
  91498. return LensFlareSystem;
  91499. }());
  91500. BABYLON.LensFlareSystem = LensFlareSystem;
  91501. })(BABYLON || (BABYLON = {}));
  91502. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  91503. var BABYLON;
  91504. (function (BABYLON) {
  91505. /**
  91506. * This is a holder class for the physics joint created by the physics plugin.
  91507. * It holds a set of functions to control the underlying joint.
  91508. */
  91509. var PhysicsJoint = /** @class */ (function () {
  91510. function PhysicsJoint(type, jointData) {
  91511. this.type = type;
  91512. this.jointData = jointData;
  91513. jointData.nativeParams = jointData.nativeParams || {};
  91514. }
  91515. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  91516. get: function () {
  91517. return this._physicsJoint;
  91518. },
  91519. set: function (newJoint) {
  91520. if (this._physicsJoint) {
  91521. //remove from the wolrd
  91522. }
  91523. this._physicsJoint = newJoint;
  91524. },
  91525. enumerable: true,
  91526. configurable: true
  91527. });
  91528. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  91529. set: function (physicsPlugin) {
  91530. this._physicsPlugin = physicsPlugin;
  91531. },
  91532. enumerable: true,
  91533. configurable: true
  91534. });
  91535. /**
  91536. * Execute a function that is physics-plugin specific.
  91537. * @param {Function} func the function that will be executed.
  91538. * It accepts two parameters: the physics world and the physics joint.
  91539. */
  91540. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  91541. func(this._physicsPlugin.world, this._physicsJoint);
  91542. };
  91543. //TODO check if the native joints are the same
  91544. //Joint Types
  91545. PhysicsJoint.DistanceJoint = 0;
  91546. PhysicsJoint.HingeJoint = 1;
  91547. PhysicsJoint.BallAndSocketJoint = 2;
  91548. PhysicsJoint.WheelJoint = 3;
  91549. PhysicsJoint.SliderJoint = 4;
  91550. //OIMO
  91551. PhysicsJoint.PrismaticJoint = 5;
  91552. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  91553. PhysicsJoint.UniversalJoint = 6;
  91554. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  91555. //Cannon
  91556. //Similar to a Ball-Joint. Different in params
  91557. PhysicsJoint.PointToPointJoint = 8;
  91558. //Cannon only at the moment
  91559. PhysicsJoint.SpringJoint = 9;
  91560. PhysicsJoint.LockJoint = 10;
  91561. return PhysicsJoint;
  91562. }());
  91563. BABYLON.PhysicsJoint = PhysicsJoint;
  91564. /**
  91565. * A class representing a physics distance joint.
  91566. */
  91567. var DistanceJoint = /** @class */ (function (_super) {
  91568. __extends(DistanceJoint, _super);
  91569. function DistanceJoint(jointData) {
  91570. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  91571. }
  91572. /**
  91573. * Update the predefined distance.
  91574. */
  91575. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  91576. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  91577. };
  91578. return DistanceJoint;
  91579. }(PhysicsJoint));
  91580. BABYLON.DistanceJoint = DistanceJoint;
  91581. var MotorEnabledJoint = /** @class */ (function (_super) {
  91582. __extends(MotorEnabledJoint, _super);
  91583. function MotorEnabledJoint(type, jointData) {
  91584. return _super.call(this, type, jointData) || this;
  91585. }
  91586. /**
  91587. * Set the motor values.
  91588. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91589. * @param {number} force the force to apply
  91590. * @param {number} maxForce max force for this motor.
  91591. */
  91592. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  91593. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91594. };
  91595. /**
  91596. * Set the motor's limits.
  91597. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91598. */
  91599. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91600. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91601. };
  91602. return MotorEnabledJoint;
  91603. }(PhysicsJoint));
  91604. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  91605. /**
  91606. * This class represents a single hinge physics joint
  91607. */
  91608. var HingeJoint = /** @class */ (function (_super) {
  91609. __extends(HingeJoint, _super);
  91610. function HingeJoint(jointData) {
  91611. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  91612. }
  91613. /**
  91614. * Set the motor values.
  91615. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91616. * @param {number} force the force to apply
  91617. * @param {number} maxForce max force for this motor.
  91618. */
  91619. HingeJoint.prototype.setMotor = function (force, maxForce) {
  91620. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91621. };
  91622. /**
  91623. * Set the motor's limits.
  91624. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91625. */
  91626. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91627. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91628. };
  91629. return HingeJoint;
  91630. }(MotorEnabledJoint));
  91631. BABYLON.HingeJoint = HingeJoint;
  91632. /**
  91633. * This class represents a dual hinge physics joint (same as wheel joint)
  91634. */
  91635. var Hinge2Joint = /** @class */ (function (_super) {
  91636. __extends(Hinge2Joint, _super);
  91637. function Hinge2Joint(jointData) {
  91638. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  91639. }
  91640. /**
  91641. * Set the motor values.
  91642. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91643. * @param {number} force the force to apply
  91644. * @param {number} maxForce max force for this motor.
  91645. * @param {motorIndex} the motor's index, 0 or 1.
  91646. */
  91647. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  91648. if (motorIndex === void 0) { motorIndex = 0; }
  91649. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  91650. };
  91651. /**
  91652. * Set the motor limits.
  91653. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91654. * @param {number} upperLimit the upper limit
  91655. * @param {number} lowerLimit lower limit
  91656. * @param {motorIndex} the motor's index, 0 or 1.
  91657. */
  91658. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  91659. if (motorIndex === void 0) { motorIndex = 0; }
  91660. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  91661. };
  91662. return Hinge2Joint;
  91663. }(MotorEnabledJoint));
  91664. BABYLON.Hinge2Joint = Hinge2Joint;
  91665. })(BABYLON || (BABYLON = {}));
  91666. //# sourceMappingURL=babylon.physicsJoint.js.map
  91667. var BABYLON;
  91668. (function (BABYLON) {
  91669. var PhysicsImpostor = /** @class */ (function () {
  91670. function PhysicsImpostor(object, type, _options, _scene) {
  91671. if (_options === void 0) { _options = { mass: 0 }; }
  91672. var _this = this;
  91673. this.object = object;
  91674. this.type = type;
  91675. this._options = _options;
  91676. this._scene = _scene;
  91677. this._bodyUpdateRequired = false;
  91678. this._onBeforePhysicsStepCallbacks = new Array();
  91679. this._onAfterPhysicsStepCallbacks = new Array();
  91680. this._onPhysicsCollideCallbacks = [];
  91681. this._deltaPosition = BABYLON.Vector3.Zero();
  91682. this._isDisposed = false;
  91683. //temp variables for parent rotation calculations
  91684. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  91685. this._tmpQuat = new BABYLON.Quaternion();
  91686. this._tmpQuat2 = new BABYLON.Quaternion();
  91687. /**
  91688. * this function is executed by the physics engine.
  91689. */
  91690. this.beforeStep = function () {
  91691. if (!_this._physicsEngine) {
  91692. return;
  91693. }
  91694. _this.object.translate(_this._deltaPosition, -1);
  91695. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  91696. _this.object.computeWorldMatrix(false);
  91697. if (_this.object.parent && _this.object.rotationQuaternion) {
  91698. _this.getParentsRotation();
  91699. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  91700. }
  91701. else {
  91702. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  91703. }
  91704. if (!_this._options.disableBidirectionalTransformation) {
  91705. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  91706. }
  91707. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  91708. func(_this);
  91709. });
  91710. };
  91711. /**
  91712. * this function is executed by the physics engine.
  91713. */
  91714. this.afterStep = function () {
  91715. if (!_this._physicsEngine) {
  91716. return;
  91717. }
  91718. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  91719. func(_this);
  91720. });
  91721. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  91722. // object has now its world rotation. needs to be converted to local.
  91723. if (_this.object.parent && _this.object.rotationQuaternion) {
  91724. _this.getParentsRotation();
  91725. _this._tmpQuat.conjugateInPlace();
  91726. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  91727. }
  91728. // take the position set and make it the absolute position of this object.
  91729. _this.object.setAbsolutePosition(_this.object.position);
  91730. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  91731. _this.object.translate(_this._deltaPosition, 1);
  91732. };
  91733. /**
  91734. * Legacy collision detection event support
  91735. */
  91736. this.onCollideEvent = null;
  91737. //event and body object due to cannon's event-based architecture.
  91738. this.onCollide = function (e) {
  91739. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  91740. return;
  91741. }
  91742. if (!_this._physicsEngine) {
  91743. return;
  91744. }
  91745. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  91746. if (otherImpostor) {
  91747. // Legacy collision detection event support
  91748. if (_this.onCollideEvent) {
  91749. _this.onCollideEvent(_this, otherImpostor);
  91750. }
  91751. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  91752. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  91753. }).forEach(function (obj) {
  91754. obj.callback(_this, otherImpostor);
  91755. });
  91756. }
  91757. };
  91758. //sanity check!
  91759. if (!this.object) {
  91760. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  91761. return;
  91762. }
  91763. //legacy support for old syntax.
  91764. if (!this._scene && object.getScene) {
  91765. this._scene = object.getScene();
  91766. }
  91767. if (!this._scene) {
  91768. return;
  91769. }
  91770. this._physicsEngine = this._scene.getPhysicsEngine();
  91771. if (!this._physicsEngine) {
  91772. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  91773. }
  91774. else {
  91775. //set the object's quaternion, if not set
  91776. if (!this.object.rotationQuaternion) {
  91777. if (this.object.rotation) {
  91778. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  91779. }
  91780. else {
  91781. this.object.rotationQuaternion = new BABYLON.Quaternion();
  91782. }
  91783. }
  91784. //default options params
  91785. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  91786. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  91787. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  91788. this._joints = [];
  91789. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  91790. if (!this.object.parent || this._options.ignoreParent) {
  91791. this._init();
  91792. }
  91793. else if (this.object.parent.physicsImpostor) {
  91794. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  91795. }
  91796. }
  91797. }
  91798. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  91799. get: function () {
  91800. return this._isDisposed;
  91801. },
  91802. enumerable: true,
  91803. configurable: true
  91804. });
  91805. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  91806. get: function () {
  91807. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  91808. },
  91809. set: function (value) {
  91810. this.setMass(value);
  91811. },
  91812. enumerable: true,
  91813. configurable: true
  91814. });
  91815. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  91816. get: function () {
  91817. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  91818. },
  91819. set: function (value) {
  91820. if (!this._physicsEngine) {
  91821. return;
  91822. }
  91823. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  91824. },
  91825. enumerable: true,
  91826. configurable: true
  91827. });
  91828. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  91829. get: function () {
  91830. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  91831. },
  91832. set: function (value) {
  91833. if (!this._physicsEngine) {
  91834. return;
  91835. }
  91836. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  91837. },
  91838. enumerable: true,
  91839. configurable: true
  91840. });
  91841. /**
  91842. * This function will completly initialize this impostor.
  91843. * It will create a new body - but only if this mesh has no parent.
  91844. * If it has, this impostor will not be used other than to define the impostor
  91845. * of the child mesh.
  91846. * @hidden
  91847. */
  91848. PhysicsImpostor.prototype._init = function () {
  91849. if (!this._physicsEngine) {
  91850. return;
  91851. }
  91852. this._physicsEngine.removeImpostor(this);
  91853. this.physicsBody = null;
  91854. this._parent = this._parent || this._getPhysicsParent();
  91855. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  91856. this._physicsEngine.addImpostor(this);
  91857. }
  91858. };
  91859. PhysicsImpostor.prototype._getPhysicsParent = function () {
  91860. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  91861. var parentMesh = this.object.parent;
  91862. return parentMesh.physicsImpostor;
  91863. }
  91864. return null;
  91865. };
  91866. /**
  91867. * Should a new body be generated.
  91868. */
  91869. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  91870. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  91871. };
  91872. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  91873. this.forceUpdate();
  91874. };
  91875. /**
  91876. * Force a regeneration of this or the parent's impostor's body.
  91877. * Use under cautious - This will remove all joints already implemented.
  91878. */
  91879. PhysicsImpostor.prototype.forceUpdate = function () {
  91880. this._init();
  91881. if (this.parent && !this._options.ignoreParent) {
  91882. this.parent.forceUpdate();
  91883. }
  91884. };
  91885. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  91886. /*public get mesh(): AbstractMesh {
  91887. return this._mesh;
  91888. }*/
  91889. /**
  91890. * Gets the body that holds this impostor. Either its own, or its parent.
  91891. */
  91892. get: function () {
  91893. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  91894. },
  91895. /**
  91896. * Set the physics body. Used mainly by the physics engine/plugin
  91897. */
  91898. set: function (physicsBody) {
  91899. if (this._physicsBody && this._physicsEngine) {
  91900. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  91901. }
  91902. this._physicsBody = physicsBody;
  91903. this.resetUpdateFlags();
  91904. },
  91905. enumerable: true,
  91906. configurable: true
  91907. });
  91908. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  91909. get: function () {
  91910. return !this._options.ignoreParent && this._parent ? this._parent : null;
  91911. },
  91912. set: function (value) {
  91913. this._parent = value;
  91914. },
  91915. enumerable: true,
  91916. configurable: true
  91917. });
  91918. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  91919. this._bodyUpdateRequired = false;
  91920. };
  91921. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  91922. if (this.object.getBoundingInfo) {
  91923. var q = this.object.rotationQuaternion;
  91924. //reset rotation
  91925. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  91926. //calculate the world matrix with no rotation
  91927. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91928. var boundingInfo = this.object.getBoundingInfo();
  91929. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  91930. //bring back the rotation
  91931. this.object.rotationQuaternion = q;
  91932. //calculate the world matrix with the new rotation
  91933. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91934. return size;
  91935. }
  91936. else {
  91937. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  91938. }
  91939. };
  91940. PhysicsImpostor.prototype.getObjectCenter = function () {
  91941. if (this.object.getBoundingInfo) {
  91942. var boundingInfo = this.object.getBoundingInfo();
  91943. return boundingInfo.boundingBox.centerWorld;
  91944. }
  91945. else {
  91946. return this.object.position;
  91947. }
  91948. };
  91949. /**
  91950. * Get a specific parametes from the options parameter.
  91951. */
  91952. PhysicsImpostor.prototype.getParam = function (paramName) {
  91953. return this._options[paramName];
  91954. };
  91955. /**
  91956. * Sets a specific parameter in the options given to the physics plugin
  91957. */
  91958. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  91959. this._options[paramName] = value;
  91960. this._bodyUpdateRequired = true;
  91961. };
  91962. /**
  91963. * Specifically change the body's mass option. Won't recreate the physics body object
  91964. */
  91965. PhysicsImpostor.prototype.setMass = function (mass) {
  91966. if (this.getParam("mass") !== mass) {
  91967. this.setParam("mass", mass);
  91968. }
  91969. if (this._physicsEngine) {
  91970. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  91971. }
  91972. };
  91973. PhysicsImpostor.prototype.getLinearVelocity = function () {
  91974. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  91975. };
  91976. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  91977. if (this._physicsEngine) {
  91978. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  91979. }
  91980. };
  91981. PhysicsImpostor.prototype.getAngularVelocity = function () {
  91982. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  91983. };
  91984. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  91985. if (this._physicsEngine) {
  91986. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  91987. }
  91988. };
  91989. /**
  91990. * Execute a function with the physics plugin native code.
  91991. * Provide a function the will have two variables - the world object and the physics body object.
  91992. */
  91993. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  91994. if (this._physicsEngine) {
  91995. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  91996. }
  91997. };
  91998. /**
  91999. * Register a function that will be executed before the physics world is stepping forward.
  92000. */
  92001. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  92002. this._onBeforePhysicsStepCallbacks.push(func);
  92003. };
  92004. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  92005. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  92006. if (index > -1) {
  92007. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  92008. }
  92009. else {
  92010. BABYLON.Tools.Warn("Function to remove was not found");
  92011. }
  92012. };
  92013. /**
  92014. * Register a function that will be executed after the physics step
  92015. */
  92016. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  92017. this._onAfterPhysicsStepCallbacks.push(func);
  92018. };
  92019. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  92020. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  92021. if (index > -1) {
  92022. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  92023. }
  92024. else {
  92025. BABYLON.Tools.Warn("Function to remove was not found");
  92026. }
  92027. };
  92028. /**
  92029. * register a function that will be executed when this impostor collides against a different body.
  92030. */
  92031. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  92032. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  92033. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  92034. };
  92035. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  92036. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  92037. var index = -1;
  92038. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  92039. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  92040. // chcek the arrays match
  92041. var sameList = cbDef.otherImpostors.every(function (impostor) {
  92042. return collidedAgainstList.indexOf(impostor) > -1;
  92043. });
  92044. if (sameList) {
  92045. index = idx;
  92046. }
  92047. return sameList;
  92048. }
  92049. return false;
  92050. });
  92051. if (found) {
  92052. this._onPhysicsCollideCallbacks.splice(index, 1);
  92053. }
  92054. else {
  92055. BABYLON.Tools.Warn("Function to remove was not found");
  92056. }
  92057. };
  92058. PhysicsImpostor.prototype.getParentsRotation = function () {
  92059. var parent = this.object.parent;
  92060. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  92061. while (parent) {
  92062. if (parent.rotationQuaternion) {
  92063. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  92064. }
  92065. else {
  92066. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  92067. }
  92068. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  92069. parent = parent.parent;
  92070. }
  92071. return this._tmpQuat;
  92072. };
  92073. /**
  92074. * Apply a force
  92075. */
  92076. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  92077. if (this._physicsEngine) {
  92078. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  92079. }
  92080. return this;
  92081. };
  92082. /**
  92083. * Apply an impulse
  92084. */
  92085. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  92086. if (this._physicsEngine) {
  92087. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  92088. }
  92089. return this;
  92090. };
  92091. /**
  92092. * A help function to create a joint.
  92093. */
  92094. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  92095. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  92096. this.addJoint(otherImpostor, joint);
  92097. return this;
  92098. };
  92099. /**
  92100. * Add a joint to this impostor with a different impostor.
  92101. */
  92102. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  92103. this._joints.push({
  92104. otherImpostor: otherImpostor,
  92105. joint: joint
  92106. });
  92107. if (this._physicsEngine) {
  92108. this._physicsEngine.addJoint(this, otherImpostor, joint);
  92109. }
  92110. return this;
  92111. };
  92112. /**
  92113. * Will keep this body still, in a sleep mode.
  92114. */
  92115. PhysicsImpostor.prototype.sleep = function () {
  92116. if (this._physicsEngine) {
  92117. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  92118. }
  92119. return this;
  92120. };
  92121. /**
  92122. * Wake the body up.
  92123. */
  92124. PhysicsImpostor.prototype.wakeUp = function () {
  92125. if (this._physicsEngine) {
  92126. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  92127. }
  92128. return this;
  92129. };
  92130. PhysicsImpostor.prototype.clone = function (newObject) {
  92131. if (!newObject)
  92132. return null;
  92133. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  92134. };
  92135. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  92136. var _this = this;
  92137. //no dispose if no physics engine is available.
  92138. if (!this._physicsEngine) {
  92139. return;
  92140. }
  92141. this._joints.forEach(function (j) {
  92142. if (_this._physicsEngine) {
  92143. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  92144. }
  92145. });
  92146. //dispose the physics body
  92147. this._physicsEngine.removeImpostor(this);
  92148. if (this.parent) {
  92149. this.parent.forceUpdate();
  92150. }
  92151. else {
  92152. /*this._object.getChildMeshes().forEach(function(mesh) {
  92153. if (mesh.physicsImpostor) {
  92154. if (disposeChildren) {
  92155. mesh.physicsImpostor.dispose();
  92156. mesh.physicsImpostor = null;
  92157. }
  92158. }
  92159. })*/
  92160. }
  92161. this._isDisposed = true;
  92162. };
  92163. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  92164. this._deltaPosition.copyFrom(position);
  92165. };
  92166. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  92167. if (!this._deltaRotation) {
  92168. this._deltaRotation = new BABYLON.Quaternion();
  92169. }
  92170. this._deltaRotation.copyFrom(rotation);
  92171. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  92172. };
  92173. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  92174. if (this._physicsEngine) {
  92175. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  92176. }
  92177. return this;
  92178. };
  92179. PhysicsImpostor.prototype.getRadius = function () {
  92180. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  92181. };
  92182. /**
  92183. * Sync a bone with this impostor
  92184. * @param bone The bone to sync to the impostor.
  92185. * @param boneMesh The mesh that the bone is influencing.
  92186. * @param jointPivot The pivot of the joint / bone in local space.
  92187. * @param distToJoint Optional distance from the impostor to the joint.
  92188. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  92189. */
  92190. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  92191. var tempVec = PhysicsImpostor._tmpVecs[0];
  92192. var mesh = this.object;
  92193. if (mesh.rotationQuaternion) {
  92194. if (adjustRotation) {
  92195. var tempQuat = PhysicsImpostor._tmpQuat;
  92196. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  92197. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  92198. }
  92199. else {
  92200. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  92201. }
  92202. }
  92203. tempVec.x = 0;
  92204. tempVec.y = 0;
  92205. tempVec.z = 0;
  92206. if (jointPivot) {
  92207. tempVec.x = jointPivot.x;
  92208. tempVec.y = jointPivot.y;
  92209. tempVec.z = jointPivot.z;
  92210. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  92211. if (distToJoint === undefined || distToJoint === null) {
  92212. distToJoint = jointPivot.length();
  92213. }
  92214. tempVec.x *= distToJoint;
  92215. tempVec.y *= distToJoint;
  92216. tempVec.z *= distToJoint;
  92217. }
  92218. if (bone.getParent()) {
  92219. tempVec.addInPlace(mesh.getAbsolutePosition());
  92220. bone.setAbsolutePosition(tempVec, boneMesh);
  92221. }
  92222. else {
  92223. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  92224. boneMesh.position.x -= tempVec.x;
  92225. boneMesh.position.y -= tempVec.y;
  92226. boneMesh.position.z -= tempVec.z;
  92227. }
  92228. };
  92229. /**
  92230. * Sync impostor to a bone
  92231. * @param bone The bone that the impostor will be synced to.
  92232. * @param boneMesh The mesh that the bone is influencing.
  92233. * @param jointPivot The pivot of the joint / bone in local space.
  92234. * @param distToJoint Optional distance from the impostor to the joint.
  92235. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  92236. * @param boneAxis Optional vector3 axis the bone is aligned with
  92237. */
  92238. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  92239. var mesh = this.object;
  92240. if (mesh.rotationQuaternion) {
  92241. if (adjustRotation) {
  92242. var tempQuat = PhysicsImpostor._tmpQuat;
  92243. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  92244. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  92245. }
  92246. else {
  92247. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  92248. }
  92249. }
  92250. var pos = PhysicsImpostor._tmpVecs[0];
  92251. var boneDir = PhysicsImpostor._tmpVecs[1];
  92252. if (!boneAxis) {
  92253. boneAxis = PhysicsImpostor._tmpVecs[2];
  92254. boneAxis.x = 0;
  92255. boneAxis.y = 1;
  92256. boneAxis.z = 0;
  92257. }
  92258. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  92259. bone.getAbsolutePositionToRef(boneMesh, pos);
  92260. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  92261. distToJoint = jointPivot.length();
  92262. }
  92263. if (distToJoint !== undefined && distToJoint !== null) {
  92264. pos.x += boneDir.x * distToJoint;
  92265. pos.y += boneDir.y * distToJoint;
  92266. pos.z += boneDir.z * distToJoint;
  92267. }
  92268. mesh.setAbsolutePosition(pos);
  92269. };
  92270. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  92271. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  92272. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  92273. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  92274. //Impostor types
  92275. PhysicsImpostor.NoImpostor = 0;
  92276. PhysicsImpostor.SphereImpostor = 1;
  92277. PhysicsImpostor.BoxImpostor = 2;
  92278. PhysicsImpostor.PlaneImpostor = 3;
  92279. PhysicsImpostor.MeshImpostor = 4;
  92280. PhysicsImpostor.CylinderImpostor = 7;
  92281. PhysicsImpostor.ParticleImpostor = 8;
  92282. PhysicsImpostor.HeightmapImpostor = 9;
  92283. return PhysicsImpostor;
  92284. }());
  92285. BABYLON.PhysicsImpostor = PhysicsImpostor;
  92286. })(BABYLON || (BABYLON = {}));
  92287. //# sourceMappingURL=babylon.physicsImpostor.js.map
  92288. var BABYLON;
  92289. (function (BABYLON) {
  92290. /**
  92291. * Class used to control physics engine
  92292. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  92293. */
  92294. var PhysicsEngine = /** @class */ (function () {
  92295. /**
  92296. * Creates a new Physics Engine
  92297. * @param gravity defines the gravity vector used by the simulation
  92298. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  92299. */
  92300. function PhysicsEngine(gravity, _physicsPlugin) {
  92301. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  92302. this._physicsPlugin = _physicsPlugin;
  92303. this._impostors = [];
  92304. this._joints = [];
  92305. if (!this._physicsPlugin.isSupported()) {
  92306. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  92307. + "Please make sure it is included.");
  92308. }
  92309. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  92310. this.setGravity(gravity);
  92311. this.setTimeStep();
  92312. }
  92313. /**
  92314. * Sets the gravity vector used by the simulation
  92315. * @param gravity defines the gravity vector to use
  92316. */
  92317. PhysicsEngine.prototype.setGravity = function (gravity) {
  92318. this.gravity = gravity;
  92319. this._physicsPlugin.setGravity(this.gravity);
  92320. };
  92321. /**
  92322. * Set the time step of the physics engine.
  92323. * Default is 1/60.
  92324. * To slow it down, enter 1/600 for example.
  92325. * To speed it up, 1/30
  92326. * @param newTimeStep defines the new timestep to apply to this world.
  92327. */
  92328. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  92329. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  92330. this._physicsPlugin.setTimeStep(newTimeStep);
  92331. };
  92332. /**
  92333. * Get the time step of the physics engine.
  92334. * @returns the current time step
  92335. */
  92336. PhysicsEngine.prototype.getTimeStep = function () {
  92337. return this._physicsPlugin.getTimeStep();
  92338. };
  92339. /**
  92340. * Release all resources
  92341. */
  92342. PhysicsEngine.prototype.dispose = function () {
  92343. this._impostors.forEach(function (impostor) {
  92344. impostor.dispose();
  92345. });
  92346. this._physicsPlugin.dispose();
  92347. };
  92348. /**
  92349. * Gets the name of the current physics plugin
  92350. * @returns the name of the plugin
  92351. */
  92352. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  92353. return this._physicsPlugin.name;
  92354. };
  92355. /**
  92356. * Adding a new impostor for the impostor tracking.
  92357. * This will be done by the impostor itself.
  92358. * @param impostor the impostor to add
  92359. */
  92360. PhysicsEngine.prototype.addImpostor = function (impostor) {
  92361. impostor.uniqueId = this._impostors.push(impostor);
  92362. //if no parent, generate the body
  92363. if (!impostor.parent) {
  92364. this._physicsPlugin.generatePhysicsBody(impostor);
  92365. }
  92366. };
  92367. /**
  92368. * Remove an impostor from the engine.
  92369. * This impostor and its mesh will not longer be updated by the physics engine.
  92370. * @param impostor the impostor to remove
  92371. */
  92372. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  92373. var index = this._impostors.indexOf(impostor);
  92374. if (index > -1) {
  92375. var removed = this._impostors.splice(index, 1);
  92376. //Is it needed?
  92377. if (removed.length) {
  92378. //this will also remove it from the world.
  92379. removed[0].physicsBody = null;
  92380. }
  92381. }
  92382. };
  92383. /**
  92384. * Add a joint to the physics engine
  92385. * @param mainImpostor defines the main impostor to which the joint is added.
  92386. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  92387. * @param joint defines the joint that will connect both impostors.
  92388. */
  92389. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  92390. var impostorJoint = {
  92391. mainImpostor: mainImpostor,
  92392. connectedImpostor: connectedImpostor,
  92393. joint: joint
  92394. };
  92395. joint.physicsPlugin = this._physicsPlugin;
  92396. this._joints.push(impostorJoint);
  92397. this._physicsPlugin.generateJoint(impostorJoint);
  92398. };
  92399. /**
  92400. * Removes a joint from the simulation
  92401. * @param mainImpostor defines the impostor used with the joint
  92402. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  92403. * @param joint defines the joint to remove
  92404. */
  92405. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  92406. var matchingJoints = this._joints.filter(function (impostorJoint) {
  92407. return (impostorJoint.connectedImpostor === connectedImpostor
  92408. && impostorJoint.joint === joint
  92409. && impostorJoint.mainImpostor === mainImpostor);
  92410. });
  92411. if (matchingJoints.length) {
  92412. this._physicsPlugin.removeJoint(matchingJoints[0]);
  92413. //TODO remove it from the list as well
  92414. }
  92415. };
  92416. /**
  92417. * Called by the scene. No need to call it.
  92418. * @param delta defines the timespam between frames
  92419. */
  92420. PhysicsEngine.prototype._step = function (delta) {
  92421. var _this = this;
  92422. //check if any mesh has no body / requires an update
  92423. this._impostors.forEach(function (impostor) {
  92424. if (impostor.isBodyInitRequired()) {
  92425. _this._physicsPlugin.generatePhysicsBody(impostor);
  92426. }
  92427. });
  92428. if (delta > 0.1) {
  92429. delta = 0.1;
  92430. }
  92431. else if (delta <= 0) {
  92432. delta = 1.0 / 60.0;
  92433. }
  92434. this._physicsPlugin.executeStep(delta, this._impostors);
  92435. };
  92436. /**
  92437. * Gets the current plugin used to run the simulation
  92438. * @returns current plugin
  92439. */
  92440. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  92441. return this._physicsPlugin;
  92442. };
  92443. /**
  92444. * Gets the list of physic impostors
  92445. * @returns an array of PhysicsImpostor
  92446. */
  92447. PhysicsEngine.prototype.getImpostors = function () {
  92448. return this._impostors;
  92449. };
  92450. /**
  92451. * Gets the impostor for a physics enabled object
  92452. * @param object defines the object impersonated by the impostor
  92453. * @returns the PhysicsImpostor or null if not found
  92454. */
  92455. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  92456. for (var i = 0; i < this._impostors.length; ++i) {
  92457. if (this._impostors[i].object === object) {
  92458. return this._impostors[i];
  92459. }
  92460. }
  92461. return null;
  92462. };
  92463. /**
  92464. * Gets the impostor for a physics body object
  92465. * @param body defines physics body used by the impostor
  92466. * @returns the PhysicsImpostor or null if not found
  92467. */
  92468. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  92469. for (var i = 0; i < this._impostors.length; ++i) {
  92470. if (this._impostors[i].physicsBody === body) {
  92471. return this._impostors[i];
  92472. }
  92473. }
  92474. return null;
  92475. };
  92476. /**
  92477. * Global value used to control the smallest number supported by the simulation
  92478. */
  92479. PhysicsEngine.Epsilon = 0.001;
  92480. return PhysicsEngine;
  92481. }());
  92482. BABYLON.PhysicsEngine = PhysicsEngine;
  92483. })(BABYLON || (BABYLON = {}));
  92484. //# sourceMappingURL=babylon.physicsEngine.js.map
  92485. var BABYLON;
  92486. (function (BABYLON) {
  92487. var PhysicsHelper = /** @class */ (function () {
  92488. function PhysicsHelper(scene) {
  92489. this._scene = scene;
  92490. this._physicsEngine = this._scene.getPhysicsEngine();
  92491. if (!this._physicsEngine) {
  92492. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  92493. }
  92494. }
  92495. /**
  92496. * @param {Vector3} origin the origin of the explosion
  92497. * @param {number} radius the explosion radius
  92498. * @param {number} strength the explosion strength
  92499. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92500. */
  92501. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  92502. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92503. if (!this._physicsEngine) {
  92504. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  92505. return null;
  92506. }
  92507. var impostors = this._physicsEngine.getImpostors();
  92508. if (impostors.length === 0) {
  92509. return null;
  92510. }
  92511. var event = new PhysicsRadialExplosionEvent(this._scene);
  92512. impostors.forEach(function (impostor) {
  92513. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  92514. if (!impostorForceAndContactPoint) {
  92515. return;
  92516. }
  92517. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92518. });
  92519. event.dispose(false);
  92520. return event;
  92521. };
  92522. /**
  92523. * @param {Vector3} origin the origin of the explosion
  92524. * @param {number} radius the explosion radius
  92525. * @param {number} strength the explosion strength
  92526. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92527. */
  92528. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  92529. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92530. if (!this._physicsEngine) {
  92531. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92532. return null;
  92533. }
  92534. var impostors = this._physicsEngine.getImpostors();
  92535. if (impostors.length === 0) {
  92536. return null;
  92537. }
  92538. var event = new PhysicsRadialExplosionEvent(this._scene);
  92539. impostors.forEach(function (impostor) {
  92540. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  92541. if (!impostorForceAndContactPoint) {
  92542. return;
  92543. }
  92544. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92545. });
  92546. event.dispose(false);
  92547. return event;
  92548. };
  92549. /**
  92550. * @param {Vector3} origin the origin of the explosion
  92551. * @param {number} radius the explosion radius
  92552. * @param {number} strength the explosion strength
  92553. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92554. */
  92555. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  92556. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92557. if (!this._physicsEngine) {
  92558. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92559. return null;
  92560. }
  92561. var impostors = this._physicsEngine.getImpostors();
  92562. if (impostors.length === 0) {
  92563. return null;
  92564. }
  92565. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  92566. event.dispose(false);
  92567. return event;
  92568. };
  92569. /**
  92570. * @param {Vector3} origin the origin of the updraft
  92571. * @param {number} radius the radius of the updraft
  92572. * @param {number} strength the strength of the updraft
  92573. * @param {number} height the height of the updraft
  92574. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  92575. */
  92576. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  92577. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  92578. if (!this._physicsEngine) {
  92579. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92580. return null;
  92581. }
  92582. if (this._physicsEngine.getImpostors().length === 0) {
  92583. return null;
  92584. }
  92585. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  92586. event.dispose(false);
  92587. return event;
  92588. };
  92589. /**
  92590. * @param {Vector3} origin the of the vortex
  92591. * @param {number} radius the radius of the vortex
  92592. * @param {number} strength the strength of the vortex
  92593. * @param {number} height the height of the vortex
  92594. */
  92595. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  92596. if (!this._physicsEngine) {
  92597. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92598. return null;
  92599. }
  92600. if (this._physicsEngine.getImpostors().length === 0) {
  92601. return null;
  92602. }
  92603. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  92604. event.dispose(false);
  92605. return event;
  92606. };
  92607. return PhysicsHelper;
  92608. }());
  92609. BABYLON.PhysicsHelper = PhysicsHelper;
  92610. /***** Radial explosion *****/
  92611. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  92612. function PhysicsRadialExplosionEvent(scene) {
  92613. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  92614. this._rays = [];
  92615. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  92616. this._scene = scene;
  92617. }
  92618. /**
  92619. * Returns the data related to the radial explosion event (sphere & rays).
  92620. * @returns {PhysicsRadialExplosionEventData}
  92621. */
  92622. PhysicsRadialExplosionEvent.prototype.getData = function () {
  92623. this._dataFetched = true;
  92624. return {
  92625. sphere: this._sphere,
  92626. rays: this._rays,
  92627. };
  92628. };
  92629. /**
  92630. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  92631. * @param impostor
  92632. * @param {Vector3} origin the origin of the explosion
  92633. * @param {number} radius the explosion radius
  92634. * @param {number} strength the explosion strength
  92635. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  92636. * @returns {Nullable<PhysicsForceAndContactPoint>}
  92637. */
  92638. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  92639. if (impostor.mass === 0) {
  92640. return null;
  92641. }
  92642. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  92643. return null;
  92644. }
  92645. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92646. return null;
  92647. }
  92648. var impostorObjectCenter = impostor.getObjectCenter();
  92649. var direction = impostorObjectCenter.subtract(origin);
  92650. var ray = new BABYLON.Ray(origin, direction, radius);
  92651. this._rays.push(ray);
  92652. var hit = ray.intersectsMesh(impostor.object);
  92653. var contactPoint = hit.pickedPoint;
  92654. if (!contactPoint) {
  92655. return null;
  92656. }
  92657. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  92658. if (distanceFromOrigin > radius) {
  92659. return null;
  92660. }
  92661. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  92662. ? strength
  92663. : strength * (1 - (distanceFromOrigin / radius));
  92664. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92665. return { force: force, contactPoint: contactPoint };
  92666. };
  92667. /**
  92668. * Disposes the sphere.
  92669. * @param {bolean} force
  92670. */
  92671. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  92672. var _this = this;
  92673. if (force === void 0) { force = true; }
  92674. if (force) {
  92675. this._sphere.dispose();
  92676. }
  92677. else {
  92678. setTimeout(function () {
  92679. if (!_this._dataFetched) {
  92680. _this._sphere.dispose();
  92681. }
  92682. }, 0);
  92683. }
  92684. };
  92685. /*** Helpers ***/
  92686. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  92687. if (!this._sphere) {
  92688. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  92689. this._sphere.isVisible = false;
  92690. }
  92691. };
  92692. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  92693. var impostorObject = impostor.object;
  92694. this._prepareSphere();
  92695. this._sphere.position = origin;
  92696. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  92697. this._sphere._updateBoundingInfo();
  92698. this._sphere.computeWorldMatrix(true);
  92699. return this._sphere.intersectsMesh(impostorObject, true);
  92700. };
  92701. return PhysicsRadialExplosionEvent;
  92702. }());
  92703. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  92704. /***** Gravitational Field *****/
  92705. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  92706. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  92707. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92708. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92709. this._physicsHelper = physicsHelper;
  92710. this._scene = scene;
  92711. this._origin = origin;
  92712. this._radius = radius;
  92713. this._strength = strength;
  92714. this._falloff = falloff;
  92715. this._tickCallback = this._tick.bind(this);
  92716. }
  92717. /**
  92718. * Returns the data related to the gravitational field event (sphere).
  92719. * @returns {PhysicsGravitationalFieldEventData}
  92720. */
  92721. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  92722. this._dataFetched = true;
  92723. return {
  92724. sphere: this._sphere,
  92725. };
  92726. };
  92727. /**
  92728. * Enables the gravitational field.
  92729. */
  92730. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  92731. this._tickCallback.call(this);
  92732. this._scene.registerBeforeRender(this._tickCallback);
  92733. };
  92734. /**
  92735. * Disables the gravitational field.
  92736. */
  92737. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  92738. this._scene.unregisterBeforeRender(this._tickCallback);
  92739. };
  92740. /**
  92741. * Disposes the sphere.
  92742. * @param {bolean} force
  92743. */
  92744. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  92745. var _this = this;
  92746. if (force === void 0) { force = true; }
  92747. if (force) {
  92748. this._sphere.dispose();
  92749. }
  92750. else {
  92751. setTimeout(function () {
  92752. if (!_this._dataFetched) {
  92753. _this._sphere.dispose();
  92754. }
  92755. }, 0);
  92756. }
  92757. };
  92758. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  92759. // Since the params won't change, we fetch the event only once
  92760. if (this._sphere) {
  92761. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92762. }
  92763. else {
  92764. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92765. if (radialExplosionEvent) {
  92766. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  92767. }
  92768. }
  92769. };
  92770. return PhysicsGravitationalFieldEvent;
  92771. }());
  92772. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  92773. /***** Updraft *****/
  92774. var PhysicsUpdraftEvent = /** @class */ (function () {
  92775. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  92776. this._scene = _scene;
  92777. this._origin = _origin;
  92778. this._radius = _radius;
  92779. this._strength = _strength;
  92780. this._height = _height;
  92781. this._updraftMode = _updraftMode;
  92782. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92783. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  92784. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92785. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92786. this._physicsEngine = this._scene.getPhysicsEngine();
  92787. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92788. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92789. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92790. this._originDirection = this._origin.subtract(this._originTop).normalize();
  92791. }
  92792. this._tickCallback = this._tick.bind(this);
  92793. }
  92794. /**
  92795. * Returns the data related to the updraft event (cylinder).
  92796. * @returns {PhysicsUpdraftEventData}
  92797. */
  92798. PhysicsUpdraftEvent.prototype.getData = function () {
  92799. this._dataFetched = true;
  92800. return {
  92801. cylinder: this._cylinder,
  92802. };
  92803. };
  92804. /**
  92805. * Enables the updraft.
  92806. */
  92807. PhysicsUpdraftEvent.prototype.enable = function () {
  92808. this._tickCallback.call(this);
  92809. this._scene.registerBeforeRender(this._tickCallback);
  92810. };
  92811. /**
  92812. * Disables the cortex.
  92813. */
  92814. PhysicsUpdraftEvent.prototype.disable = function () {
  92815. this._scene.unregisterBeforeRender(this._tickCallback);
  92816. };
  92817. /**
  92818. * Disposes the sphere.
  92819. * @param {bolean} force
  92820. */
  92821. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  92822. var _this = this;
  92823. if (force === void 0) { force = true; }
  92824. if (force) {
  92825. this._cylinder.dispose();
  92826. }
  92827. else {
  92828. setTimeout(function () {
  92829. if (!_this._dataFetched) {
  92830. _this._cylinder.dispose();
  92831. }
  92832. }, 0);
  92833. }
  92834. };
  92835. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92836. if (impostor.mass === 0) {
  92837. return null;
  92838. }
  92839. if (!this._intersectsWithCylinder(impostor)) {
  92840. return null;
  92841. }
  92842. var impostorObjectCenter = impostor.getObjectCenter();
  92843. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92844. var direction = this._originDirection;
  92845. }
  92846. else {
  92847. var direction = impostorObjectCenter.subtract(this._originTop);
  92848. }
  92849. var multiplier = this._strength * -1;
  92850. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92851. return { force: force, contactPoint: impostorObjectCenter };
  92852. };
  92853. PhysicsUpdraftEvent.prototype._tick = function () {
  92854. var _this = this;
  92855. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92856. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92857. if (!impostorForceAndContactPoint) {
  92858. return;
  92859. }
  92860. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92861. });
  92862. };
  92863. /*** Helpers ***/
  92864. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  92865. if (!this._cylinder) {
  92866. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  92867. height: this._height,
  92868. diameter: this._radius * 2,
  92869. }, this._scene);
  92870. this._cylinder.isVisible = false;
  92871. }
  92872. };
  92873. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  92874. var impostorObject = impostor.object;
  92875. this._prepareCylinder();
  92876. this._cylinder.position = this._cylinderPosition;
  92877. return this._cylinder.intersectsMesh(impostorObject, true);
  92878. };
  92879. return PhysicsUpdraftEvent;
  92880. }());
  92881. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  92882. /***** Vortex *****/
  92883. var PhysicsVortexEvent = /** @class */ (function () {
  92884. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  92885. this._scene = _scene;
  92886. this._origin = _origin;
  92887. this._radius = _radius;
  92888. this._strength = _strength;
  92889. this._height = _height;
  92890. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92891. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  92892. this._updraftMultiplier = 0.02;
  92893. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92894. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92895. this._physicsEngine = this._scene.getPhysicsEngine();
  92896. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92897. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92898. this._tickCallback = this._tick.bind(this);
  92899. }
  92900. /**
  92901. * Returns the data related to the vortex event (cylinder).
  92902. * @returns {PhysicsVortexEventData}
  92903. */
  92904. PhysicsVortexEvent.prototype.getData = function () {
  92905. this._dataFetched = true;
  92906. return {
  92907. cylinder: this._cylinder,
  92908. };
  92909. };
  92910. /**
  92911. * Enables the vortex.
  92912. */
  92913. PhysicsVortexEvent.prototype.enable = function () {
  92914. this._tickCallback.call(this);
  92915. this._scene.registerBeforeRender(this._tickCallback);
  92916. };
  92917. /**
  92918. * Disables the cortex.
  92919. */
  92920. PhysicsVortexEvent.prototype.disable = function () {
  92921. this._scene.unregisterBeforeRender(this._tickCallback);
  92922. };
  92923. /**
  92924. * Disposes the sphere.
  92925. * @param {bolean} force
  92926. */
  92927. PhysicsVortexEvent.prototype.dispose = function (force) {
  92928. var _this = this;
  92929. if (force === void 0) { force = true; }
  92930. if (force) {
  92931. this._cylinder.dispose();
  92932. }
  92933. else {
  92934. setTimeout(function () {
  92935. if (!_this._dataFetched) {
  92936. _this._cylinder.dispose();
  92937. }
  92938. }, 0);
  92939. }
  92940. };
  92941. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92942. if (impostor.mass === 0) {
  92943. return null;
  92944. }
  92945. if (!this._intersectsWithCylinder(impostor)) {
  92946. return null;
  92947. }
  92948. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92949. return null;
  92950. }
  92951. var impostorObjectCenter = impostor.getObjectCenter();
  92952. 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)
  92953. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  92954. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  92955. var hit = ray.intersectsMesh(impostor.object);
  92956. var contactPoint = hit.pickedPoint;
  92957. if (!contactPoint) {
  92958. return null;
  92959. }
  92960. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  92961. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  92962. var directionToOrigin = contactPoint.normalize();
  92963. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92964. directionToOrigin = directionToOrigin.negate();
  92965. }
  92966. // TODO: find a more physically based solution
  92967. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92968. var forceX = directionToOrigin.x * this._strength / 8;
  92969. var forceY = directionToOrigin.y * this._updraftMultiplier;
  92970. var forceZ = directionToOrigin.z * this._strength / 8;
  92971. }
  92972. else {
  92973. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  92974. var forceY = this._originTop.y * this._updraftMultiplier;
  92975. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  92976. }
  92977. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  92978. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  92979. return { force: force, contactPoint: impostorObjectCenter };
  92980. };
  92981. PhysicsVortexEvent.prototype._tick = function () {
  92982. var _this = this;
  92983. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92984. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92985. if (!impostorForceAndContactPoint) {
  92986. return;
  92987. }
  92988. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92989. });
  92990. };
  92991. /*** Helpers ***/
  92992. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  92993. if (!this._cylinder) {
  92994. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  92995. height: this._height,
  92996. diameter: this._radius * 2,
  92997. }, this._scene);
  92998. this._cylinder.isVisible = false;
  92999. }
  93000. };
  93001. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  93002. var impostorObject = impostor.object;
  93003. this._prepareCylinder();
  93004. this._cylinder.position = this._cylinderPosition;
  93005. return this._cylinder.intersectsMesh(impostorObject, true);
  93006. };
  93007. return PhysicsVortexEvent;
  93008. }());
  93009. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  93010. /***** Enums *****/
  93011. /**
  93012. * The strenght of the force in correspondence to the distance of the affected object
  93013. */
  93014. var PhysicsRadialImpulseFalloff;
  93015. (function (PhysicsRadialImpulseFalloff) {
  93016. /** Defines that impulse is constant in strength across it's whole radius */
  93017. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  93018. /** DEfines that impulse gets weaker if it's further from the origin */
  93019. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  93020. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  93021. /**
  93022. * The strenght of the force in correspondence to the distance of the affected object
  93023. */
  93024. var PhysicsUpdraftMode;
  93025. (function (PhysicsUpdraftMode) {
  93026. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  93027. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  93028. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  93029. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  93030. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  93031. })(BABYLON || (BABYLON = {}));
  93032. //# sourceMappingURL=babylon.physicsHelper.js.map
  93033. var BABYLON;
  93034. (function (BABYLON) {
  93035. /** @hidden */
  93036. var CannonJSPlugin = /** @class */ (function () {
  93037. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  93038. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  93039. if (iterations === void 0) { iterations = 10; }
  93040. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  93041. this.name = "CannonJSPlugin";
  93042. this._physicsMaterials = new Array();
  93043. this._fixedTimeStep = 1 / 60;
  93044. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  93045. this.BJSCANNON = CANNON;
  93046. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  93047. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  93048. this._tmpPosition = BABYLON.Vector3.Zero();
  93049. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  93050. this._tmpUnityRotation = new BABYLON.Quaternion();
  93051. if (!this.isSupported()) {
  93052. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  93053. return;
  93054. }
  93055. this._extendNamespace();
  93056. this.world = new this.BJSCANNON.World();
  93057. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  93058. this.world.solver.iterations = iterations;
  93059. }
  93060. CannonJSPlugin.prototype.setGravity = function (gravity) {
  93061. this.world.gravity.copy(gravity);
  93062. };
  93063. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  93064. this._fixedTimeStep = timeStep;
  93065. };
  93066. CannonJSPlugin.prototype.getTimeStep = function () {
  93067. return this._fixedTimeStep;
  93068. };
  93069. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  93070. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  93071. };
  93072. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  93073. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  93074. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  93075. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  93076. };
  93077. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  93078. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  93079. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  93080. impostor.physicsBody.applyForce(impulse, worldPoint);
  93081. };
  93082. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  93083. //parent-child relationship. Does this impostor has a parent impostor?
  93084. if (impostor.parent) {
  93085. if (impostor.physicsBody) {
  93086. this.removePhysicsBody(impostor);
  93087. //TODO is that needed?
  93088. impostor.forceUpdate();
  93089. }
  93090. return;
  93091. }
  93092. //should a new body be created for this impostor?
  93093. if (impostor.isBodyInitRequired()) {
  93094. var shape = this._createShape(impostor);
  93095. //unregister events, if body is being changed
  93096. var oldBody = impostor.physicsBody;
  93097. if (oldBody) {
  93098. this.removePhysicsBody(impostor);
  93099. }
  93100. //create the body and material
  93101. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  93102. var bodyCreationObject = {
  93103. mass: impostor.getParam("mass"),
  93104. material: material
  93105. };
  93106. // A simple extend, in case native options were used.
  93107. var nativeOptions = impostor.getParam("nativeOptions");
  93108. for (var key in nativeOptions) {
  93109. if (nativeOptions.hasOwnProperty(key)) {
  93110. bodyCreationObject[key] = nativeOptions[key];
  93111. }
  93112. }
  93113. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  93114. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  93115. this.world.addEventListener("preStep", impostor.beforeStep);
  93116. this.world.addEventListener("postStep", impostor.afterStep);
  93117. impostor.physicsBody.addShape(shape);
  93118. this.world.add(impostor.physicsBody);
  93119. //try to keep the body moving in the right direction by taking old properties.
  93120. //Should be tested!
  93121. if (oldBody) {
  93122. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  93123. impostor.physicsBody[param].copy(oldBody[param]);
  93124. });
  93125. }
  93126. this._processChildMeshes(impostor);
  93127. }
  93128. //now update the body's transformation
  93129. this._updatePhysicsBodyTransformation(impostor);
  93130. };
  93131. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  93132. var _this = this;
  93133. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  93134. var currentRotation = mainImpostor.object.rotationQuaternion;
  93135. if (meshChildren.length) {
  93136. var processMesh = function (localPosition, mesh) {
  93137. if (!currentRotation || !mesh.rotationQuaternion) {
  93138. return;
  93139. }
  93140. var childImpostor = mesh.getPhysicsImpostor();
  93141. if (childImpostor) {
  93142. var parent = childImpostor.parent;
  93143. if (parent !== mainImpostor) {
  93144. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  93145. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  93146. if (childImpostor.physicsBody) {
  93147. _this.removePhysicsBody(childImpostor);
  93148. childImpostor.physicsBody = null;
  93149. }
  93150. childImpostor.parent = mainImpostor;
  93151. childImpostor.resetUpdateFlags();
  93152. 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));
  93153. //Add the mass of the children.
  93154. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  93155. }
  93156. }
  93157. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  93158. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  93159. };
  93160. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  93161. }
  93162. };
  93163. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  93164. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  93165. this.world.removeEventListener("preStep", impostor.beforeStep);
  93166. this.world.removeEventListener("postStep", impostor.afterStep);
  93167. this.world.remove(impostor.physicsBody);
  93168. };
  93169. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  93170. var mainBody = impostorJoint.mainImpostor.physicsBody;
  93171. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  93172. if (!mainBody || !connectedBody) {
  93173. return;
  93174. }
  93175. var constraint;
  93176. var jointData = impostorJoint.joint.jointData;
  93177. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  93178. var constraintData = {
  93179. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  93180. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  93181. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  93182. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  93183. maxForce: jointData.nativeParams.maxForce,
  93184. collideConnected: !!jointData.collision
  93185. };
  93186. switch (impostorJoint.joint.type) {
  93187. case BABYLON.PhysicsJoint.HingeJoint:
  93188. case BABYLON.PhysicsJoint.Hinge2Joint:
  93189. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  93190. break;
  93191. case BABYLON.PhysicsJoint.DistanceJoint:
  93192. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  93193. break;
  93194. case BABYLON.PhysicsJoint.SpringJoint:
  93195. var springData = jointData;
  93196. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  93197. restLength: springData.length,
  93198. stiffness: springData.stiffness,
  93199. damping: springData.damping,
  93200. localAnchorA: constraintData.pivotA,
  93201. localAnchorB: constraintData.pivotB
  93202. });
  93203. break;
  93204. case BABYLON.PhysicsJoint.LockJoint:
  93205. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  93206. break;
  93207. case BABYLON.PhysicsJoint.PointToPointJoint:
  93208. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  93209. default:
  93210. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  93211. break;
  93212. }
  93213. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  93214. constraint.collideConnected = !!jointData.collision;
  93215. impostorJoint.joint.physicsJoint = constraint;
  93216. //don't add spring as constraint, as it is not one.
  93217. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  93218. this.world.addConstraint(constraint);
  93219. }
  93220. else {
  93221. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  93222. constraint.applyForce();
  93223. };
  93224. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  93225. }
  93226. };
  93227. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  93228. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  93229. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  93230. }
  93231. else {
  93232. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  93233. }
  93234. };
  93235. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  93236. var index;
  93237. var mat;
  93238. for (index = 0; index < this._physicsMaterials.length; index++) {
  93239. mat = this._physicsMaterials[index];
  93240. if (mat.friction === friction && mat.restitution === restitution) {
  93241. return mat;
  93242. }
  93243. }
  93244. var currentMat = new this.BJSCANNON.Material(name);
  93245. currentMat.friction = friction;
  93246. currentMat.restitution = restitution;
  93247. this._physicsMaterials.push(currentMat);
  93248. return currentMat;
  93249. };
  93250. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  93251. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  93252. };
  93253. CannonJSPlugin.prototype._createShape = function (impostor) {
  93254. var object = impostor.object;
  93255. var returnValue;
  93256. var extendSize = impostor.getObjectExtendSize();
  93257. switch (impostor.type) {
  93258. case BABYLON.PhysicsImpostor.SphereImpostor:
  93259. var radiusX = extendSize.x;
  93260. var radiusY = extendSize.y;
  93261. var radiusZ = extendSize.z;
  93262. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  93263. break;
  93264. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  93265. case BABYLON.PhysicsImpostor.CylinderImpostor:
  93266. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  93267. break;
  93268. case BABYLON.PhysicsImpostor.BoxImpostor:
  93269. var box = extendSize.scale(0.5);
  93270. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  93271. break;
  93272. case BABYLON.PhysicsImpostor.PlaneImpostor:
  93273. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  93274. returnValue = new this.BJSCANNON.Plane();
  93275. break;
  93276. case BABYLON.PhysicsImpostor.MeshImpostor:
  93277. // should transform the vertex data to world coordinates!!
  93278. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  93279. var rawFaces = object.getIndices ? object.getIndices() : [];
  93280. if (!rawVerts)
  93281. return;
  93282. // get only scale! so the object could transform correctly.
  93283. var oldPosition = object.position.clone();
  93284. var oldRotation = object.rotation && object.rotation.clone();
  93285. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  93286. object.position.copyFromFloats(0, 0, 0);
  93287. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  93288. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  93289. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  93290. var transform = object.computeWorldMatrix(true);
  93291. // convert rawVerts to object space
  93292. var temp = new Array();
  93293. var index;
  93294. for (index = 0; index < rawVerts.length; index += 3) {
  93295. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  93296. }
  93297. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  93298. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  93299. //now set back the transformation!
  93300. object.position.copyFrom(oldPosition);
  93301. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  93302. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  93303. break;
  93304. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  93305. var oldPosition2 = object.position.clone();
  93306. var oldRotation2 = object.rotation && object.rotation.clone();
  93307. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  93308. object.position.copyFromFloats(0, 0, 0);
  93309. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  93310. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  93311. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  93312. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  93313. returnValue = this._createHeightmap(object);
  93314. object.position.copyFrom(oldPosition2);
  93315. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  93316. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  93317. object.computeWorldMatrix(true);
  93318. break;
  93319. case BABYLON.PhysicsImpostor.ParticleImpostor:
  93320. returnValue = new this.BJSCANNON.Particle();
  93321. break;
  93322. }
  93323. return returnValue;
  93324. };
  93325. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  93326. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  93327. var transform = object.computeWorldMatrix(true);
  93328. // convert rawVerts to object space
  93329. var temp = new Array();
  93330. var index;
  93331. for (index = 0; index < pos.length; index += 3) {
  93332. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  93333. }
  93334. pos = temp;
  93335. var matrix = new Array();
  93336. //For now pointDepth will not be used and will be automatically calculated.
  93337. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  93338. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  93339. var boundingInfo = object.getBoundingInfo();
  93340. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  93341. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  93342. var elementSize = dim * 2 / arraySize;
  93343. for (var i = 0; i < pos.length; i = i + 3) {
  93344. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  93345. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  93346. var y = -pos[i + 2] + minY;
  93347. if (!matrix[x]) {
  93348. matrix[x] = [];
  93349. }
  93350. if (!matrix[x][z]) {
  93351. matrix[x][z] = y;
  93352. }
  93353. matrix[x][z] = Math.max(y, matrix[x][z]);
  93354. }
  93355. for (var x = 0; x <= arraySize; ++x) {
  93356. if (!matrix[x]) {
  93357. var loc = 1;
  93358. while (!matrix[(x + loc) % arraySize]) {
  93359. loc++;
  93360. }
  93361. matrix[x] = matrix[(x + loc) % arraySize].slice();
  93362. //console.log("missing x", x);
  93363. }
  93364. for (var z = 0; z <= arraySize; ++z) {
  93365. if (!matrix[x][z]) {
  93366. var loc = 1;
  93367. var newValue;
  93368. while (newValue === undefined) {
  93369. newValue = matrix[x][(z + loc++) % arraySize];
  93370. }
  93371. matrix[x][z] = newValue;
  93372. }
  93373. }
  93374. }
  93375. var shape = new this.BJSCANNON.Heightfield(matrix, {
  93376. elementSize: elementSize
  93377. });
  93378. //For future reference, needed for body transformation
  93379. shape.minY = minY;
  93380. return shape;
  93381. };
  93382. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  93383. var object = impostor.object;
  93384. //make sure it is updated...
  93385. object.computeWorldMatrix && object.computeWorldMatrix(true);
  93386. // The delta between the mesh position and the mesh bounding box center
  93387. var bInfo = object.getBoundingInfo();
  93388. if (!bInfo)
  93389. return;
  93390. var center = impostor.getObjectCenter();
  93391. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  93392. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  93393. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  93394. this._tmpPosition.copyFrom(center);
  93395. var quaternion = object.rotationQuaternion;
  93396. if (!quaternion) {
  93397. return;
  93398. }
  93399. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  93400. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  93401. //-90 DEG in X, precalculated
  93402. quaternion = quaternion.multiply(this._minus90X);
  93403. //Invert! (Precalculated, 90 deg in X)
  93404. //No need to clone. this will never change.
  93405. impostor.setDeltaRotation(this._plus90X);
  93406. }
  93407. //If it is a heightfield, if should be centered.
  93408. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  93409. var mesh = object;
  93410. var boundingInfo = mesh.getBoundingInfo();
  93411. //calculate the correct body position:
  93412. var rotationQuaternion = mesh.rotationQuaternion;
  93413. mesh.rotationQuaternion = this._tmpUnityRotation;
  93414. mesh.computeWorldMatrix(true);
  93415. //get original center with no rotation
  93416. var c = center.clone();
  93417. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  93418. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  93419. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  93420. mesh.setPreTransformMatrix(p);
  93421. mesh.computeWorldMatrix(true);
  93422. //calculate the translation
  93423. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  93424. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  93425. //add it inverted to the delta
  93426. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  93427. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  93428. //rotation is back
  93429. mesh.rotationQuaternion = rotationQuaternion;
  93430. mesh.setPreTransformMatrix(oldPivot);
  93431. mesh.computeWorldMatrix(true);
  93432. }
  93433. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  93434. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  93435. //this._tmpPosition.copyFrom(object.position);
  93436. }
  93437. impostor.setDeltaPosition(this._tmpDeltaPosition);
  93438. //Now update the impostor object
  93439. impostor.physicsBody.position.copy(this._tmpPosition);
  93440. impostor.physicsBody.quaternion.copy(quaternion);
  93441. };
  93442. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  93443. impostor.object.position.copyFrom(impostor.physicsBody.position);
  93444. if (impostor.object.rotationQuaternion) {
  93445. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  93446. }
  93447. };
  93448. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  93449. impostor.physicsBody.position.copy(newPosition);
  93450. impostor.physicsBody.quaternion.copy(newRotation);
  93451. };
  93452. CannonJSPlugin.prototype.isSupported = function () {
  93453. return this.BJSCANNON !== undefined;
  93454. };
  93455. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  93456. impostor.physicsBody.velocity.copy(velocity);
  93457. };
  93458. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  93459. impostor.physicsBody.angularVelocity.copy(velocity);
  93460. };
  93461. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  93462. var v = impostor.physicsBody.velocity;
  93463. if (!v) {
  93464. return null;
  93465. }
  93466. return new BABYLON.Vector3(v.x, v.y, v.z);
  93467. };
  93468. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  93469. var v = impostor.physicsBody.angularVelocity;
  93470. if (!v) {
  93471. return null;
  93472. }
  93473. return new BABYLON.Vector3(v.x, v.y, v.z);
  93474. };
  93475. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  93476. impostor.physicsBody.mass = mass;
  93477. impostor.physicsBody.updateMassProperties();
  93478. };
  93479. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  93480. return impostor.physicsBody.mass;
  93481. };
  93482. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  93483. return impostor.physicsBody.material.friction;
  93484. };
  93485. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  93486. impostor.physicsBody.material.friction = friction;
  93487. };
  93488. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  93489. return impostor.physicsBody.material.restitution;
  93490. };
  93491. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  93492. impostor.physicsBody.material.restitution = restitution;
  93493. };
  93494. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  93495. impostor.physicsBody.sleep();
  93496. };
  93497. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  93498. impostor.physicsBody.wakeUp();
  93499. };
  93500. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  93501. joint.physicsJoint.distance = maxDistance;
  93502. };
  93503. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  93504. // if (!motorIndex) {
  93505. // joint.physicsJoint.enableMotor();
  93506. // }
  93507. // }
  93508. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  93509. // if (!motorIndex) {
  93510. // joint.physicsJoint.disableMotor();
  93511. // }
  93512. // }
  93513. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  93514. if (!motorIndex) {
  93515. joint.physicsJoint.enableMotor();
  93516. joint.physicsJoint.setMotorSpeed(speed);
  93517. if (maxForce) {
  93518. this.setLimit(joint, maxForce);
  93519. }
  93520. }
  93521. };
  93522. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  93523. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  93524. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  93525. };
  93526. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  93527. var body = impostor.physicsBody;
  93528. mesh.position.x = body.position.x;
  93529. mesh.position.y = body.position.y;
  93530. mesh.position.z = body.position.z;
  93531. if (mesh.rotationQuaternion) {
  93532. mesh.rotationQuaternion.x = body.quaternion.x;
  93533. mesh.rotationQuaternion.y = body.quaternion.y;
  93534. mesh.rotationQuaternion.z = body.quaternion.z;
  93535. mesh.rotationQuaternion.w = body.quaternion.w;
  93536. }
  93537. };
  93538. CannonJSPlugin.prototype.getRadius = function (impostor) {
  93539. var shape = impostor.physicsBody.shapes[0];
  93540. return shape.boundingSphereRadius;
  93541. };
  93542. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93543. var shape = impostor.physicsBody.shapes[0];
  93544. result.x = shape.halfExtents.x * 2;
  93545. result.y = shape.halfExtents.y * 2;
  93546. result.z = shape.halfExtents.z * 2;
  93547. };
  93548. CannonJSPlugin.prototype.dispose = function () {
  93549. };
  93550. CannonJSPlugin.prototype._extendNamespace = function () {
  93551. //this will force cannon to execute at least one step when using interpolation
  93552. var step_tmp1 = new this.BJSCANNON.Vec3();
  93553. var Engine = this.BJSCANNON;
  93554. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  93555. maxSubSteps = maxSubSteps || 10;
  93556. timeSinceLastCalled = timeSinceLastCalled || 0;
  93557. if (timeSinceLastCalled === 0) {
  93558. this.internalStep(dt);
  93559. this.time += dt;
  93560. }
  93561. else {
  93562. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  93563. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  93564. var t0 = performance.now();
  93565. for (var i = 0; i !== internalSteps; i++) {
  93566. this.internalStep(dt);
  93567. if (performance.now() - t0 > dt * 1000) {
  93568. break;
  93569. }
  93570. }
  93571. this.time += timeSinceLastCalled;
  93572. var h = this.time % dt;
  93573. var h_div_dt = h / dt;
  93574. var interpvelo = step_tmp1;
  93575. var bodies = this.bodies;
  93576. for (var j = 0; j !== bodies.length; j++) {
  93577. var b = bodies[j];
  93578. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  93579. b.position.vsub(b.previousPosition, interpvelo);
  93580. interpvelo.scale(h_div_dt, interpvelo);
  93581. b.position.vadd(interpvelo, b.interpolatedPosition);
  93582. }
  93583. else {
  93584. b.interpolatedPosition.copy(b.position);
  93585. b.interpolatedQuaternion.copy(b.quaternion);
  93586. }
  93587. }
  93588. }
  93589. };
  93590. };
  93591. return CannonJSPlugin;
  93592. }());
  93593. BABYLON.CannonJSPlugin = CannonJSPlugin;
  93594. })(BABYLON || (BABYLON = {}));
  93595. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  93596. var BABYLON;
  93597. (function (BABYLON) {
  93598. /** @hidden */
  93599. var OimoJSPlugin = /** @class */ (function () {
  93600. function OimoJSPlugin(iterations) {
  93601. this.name = "OimoJSPlugin";
  93602. this._tmpImpostorsArray = [];
  93603. this._tmpPositionVector = BABYLON.Vector3.Zero();
  93604. this.BJSOIMO = OIMO;
  93605. this.world = new this.BJSOIMO.World({
  93606. iterations: iterations
  93607. });
  93608. this.world.clear();
  93609. }
  93610. OimoJSPlugin.prototype.setGravity = function (gravity) {
  93611. this.world.gravity.copy(gravity);
  93612. };
  93613. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  93614. this.world.timeStep = timeStep;
  93615. };
  93616. OimoJSPlugin.prototype.getTimeStep = function () {
  93617. return this.world.timeStep;
  93618. };
  93619. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  93620. var _this = this;
  93621. impostors.forEach(function (impostor) {
  93622. impostor.beforeStep();
  93623. });
  93624. this.world.step();
  93625. impostors.forEach(function (impostor) {
  93626. impostor.afterStep();
  93627. //update the ordered impostors array
  93628. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  93629. });
  93630. //check for collisions
  93631. var contact = this.world.contacts;
  93632. while (contact !== null) {
  93633. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  93634. contact = contact.next;
  93635. continue;
  93636. }
  93637. //is this body colliding with any other? get the impostor
  93638. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  93639. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  93640. if (!mainImpostor || !collidingImpostor) {
  93641. contact = contact.next;
  93642. continue;
  93643. }
  93644. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  93645. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  93646. contact = contact.next;
  93647. }
  93648. };
  93649. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  93650. var mass = impostor.physicsBody.mass;
  93651. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  93652. };
  93653. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  93654. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  93655. this.applyImpulse(impostor, force, contactPoint);
  93656. };
  93657. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  93658. var _this = this;
  93659. //parent-child relationship. Does this impostor has a parent impostor?
  93660. if (impostor.parent) {
  93661. if (impostor.physicsBody) {
  93662. this.removePhysicsBody(impostor);
  93663. //TODO is that needed?
  93664. impostor.forceUpdate();
  93665. }
  93666. return;
  93667. }
  93668. if (impostor.isBodyInitRequired()) {
  93669. var bodyConfig = {
  93670. name: impostor.uniqueId,
  93671. //Oimo must have mass, also for static objects.
  93672. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  93673. size: [],
  93674. type: [],
  93675. pos: [],
  93676. posShape: [],
  93677. rot: [],
  93678. rotShape: [],
  93679. move: impostor.getParam("mass") !== 0,
  93680. density: impostor.getParam("mass"),
  93681. friction: impostor.getParam("friction"),
  93682. restitution: impostor.getParam("restitution"),
  93683. //Supporting older versions of Oimo
  93684. world: this.world
  93685. };
  93686. var impostors = [impostor];
  93687. var addToArray = function (parent) {
  93688. if (!parent.getChildMeshes)
  93689. return;
  93690. parent.getChildMeshes().forEach(function (m) {
  93691. if (m.physicsImpostor) {
  93692. impostors.push(m.physicsImpostor);
  93693. //m.physicsImpostor._init();
  93694. }
  93695. });
  93696. };
  93697. addToArray(impostor.object);
  93698. var checkWithEpsilon_1 = function (value) {
  93699. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  93700. };
  93701. var globalQuaternion_1 = new BABYLON.Quaternion();
  93702. impostors.forEach(function (i) {
  93703. if (!i.object.rotationQuaternion) {
  93704. return;
  93705. }
  93706. //get the correct bounding box
  93707. var oldQuaternion = i.object.rotationQuaternion;
  93708. globalQuaternion_1 = oldQuaternion.clone();
  93709. var rot = oldQuaternion.toEulerAngles();
  93710. var extendSize = i.getObjectExtendSize();
  93711. var radToDeg = 57.295779513082320876;
  93712. if (i === impostor) {
  93713. var center = impostor.getObjectCenter();
  93714. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  93715. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  93716. //Can also use Array.prototype.push.apply
  93717. bodyConfig.pos.push(center.x);
  93718. bodyConfig.pos.push(center.y);
  93719. bodyConfig.pos.push(center.z);
  93720. bodyConfig.posShape.push(0, 0, 0);
  93721. //tmp solution
  93722. bodyConfig.rot.push(0);
  93723. bodyConfig.rot.push(0);
  93724. bodyConfig.rot.push(0);
  93725. bodyConfig.rotShape.push(0, 0, 0);
  93726. }
  93727. else {
  93728. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  93729. bodyConfig.posShape.push(localPosition.x);
  93730. bodyConfig.posShape.push(localPosition.y);
  93731. bodyConfig.posShape.push(localPosition.z);
  93732. bodyConfig.pos.push(0, 0, 0);
  93733. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  93734. bodyConfig.rot.push(0);
  93735. bodyConfig.rot.push(0);
  93736. bodyConfig.rot.push(0);
  93737. bodyConfig.rotShape.push(rot.x * radToDeg);
  93738. bodyConfig.rotShape.push(rot.y * radToDeg);
  93739. bodyConfig.rotShape.push(rot.z * radToDeg);
  93740. }
  93741. // register mesh
  93742. switch (i.type) {
  93743. case BABYLON.PhysicsImpostor.ParticleImpostor:
  93744. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  93745. case BABYLON.PhysicsImpostor.SphereImpostor:
  93746. var radiusX = extendSize.x;
  93747. var radiusY = extendSize.y;
  93748. var radiusZ = extendSize.z;
  93749. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  93750. bodyConfig.type.push('sphere');
  93751. //due to the way oimo works with compounds, add 3 times
  93752. bodyConfig.size.push(size);
  93753. bodyConfig.size.push(size);
  93754. bodyConfig.size.push(size);
  93755. break;
  93756. case BABYLON.PhysicsImpostor.CylinderImpostor:
  93757. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  93758. var sizeY = checkWithEpsilon_1(extendSize.y);
  93759. bodyConfig.type.push('cylinder');
  93760. bodyConfig.size.push(sizeX);
  93761. bodyConfig.size.push(sizeY);
  93762. //due to the way oimo works with compounds, add one more value.
  93763. bodyConfig.size.push(sizeY);
  93764. break;
  93765. case BABYLON.PhysicsImpostor.PlaneImpostor:
  93766. case BABYLON.PhysicsImpostor.BoxImpostor:
  93767. default:
  93768. var sizeX = checkWithEpsilon_1(extendSize.x);
  93769. var sizeY = checkWithEpsilon_1(extendSize.y);
  93770. var sizeZ = checkWithEpsilon_1(extendSize.z);
  93771. bodyConfig.type.push('box');
  93772. //if (i === impostor) {
  93773. bodyConfig.size.push(sizeX);
  93774. bodyConfig.size.push(sizeY);
  93775. bodyConfig.size.push(sizeZ);
  93776. //} else {
  93777. // bodyConfig.size.push(0,0,0);
  93778. //}
  93779. break;
  93780. }
  93781. //actually not needed, but hey...
  93782. i.object.rotationQuaternion = oldQuaternion;
  93783. });
  93784. impostor.physicsBody = this.world.add(bodyConfig);
  93785. // set the quaternion, ignoring the previously defined (euler) rotation
  93786. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  93787. // update with delta 0, so the body will reveive the new rotation.
  93788. impostor.physicsBody.updatePosition(0);
  93789. }
  93790. else {
  93791. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  93792. }
  93793. impostor.setDeltaPosition(this._tmpPositionVector);
  93794. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  93795. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  93796. };
  93797. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  93798. //impostor.physicsBody.dispose();
  93799. //Same as : (older oimo versions)
  93800. this.world.removeRigidBody(impostor.physicsBody);
  93801. };
  93802. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  93803. var mainBody = impostorJoint.mainImpostor.physicsBody;
  93804. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  93805. if (!mainBody || !connectedBody) {
  93806. return;
  93807. }
  93808. var jointData = impostorJoint.joint.jointData;
  93809. var options = jointData.nativeParams || {};
  93810. var type;
  93811. var nativeJointData = {
  93812. body1: mainBody,
  93813. body2: connectedBody,
  93814. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  93815. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  93816. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  93817. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  93818. min: options.min,
  93819. max: options.max,
  93820. collision: options.collision || jointData.collision,
  93821. spring: options.spring,
  93822. //supporting older version of Oimo
  93823. world: this.world
  93824. };
  93825. switch (impostorJoint.joint.type) {
  93826. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  93827. type = "jointBall";
  93828. break;
  93829. case BABYLON.PhysicsJoint.SpringJoint:
  93830. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  93831. var springData = jointData;
  93832. nativeJointData.min = springData.length || nativeJointData.min;
  93833. //Max should also be set, just make sure it is at least min
  93834. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  93835. case BABYLON.PhysicsJoint.DistanceJoint:
  93836. type = "jointDistance";
  93837. nativeJointData.max = jointData.maxDistance;
  93838. break;
  93839. case BABYLON.PhysicsJoint.PrismaticJoint:
  93840. type = "jointPrisme";
  93841. break;
  93842. case BABYLON.PhysicsJoint.SliderJoint:
  93843. type = "jointSlide";
  93844. break;
  93845. case BABYLON.PhysicsJoint.WheelJoint:
  93846. type = "jointWheel";
  93847. break;
  93848. case BABYLON.PhysicsJoint.HingeJoint:
  93849. default:
  93850. type = "jointHinge";
  93851. break;
  93852. }
  93853. nativeJointData.type = type;
  93854. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  93855. };
  93856. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  93857. //Bug in Oimo prevents us from disposing a joint in the playground
  93858. //joint.joint.physicsJoint.dispose();
  93859. //So we will bruteforce it!
  93860. try {
  93861. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  93862. }
  93863. catch (e) {
  93864. BABYLON.Tools.Warn(e);
  93865. }
  93866. };
  93867. OimoJSPlugin.prototype.isSupported = function () {
  93868. return this.BJSOIMO !== undefined;
  93869. };
  93870. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  93871. if (!impostor.physicsBody.sleeping) {
  93872. //TODO check that
  93873. /*if (impostor.physicsBody.shapes.next) {
  93874. var parentShape = this._getLastShape(impostor.physicsBody);
  93875. impostor.object.position.copyFrom(parentShape.position);
  93876. console.log(parentShape.position);
  93877. } else {*/
  93878. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  93879. //}
  93880. if (impostor.object.rotationQuaternion) {
  93881. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  93882. }
  93883. }
  93884. };
  93885. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  93886. var body = impostor.physicsBody;
  93887. body.position.copy(newPosition);
  93888. body.orientation.copy(newRotation);
  93889. body.syncShapes();
  93890. body.awake();
  93891. };
  93892. /*private _getLastShape(body: any): any {
  93893. var lastShape = body.shapes;
  93894. while (lastShape.next) {
  93895. lastShape = lastShape.next;
  93896. }
  93897. return lastShape;
  93898. }*/
  93899. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  93900. impostor.physicsBody.linearVelocity.copy(velocity);
  93901. };
  93902. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  93903. impostor.physicsBody.angularVelocity.copy(velocity);
  93904. };
  93905. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  93906. var v = impostor.physicsBody.linearVelocity;
  93907. if (!v) {
  93908. return null;
  93909. }
  93910. return new BABYLON.Vector3(v.x, v.y, v.z);
  93911. };
  93912. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  93913. var v = impostor.physicsBody.angularVelocity;
  93914. if (!v) {
  93915. return null;
  93916. }
  93917. return new BABYLON.Vector3(v.x, v.y, v.z);
  93918. };
  93919. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  93920. var staticBody = mass === 0;
  93921. //this will actually set the body's density and not its mass.
  93922. //But this is how oimo treats the mass variable.
  93923. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  93924. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  93925. };
  93926. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  93927. return impostor.physicsBody.shapes.density;
  93928. };
  93929. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  93930. return impostor.physicsBody.shapes.friction;
  93931. };
  93932. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  93933. impostor.physicsBody.shapes.friction = friction;
  93934. };
  93935. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  93936. return impostor.physicsBody.shapes.restitution;
  93937. };
  93938. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  93939. impostor.physicsBody.shapes.restitution = restitution;
  93940. };
  93941. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  93942. impostor.physicsBody.sleep();
  93943. };
  93944. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  93945. impostor.physicsBody.awake();
  93946. };
  93947. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  93948. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  93949. if (minDistance !== void 0) {
  93950. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  93951. }
  93952. };
  93953. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  93954. //TODO separate rotational and transational motors.
  93955. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93956. if (motor) {
  93957. motor.setMotor(speed, maxForce);
  93958. }
  93959. };
  93960. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  93961. //TODO separate rotational and transational motors.
  93962. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93963. if (motor) {
  93964. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  93965. }
  93966. };
  93967. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  93968. var body = impostor.physicsBody;
  93969. mesh.position.x = body.position.x;
  93970. mesh.position.y = body.position.y;
  93971. mesh.position.z = body.position.z;
  93972. if (mesh.rotationQuaternion) {
  93973. mesh.rotationQuaternion.x = body.orientation.x;
  93974. mesh.rotationQuaternion.y = body.orientation.y;
  93975. mesh.rotationQuaternion.z = body.orientation.z;
  93976. mesh.rotationQuaternion.w = body.orientation.s;
  93977. }
  93978. };
  93979. OimoJSPlugin.prototype.getRadius = function (impostor) {
  93980. return impostor.physicsBody.shapes.radius;
  93981. };
  93982. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93983. var shape = impostor.physicsBody.shapes;
  93984. result.x = shape.halfWidth * 2;
  93985. result.y = shape.halfHeight * 2;
  93986. result.z = shape.halfDepth * 2;
  93987. };
  93988. OimoJSPlugin.prototype.dispose = function () {
  93989. this.world.clear();
  93990. };
  93991. return OimoJSPlugin;
  93992. }());
  93993. BABYLON.OimoJSPlugin = OimoJSPlugin;
  93994. })(BABYLON || (BABYLON = {}));
  93995. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  93996. var BABYLON;
  93997. (function (BABYLON) {
  93998. /**
  93999. * Gets the current physics engine
  94000. * @returns a IPhysicsEngine or null if none attached
  94001. */
  94002. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  94003. return this._physicsEngine;
  94004. };
  94005. /**
  94006. * Enables physics to the current scene
  94007. * @param gravity defines the scene's gravity for the physics engine
  94008. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  94009. * @return a boolean indicating if the physics engine was initialized
  94010. */
  94011. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  94012. if (gravity === void 0) { gravity = null; }
  94013. if (this._physicsEngine) {
  94014. return true;
  94015. }
  94016. // Register the component to the scene
  94017. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  94018. if (!component) {
  94019. component = new PhysicsEngineSceneComponent(this);
  94020. this._addComponent(component);
  94021. }
  94022. try {
  94023. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  94024. return true;
  94025. }
  94026. catch (e) {
  94027. BABYLON.Tools.Error(e.message);
  94028. return false;
  94029. }
  94030. };
  94031. /**
  94032. * Disables and disposes the physics engine associated with the scene
  94033. */
  94034. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  94035. if (!this._physicsEngine) {
  94036. return;
  94037. }
  94038. this._physicsEngine.dispose();
  94039. this._physicsEngine = null;
  94040. };
  94041. /**
  94042. * Gets a boolean indicating if there is an active physics engine
  94043. * @returns a boolean indicating if there is an active physics engine
  94044. */
  94045. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  94046. return this._physicsEngine !== undefined;
  94047. };
  94048. /**
  94049. * Deletes a physics compound impostor
  94050. * @param compound defines the compound to delete
  94051. */
  94052. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  94053. var mesh = compound.parts[0].mesh;
  94054. if (mesh.physicsImpostor) {
  94055. mesh.physicsImpostor.dispose( /*true*/);
  94056. mesh.physicsImpostor = null;
  94057. }
  94058. };
  94059. /** @hidden */
  94060. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  94061. if (this._physicsEngine) {
  94062. this.onBeforePhysicsObservable.notifyObservers(this);
  94063. this._physicsEngine._step(step / 1000);
  94064. this.onAfterPhysicsObservable.notifyObservers(this);
  94065. }
  94066. };
  94067. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  94068. get: function () {
  94069. return this._physicsImpostor;
  94070. },
  94071. set: function (value) {
  94072. var _this = this;
  94073. if (this._physicsImpostor === value) {
  94074. return;
  94075. }
  94076. if (this._disposePhysicsObserver) {
  94077. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  94078. }
  94079. this._physicsImpostor = value;
  94080. if (value) {
  94081. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  94082. // Physics
  94083. if (_this.physicsImpostor) {
  94084. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  94085. _this.physicsImpostor = null;
  94086. }
  94087. });
  94088. }
  94089. },
  94090. enumerable: true,
  94091. configurable: true
  94092. });
  94093. /**
  94094. * Gets the current physics impostor
  94095. * @see http://doc.babylonjs.com/features/physics_engine
  94096. * @returns a physics impostor or null
  94097. */
  94098. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  94099. return this.physicsImpostor;
  94100. };
  94101. /**
  94102. * Apply a physic impulse to the mesh
  94103. * @param force defines the force to apply
  94104. * @param contactPoint defines where to apply the force
  94105. * @returns the current mesh
  94106. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  94107. */
  94108. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  94109. if (!this.physicsImpostor) {
  94110. return this;
  94111. }
  94112. this.physicsImpostor.applyImpulse(force, contactPoint);
  94113. return this;
  94114. };
  94115. /**
  94116. * Creates a physic joint between two meshes
  94117. * @param otherMesh defines the other mesh to use
  94118. * @param pivot1 defines the pivot to use on this mesh
  94119. * @param pivot2 defines the pivot to use on the other mesh
  94120. * @param options defines additional options (can be plugin dependent)
  94121. * @returns the current mesh
  94122. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  94123. */
  94124. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  94125. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  94126. return this;
  94127. }
  94128. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  94129. mainPivot: pivot1,
  94130. connectedPivot: pivot2,
  94131. nativeParams: options
  94132. });
  94133. return this;
  94134. };
  94135. /**
  94136. * Defines the physics engine scene component responsible to manage a physics engine
  94137. */
  94138. var PhysicsEngineSceneComponent = /** @class */ (function () {
  94139. /**
  94140. * Creates a new instance of the component for the given scene
  94141. * @param scene Defines the scene to register the component in
  94142. */
  94143. function PhysicsEngineSceneComponent(scene) {
  94144. var _this = this;
  94145. /**
  94146. * The component name helpful to identify the component in the list of scene components.
  94147. */
  94148. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  94149. this.scene = scene;
  94150. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  94151. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  94152. // Replace the function used to get the deterministic frame time
  94153. this.scene.getDeterministicFrameTime = function () {
  94154. if (_this.scene._physicsEngine) {
  94155. return _this.scene._physicsEngine.getTimeStep() * 1000;
  94156. }
  94157. return 1000.0 / 60.0;
  94158. };
  94159. }
  94160. /**
  94161. * Registers the component in a given scene
  94162. */
  94163. PhysicsEngineSceneComponent.prototype.register = function () {
  94164. };
  94165. /**
  94166. * Rebuilds the elements related to this component in case of
  94167. * context lost for instance.
  94168. */
  94169. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  94170. // Nothing to do for this component
  94171. };
  94172. /**
  94173. * Disposes the component and the associated ressources
  94174. */
  94175. PhysicsEngineSceneComponent.prototype.dispose = function () {
  94176. this.scene.onBeforePhysicsObservable.clear();
  94177. this.scene.onAfterPhysicsObservable.clear();
  94178. if (this.scene._physicsEngine) {
  94179. this.scene.disablePhysicsEngine();
  94180. }
  94181. };
  94182. return PhysicsEngineSceneComponent;
  94183. }());
  94184. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  94185. })(BABYLON || (BABYLON = {}));
  94186. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  94187. var BABYLON;
  94188. (function (BABYLON) {
  94189. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  94190. // All values and structures referenced from:
  94191. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  94192. var DDS_MAGIC = 0x20534444;
  94193. var
  94194. //DDSD_CAPS = 0x1,
  94195. //DDSD_HEIGHT = 0x2,
  94196. //DDSD_WIDTH = 0x4,
  94197. //DDSD_PITCH = 0x8,
  94198. //DDSD_PIXELFORMAT = 0x1000,
  94199. DDSD_MIPMAPCOUNT = 0x20000;
  94200. //DDSD_LINEARSIZE = 0x80000,
  94201. //DDSD_DEPTH = 0x800000;
  94202. // var DDSCAPS_COMPLEX = 0x8,
  94203. // DDSCAPS_MIPMAP = 0x400000,
  94204. // DDSCAPS_TEXTURE = 0x1000;
  94205. var DDSCAPS2_CUBEMAP = 0x200;
  94206. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  94207. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  94208. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  94209. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  94210. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  94211. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  94212. // DDSCAPS2_VOLUME = 0x200000;
  94213. var
  94214. //DDPF_ALPHAPIXELS = 0x1,
  94215. //DDPF_ALPHA = 0x2,
  94216. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  94217. //DDPF_YUV = 0x200,
  94218. DDPF_LUMINANCE = 0x20000;
  94219. function FourCCToInt32(value) {
  94220. return value.charCodeAt(0) +
  94221. (value.charCodeAt(1) << 8) +
  94222. (value.charCodeAt(2) << 16) +
  94223. (value.charCodeAt(3) << 24);
  94224. }
  94225. function Int32ToFourCC(value) {
  94226. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  94227. }
  94228. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  94229. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  94230. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  94231. var FOURCC_DX10 = FourCCToInt32("DX10");
  94232. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  94233. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  94234. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  94235. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  94236. var headerLengthInt = 31; // The header length in 32 bit ints
  94237. // Offsets into the header array
  94238. var off_magic = 0;
  94239. var off_size = 1;
  94240. var off_flags = 2;
  94241. var off_height = 3;
  94242. var off_width = 4;
  94243. var off_mipmapCount = 7;
  94244. var off_pfFlags = 20;
  94245. var off_pfFourCC = 21;
  94246. var off_RGBbpp = 22;
  94247. var off_RMask = 23;
  94248. var off_GMask = 24;
  94249. var off_BMask = 25;
  94250. var off_AMask = 26;
  94251. // var off_caps1 = 27;
  94252. var off_caps2 = 28;
  94253. // var off_caps3 = 29;
  94254. // var off_caps4 = 30;
  94255. var off_dxgiFormat = 32;
  94256. ;
  94257. /**
  94258. * Class used to provide DDS decompression tools
  94259. */
  94260. var DDSTools = /** @class */ (function () {
  94261. function DDSTools() {
  94262. }
  94263. /**
  94264. * Gets DDS information from an array buffer
  94265. * @param arrayBuffer defines the array buffer to read data from
  94266. * @returns the DDS information
  94267. */
  94268. DDSTools.GetDDSInfo = function (arrayBuffer) {
  94269. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  94270. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  94271. var mipmapCount = 1;
  94272. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  94273. mipmapCount = Math.max(1, header[off_mipmapCount]);
  94274. }
  94275. var fourCC = header[off_pfFourCC];
  94276. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  94277. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94278. switch (fourCC) {
  94279. case FOURCC_D3DFMT_R16G16B16A16F:
  94280. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94281. break;
  94282. case FOURCC_D3DFMT_R32G32B32A32F:
  94283. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94284. break;
  94285. case FOURCC_DX10:
  94286. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  94287. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94288. break;
  94289. }
  94290. }
  94291. return {
  94292. width: header[off_width],
  94293. height: header[off_height],
  94294. mipmapCount: mipmapCount,
  94295. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  94296. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  94297. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  94298. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  94299. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  94300. dxgiFormat: dxgiFormat,
  94301. textureType: textureType
  94302. };
  94303. };
  94304. DDSTools._ToHalfFloat = function (value) {
  94305. if (!DDSTools._FloatView) {
  94306. DDSTools._FloatView = new Float32Array(1);
  94307. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  94308. }
  94309. DDSTools._FloatView[0] = value;
  94310. var x = DDSTools._Int32View[0];
  94311. var bits = (x >> 16) & 0x8000; /* Get the sign */
  94312. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  94313. var e = (x >> 23) & 0xff; /* Using int is faster here */
  94314. /* If zero, or denormal, or exponent underflows too much for a denormal
  94315. * half, return signed zero. */
  94316. if (e < 103) {
  94317. return bits;
  94318. }
  94319. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  94320. if (e > 142) {
  94321. bits |= 0x7c00;
  94322. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  94323. * not Inf, so make sure we set one mantissa bit too. */
  94324. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  94325. return bits;
  94326. }
  94327. /* If exponent underflows but not too much, return a denormal */
  94328. if (e < 113) {
  94329. m |= 0x0800;
  94330. /* Extra rounding may overflow and set mantissa to 0 and exponent
  94331. * to 1, which is OK. */
  94332. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  94333. return bits;
  94334. }
  94335. bits |= ((e - 112) << 10) | (m >> 1);
  94336. bits += m & 1;
  94337. return bits;
  94338. };
  94339. DDSTools._FromHalfFloat = function (value) {
  94340. var s = (value & 0x8000) >> 15;
  94341. var e = (value & 0x7C00) >> 10;
  94342. var f = value & 0x03FF;
  94343. if (e === 0) {
  94344. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  94345. }
  94346. else if (e == 0x1F) {
  94347. return f ? NaN : ((s ? -1 : 1) * Infinity);
  94348. }
  94349. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  94350. };
  94351. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  94352. var destArray = new Float32Array(dataLength);
  94353. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  94354. var index = 0;
  94355. for (var y = 0; y < height; y++) {
  94356. for (var x = 0; x < width; x++) {
  94357. var srcPos = (x + y * width) * 4;
  94358. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  94359. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  94360. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  94361. if (DDSTools.StoreLODInAlphaChannel) {
  94362. destArray[index + 3] = lod;
  94363. }
  94364. else {
  94365. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  94366. }
  94367. index += 4;
  94368. }
  94369. }
  94370. return destArray;
  94371. };
  94372. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  94373. if (DDSTools.StoreLODInAlphaChannel) {
  94374. var destArray = new Uint16Array(dataLength);
  94375. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  94376. var index = 0;
  94377. for (var y = 0; y < height; y++) {
  94378. for (var x = 0; x < width; x++) {
  94379. var srcPos = (x + y * width) * 4;
  94380. destArray[index] = srcData[srcPos];
  94381. destArray[index + 1] = srcData[srcPos + 1];
  94382. destArray[index + 2] = srcData[srcPos + 2];
  94383. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  94384. index += 4;
  94385. }
  94386. }
  94387. return destArray;
  94388. }
  94389. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  94390. };
  94391. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  94392. if (DDSTools.StoreLODInAlphaChannel) {
  94393. var destArray = new Float32Array(dataLength);
  94394. var srcData = new Float32Array(arrayBuffer, dataOffset);
  94395. var index = 0;
  94396. for (var y = 0; y < height; y++) {
  94397. for (var x = 0; x < width; x++) {
  94398. var srcPos = (x + y * width) * 4;
  94399. destArray[index] = srcData[srcPos];
  94400. destArray[index + 1] = srcData[srcPos + 1];
  94401. destArray[index + 2] = srcData[srcPos + 2];
  94402. destArray[index + 3] = lod;
  94403. index += 4;
  94404. }
  94405. }
  94406. return destArray;
  94407. }
  94408. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  94409. };
  94410. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  94411. var destArray = new Uint8Array(dataLength);
  94412. var srcData = new Float32Array(arrayBuffer, dataOffset);
  94413. var index = 0;
  94414. for (var y = 0; y < height; y++) {
  94415. for (var x = 0; x < width; x++) {
  94416. var srcPos = (x + y * width) * 4;
  94417. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  94418. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  94419. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  94420. if (DDSTools.StoreLODInAlphaChannel) {
  94421. destArray[index + 3] = lod;
  94422. }
  94423. else {
  94424. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  94425. }
  94426. index += 4;
  94427. }
  94428. }
  94429. return destArray;
  94430. };
  94431. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  94432. var destArray = new Uint8Array(dataLength);
  94433. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  94434. var index = 0;
  94435. for (var y = 0; y < height; y++) {
  94436. for (var x = 0; x < width; x++) {
  94437. var srcPos = (x + y * width) * 4;
  94438. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  94439. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  94440. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  94441. if (DDSTools.StoreLODInAlphaChannel) {
  94442. destArray[index + 3] = lod;
  94443. }
  94444. else {
  94445. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  94446. }
  94447. index += 4;
  94448. }
  94449. }
  94450. return destArray;
  94451. };
  94452. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  94453. var byteArray = new Uint8Array(dataLength);
  94454. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  94455. var index = 0;
  94456. for (var y = 0; y < height; y++) {
  94457. for (var x = 0; x < width; x++) {
  94458. var srcPos = (x + y * width) * 4;
  94459. byteArray[index] = srcData[srcPos + rOffset];
  94460. byteArray[index + 1] = srcData[srcPos + gOffset];
  94461. byteArray[index + 2] = srcData[srcPos + bOffset];
  94462. byteArray[index + 3] = srcData[srcPos + aOffset];
  94463. index += 4;
  94464. }
  94465. }
  94466. return byteArray;
  94467. };
  94468. DDSTools._ExtractLongWordOrder = function (value) {
  94469. if (value === 0 || value === 255 || value === -16777216) {
  94470. return 0;
  94471. }
  94472. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  94473. };
  94474. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  94475. var byteArray = new Uint8Array(dataLength);
  94476. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  94477. var index = 0;
  94478. for (var y = 0; y < height; y++) {
  94479. for (var x = 0; x < width; x++) {
  94480. var srcPos = (x + y * width) * 3;
  94481. byteArray[index] = srcData[srcPos + rOffset];
  94482. byteArray[index + 1] = srcData[srcPos + gOffset];
  94483. byteArray[index + 2] = srcData[srcPos + bOffset];
  94484. index += 3;
  94485. }
  94486. }
  94487. return byteArray;
  94488. };
  94489. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  94490. var byteArray = new Uint8Array(dataLength);
  94491. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  94492. var index = 0;
  94493. for (var y = 0; y < height; y++) {
  94494. for (var x = 0; x < width; x++) {
  94495. var srcPos = (x + y * width);
  94496. byteArray[index] = srcData[srcPos];
  94497. index++;
  94498. }
  94499. }
  94500. return byteArray;
  94501. };
  94502. /**
  94503. * Uploads DDS Levels to a Babylon Texture
  94504. * @hidden
  94505. */
  94506. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  94507. if (lodIndex === void 0) { lodIndex = -1; }
  94508. var sphericalPolynomialFaces = null;
  94509. if (info.sphericalPolynomial) {
  94510. sphericalPolynomialFaces = new Array();
  94511. }
  94512. var ext = engine.getCaps().s3tc;
  94513. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  94514. var fourCC, width, height, dataLength = 0, dataOffset;
  94515. var byteArray, mipmapCount, mip;
  94516. var internalCompressedFormat = 0;
  94517. var blockBytes = 1;
  94518. if (header[off_magic] !== DDS_MAGIC) {
  94519. BABYLON.Tools.Error("Invalid magic number in DDS header");
  94520. return;
  94521. }
  94522. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  94523. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  94524. return;
  94525. }
  94526. if (info.isCompressed && !ext) {
  94527. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  94528. return;
  94529. }
  94530. var bpp = header[off_RGBbpp];
  94531. dataOffset = header[off_size] + 4;
  94532. var computeFormats = false;
  94533. if (info.isFourCC) {
  94534. fourCC = header[off_pfFourCC];
  94535. switch (fourCC) {
  94536. case FOURCC_DXT1:
  94537. blockBytes = 8;
  94538. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  94539. break;
  94540. case FOURCC_DXT3:
  94541. blockBytes = 16;
  94542. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  94543. break;
  94544. case FOURCC_DXT5:
  94545. blockBytes = 16;
  94546. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  94547. break;
  94548. case FOURCC_D3DFMT_R16G16B16A16F:
  94549. computeFormats = true;
  94550. break;
  94551. case FOURCC_D3DFMT_R32G32B32A32F:
  94552. computeFormats = true;
  94553. break;
  94554. case FOURCC_DX10:
  94555. // There is an additionnal header so dataOffset need to be changed
  94556. dataOffset += 5 * 4; // 5 uints
  94557. var supported = false;
  94558. switch (info.dxgiFormat) {
  94559. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  94560. computeFormats = true;
  94561. supported = true;
  94562. break;
  94563. case DXGI_FORMAT_B8G8R8X8_UNORM:
  94564. info.isRGB = true;
  94565. info.isFourCC = false;
  94566. bpp = 32;
  94567. supported = true;
  94568. break;
  94569. }
  94570. if (supported) {
  94571. break;
  94572. }
  94573. default:
  94574. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  94575. return;
  94576. }
  94577. }
  94578. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  94579. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  94580. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  94581. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  94582. if (computeFormats) {
  94583. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  94584. }
  94585. mipmapCount = 1;
  94586. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  94587. mipmapCount = Math.max(1, header[off_mipmapCount]);
  94588. }
  94589. for (var face = 0; face < faces; face++) {
  94590. width = header[off_width];
  94591. height = header[off_height];
  94592. for (mip = 0; mip < mipmapCount; ++mip) {
  94593. if (lodIndex === -1 || lodIndex === mip) {
  94594. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  94595. var i = (lodIndex === -1) ? mip : 0;
  94596. if (!info.isCompressed && info.isFourCC) {
  94597. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94598. dataLength = width * height * 4;
  94599. var floatArray = null;
  94600. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  94601. if (bpp === 128) {
  94602. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94603. if (sphericalPolynomialFaces && i == 0) {
  94604. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94605. }
  94606. }
  94607. else if (bpp === 64) {
  94608. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94609. if (sphericalPolynomialFaces && i == 0) {
  94610. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94611. }
  94612. }
  94613. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94614. }
  94615. else {
  94616. if (bpp === 128) {
  94617. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94618. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94619. if (sphericalPolynomialFaces && i == 0) {
  94620. sphericalPolynomialFaces.push(floatArray);
  94621. }
  94622. }
  94623. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  94624. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94625. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94626. if (sphericalPolynomialFaces && i == 0) {
  94627. sphericalPolynomialFaces.push(floatArray);
  94628. }
  94629. }
  94630. else { // 64
  94631. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94632. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94633. if (sphericalPolynomialFaces && i == 0) {
  94634. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94635. }
  94636. }
  94637. }
  94638. if (floatArray) {
  94639. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  94640. }
  94641. }
  94642. else if (info.isRGB) {
  94643. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94644. if (bpp === 24) {
  94645. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  94646. dataLength = width * height * 3;
  94647. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  94648. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94649. }
  94650. else { // 32
  94651. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94652. dataLength = width * height * 4;
  94653. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  94654. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94655. }
  94656. }
  94657. else if (info.isLuminance) {
  94658. var unpackAlignment = engine._getUnpackAlignement();
  94659. var unpaddedRowSize = width;
  94660. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  94661. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  94662. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  94663. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  94664. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94665. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94666. }
  94667. else {
  94668. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  94669. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  94670. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94671. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  94672. }
  94673. }
  94674. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  94675. width *= 0.5;
  94676. height *= 0.5;
  94677. width = Math.max(1.0, width);
  94678. height = Math.max(1.0, height);
  94679. }
  94680. if (currentFace !== undefined) {
  94681. // Loading a single face
  94682. break;
  94683. }
  94684. }
  94685. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  94686. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  94687. size: header[off_width],
  94688. right: sphericalPolynomialFaces[0],
  94689. left: sphericalPolynomialFaces[1],
  94690. up: sphericalPolynomialFaces[2],
  94691. down: sphericalPolynomialFaces[3],
  94692. front: sphericalPolynomialFaces[4],
  94693. back: sphericalPolynomialFaces[5],
  94694. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  94695. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94696. gammaSpace: false,
  94697. });
  94698. }
  94699. else {
  94700. info.sphericalPolynomial = undefined;
  94701. }
  94702. };
  94703. /**
  94704. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  94705. */
  94706. DDSTools.StoreLODInAlphaChannel = false;
  94707. return DDSTools;
  94708. }());
  94709. BABYLON.DDSTools = DDSTools;
  94710. })(BABYLON || (BABYLON = {}));
  94711. //# sourceMappingURL=babylon.dds.js.map
  94712. var BABYLON;
  94713. (function (BABYLON) {
  94714. /**
  94715. * Implementation of the DDS Texture Loader.
  94716. */
  94717. var DDSTextureLoader = /** @class */ (function () {
  94718. function DDSTextureLoader() {
  94719. /**
  94720. * Defines wether the loader supports cascade loading the different faces.
  94721. */
  94722. this.supportCascades = true;
  94723. }
  94724. /**
  94725. * This returns if the loader support the current file information.
  94726. * @param extension defines the file extension of the file being loaded
  94727. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94728. * @param fallback defines the fallback internal texture if any
  94729. * @param isBase64 defines whether the texture is encoded as a base64
  94730. * @param isBuffer defines whether the texture data are stored as a buffer
  94731. * @returns true if the loader can load the specified file
  94732. */
  94733. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94734. return extension.indexOf(".dds") === 0;
  94735. };
  94736. /**
  94737. * Transform the url before loading if required.
  94738. * @param rootUrl the url of the texture
  94739. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94740. * @returns the transformed texture
  94741. */
  94742. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94743. return rootUrl;
  94744. };
  94745. /**
  94746. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94747. * @param rootUrl the url of the texture
  94748. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94749. * @returns the fallback texture
  94750. */
  94751. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94752. return null;
  94753. };
  94754. /**
  94755. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94756. * @param data contains the texture data
  94757. * @param texture defines the BabylonJS internal texture
  94758. * @param createPolynomials will be true if polynomials have been requested
  94759. * @param onLoad defines the callback to trigger once the texture is ready
  94760. * @param onError defines the callback to trigger in case of error
  94761. */
  94762. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  94763. var engine = texture.getEngine();
  94764. var info;
  94765. var loadMipmap = false;
  94766. if (Array.isArray(imgs)) {
  94767. for (var index = 0; index < imgs.length; index++) {
  94768. var data_1 = imgs[index];
  94769. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  94770. texture.width = info.width;
  94771. texture.height = info.height;
  94772. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94773. engine._unpackFlipY(info.isCompressed);
  94774. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  94775. if (!info.isFourCC && info.mipmapCount === 1) {
  94776. engine.generateMipMapsForCubemap(texture);
  94777. }
  94778. }
  94779. }
  94780. else {
  94781. var data = imgs;
  94782. info = BABYLON.DDSTools.GetDDSInfo(data);
  94783. texture.width = info.width;
  94784. texture.height = info.height;
  94785. if (createPolynomials) {
  94786. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  94787. }
  94788. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94789. engine._unpackFlipY(info.isCompressed);
  94790. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  94791. if (!info.isFourCC && info.mipmapCount === 1) {
  94792. engine.generateMipMapsForCubemap(texture);
  94793. }
  94794. }
  94795. engine._setCubeMapTextureParams(loadMipmap);
  94796. texture.isReady = true;
  94797. if (onLoad) {
  94798. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  94799. }
  94800. };
  94801. /**
  94802. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94803. * @param data contains the texture data
  94804. * @param texture defines the BabylonJS internal texture
  94805. * @param callback defines the method to call once ready to upload
  94806. */
  94807. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  94808. var info = BABYLON.DDSTools.GetDDSInfo(data);
  94809. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  94810. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  94811. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  94812. });
  94813. };
  94814. return DDSTextureLoader;
  94815. }());
  94816. // Register the loader.
  94817. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  94818. })(BABYLON || (BABYLON = {}));
  94819. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  94820. var BABYLON;
  94821. (function (BABYLON) {
  94822. /**
  94823. * Based on jsTGALoader - Javascript loader for TGA file
  94824. * By Vincent Thibault
  94825. * @see http://blog.robrowser.com/javascript-tga-loader.html
  94826. */
  94827. var TGATools = /** @class */ (function () {
  94828. function TGATools() {
  94829. }
  94830. /**
  94831. * Gets the header of a TGA file
  94832. * @param data defines the TGA data
  94833. * @returns the header
  94834. */
  94835. TGATools.GetTGAHeader = function (data) {
  94836. var offset = 0;
  94837. var header = {
  94838. id_length: data[offset++],
  94839. colormap_type: data[offset++],
  94840. image_type: data[offset++],
  94841. colormap_index: data[offset++] | data[offset++] << 8,
  94842. colormap_length: data[offset++] | data[offset++] << 8,
  94843. colormap_size: data[offset++],
  94844. origin: [
  94845. data[offset++] | data[offset++] << 8,
  94846. data[offset++] | data[offset++] << 8
  94847. ],
  94848. width: data[offset++] | data[offset++] << 8,
  94849. height: data[offset++] | data[offset++] << 8,
  94850. pixel_size: data[offset++],
  94851. flags: data[offset++]
  94852. };
  94853. return header;
  94854. };
  94855. /**
  94856. * Uploads TGA content to a Babylon Texture
  94857. * @hidden
  94858. */
  94859. TGATools.UploadContent = function (texture, data) {
  94860. // Not enough data to contain header ?
  94861. if (data.length < 19) {
  94862. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  94863. return;
  94864. }
  94865. // Read Header
  94866. var offset = 18;
  94867. var header = TGATools.GetTGAHeader(data);
  94868. // Assume it's a valid Targa file.
  94869. if (header.id_length + offset > data.length) {
  94870. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  94871. return;
  94872. }
  94873. // Skip not needed data
  94874. offset += header.id_length;
  94875. var use_rle = false;
  94876. var use_pal = false;
  94877. var use_grey = false;
  94878. // Get some informations.
  94879. switch (header.image_type) {
  94880. case TGATools._TYPE_RLE_INDEXED:
  94881. use_rle = true;
  94882. case TGATools._TYPE_INDEXED:
  94883. use_pal = true;
  94884. break;
  94885. case TGATools._TYPE_RLE_RGB:
  94886. use_rle = true;
  94887. case TGATools._TYPE_RGB:
  94888. // use_rgb = true;
  94889. break;
  94890. case TGATools._TYPE_RLE_GREY:
  94891. use_rle = true;
  94892. case TGATools._TYPE_GREY:
  94893. use_grey = true;
  94894. break;
  94895. }
  94896. var pixel_data;
  94897. // var numAlphaBits = header.flags & 0xf;
  94898. var pixel_size = header.pixel_size >> 3;
  94899. var pixel_total = header.width * header.height * pixel_size;
  94900. // Read palettes
  94901. var palettes;
  94902. if (use_pal) {
  94903. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  94904. }
  94905. // Read LRE
  94906. if (use_rle) {
  94907. pixel_data = new Uint8Array(pixel_total);
  94908. var c, count, i;
  94909. var localOffset = 0;
  94910. var pixels = new Uint8Array(pixel_size);
  94911. while (offset < pixel_total && localOffset < pixel_total) {
  94912. c = data[offset++];
  94913. count = (c & 0x7f) + 1;
  94914. // RLE pixels
  94915. if (c & 0x80) {
  94916. // Bind pixel tmp array
  94917. for (i = 0; i < pixel_size; ++i) {
  94918. pixels[i] = data[offset++];
  94919. }
  94920. // Copy pixel array
  94921. for (i = 0; i < count; ++i) {
  94922. pixel_data.set(pixels, localOffset + i * pixel_size);
  94923. }
  94924. localOffset += pixel_size * count;
  94925. }
  94926. // Raw pixels
  94927. else {
  94928. count *= pixel_size;
  94929. for (i = 0; i < count; ++i) {
  94930. pixel_data[localOffset + i] = data[offset++];
  94931. }
  94932. localOffset += count;
  94933. }
  94934. }
  94935. }
  94936. // RAW Pixels
  94937. else {
  94938. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  94939. }
  94940. // Load to texture
  94941. var x_start, y_start, x_step, y_step, y_end, x_end;
  94942. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  94943. default:
  94944. case TGATools._ORIGIN_UL:
  94945. x_start = 0;
  94946. x_step = 1;
  94947. x_end = header.width;
  94948. y_start = 0;
  94949. y_step = 1;
  94950. y_end = header.height;
  94951. break;
  94952. case TGATools._ORIGIN_BL:
  94953. x_start = 0;
  94954. x_step = 1;
  94955. x_end = header.width;
  94956. y_start = header.height - 1;
  94957. y_step = -1;
  94958. y_end = -1;
  94959. break;
  94960. case TGATools._ORIGIN_UR:
  94961. x_start = header.width - 1;
  94962. x_step = -1;
  94963. x_end = -1;
  94964. y_start = 0;
  94965. y_step = 1;
  94966. y_end = header.height;
  94967. break;
  94968. case TGATools._ORIGIN_BR:
  94969. x_start = header.width - 1;
  94970. x_step = -1;
  94971. x_end = -1;
  94972. y_start = header.height - 1;
  94973. y_step = -1;
  94974. y_end = -1;
  94975. break;
  94976. }
  94977. // Load the specify method
  94978. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  94979. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  94980. var engine = texture.getEngine();
  94981. engine._uploadDataToTextureDirectly(texture, imageData);
  94982. };
  94983. /** @hidden */
  94984. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94985. var image = pixel_data, colormap = palettes;
  94986. var width = header.width, height = header.height;
  94987. var color, i = 0, x, y;
  94988. var imageData = new Uint8Array(width * height * 4);
  94989. for (y = y_start; y !== y_end; y += y_step) {
  94990. for (x = x_start; x !== x_end; x += x_step, i++) {
  94991. color = image[i];
  94992. imageData[(x + width * y) * 4 + 3] = 255;
  94993. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  94994. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  94995. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  94996. }
  94997. }
  94998. return imageData;
  94999. };
  95000. /** @hidden */
  95001. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95002. var image = pixel_data;
  95003. var width = header.width, height = header.height;
  95004. var color, i = 0, x, y;
  95005. var imageData = new Uint8Array(width * height * 4);
  95006. for (y = y_start; y !== y_end; y += y_step) {
  95007. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  95008. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  95009. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  95010. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  95011. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  95012. imageData[(x + width * y) * 4 + 0] = r;
  95013. imageData[(x + width * y) * 4 + 1] = g;
  95014. imageData[(x + width * y) * 4 + 2] = b;
  95015. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  95016. }
  95017. }
  95018. return imageData;
  95019. };
  95020. /** @hidden */
  95021. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95022. var image = pixel_data;
  95023. var width = header.width, height = header.height;
  95024. var i = 0, x, y;
  95025. var imageData = new Uint8Array(width * height * 4);
  95026. for (y = y_start; y !== y_end; y += y_step) {
  95027. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  95028. imageData[(x + width * y) * 4 + 3] = 255;
  95029. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95030. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  95031. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  95032. }
  95033. }
  95034. return imageData;
  95035. };
  95036. /** @hidden */
  95037. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95038. var image = pixel_data;
  95039. var width = header.width, height = header.height;
  95040. var i = 0, x, y;
  95041. var imageData = new Uint8Array(width * height * 4);
  95042. for (y = y_start; y !== y_end; y += y_step) {
  95043. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  95044. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95045. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  95046. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  95047. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  95048. }
  95049. }
  95050. return imageData;
  95051. };
  95052. /** @hidden */
  95053. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95054. var image = pixel_data;
  95055. var width = header.width, height = header.height;
  95056. var color, i = 0, x, y;
  95057. var imageData = new Uint8Array(width * height * 4);
  95058. for (y = y_start; y !== y_end; y += y_step) {
  95059. for (x = x_start; x !== x_end; x += x_step, i++) {
  95060. color = image[i];
  95061. imageData[(x + width * y) * 4 + 0] = color;
  95062. imageData[(x + width * y) * 4 + 1] = color;
  95063. imageData[(x + width * y) * 4 + 2] = color;
  95064. imageData[(x + width * y) * 4 + 3] = 255;
  95065. }
  95066. }
  95067. return imageData;
  95068. };
  95069. /** @hidden */
  95070. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95071. var image = pixel_data;
  95072. var width = header.width, height = header.height;
  95073. var i = 0, x, y;
  95074. var imageData = new Uint8Array(width * height * 4);
  95075. for (y = y_start; y !== y_end; y += y_step) {
  95076. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  95077. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  95078. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  95079. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95080. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  95081. }
  95082. }
  95083. return imageData;
  95084. };
  95085. //private static _TYPE_NO_DATA = 0;
  95086. TGATools._TYPE_INDEXED = 1;
  95087. TGATools._TYPE_RGB = 2;
  95088. TGATools._TYPE_GREY = 3;
  95089. TGATools._TYPE_RLE_INDEXED = 9;
  95090. TGATools._TYPE_RLE_RGB = 10;
  95091. TGATools._TYPE_RLE_GREY = 11;
  95092. TGATools._ORIGIN_MASK = 0x30;
  95093. TGATools._ORIGIN_SHIFT = 0x04;
  95094. TGATools._ORIGIN_BL = 0x00;
  95095. TGATools._ORIGIN_BR = 0x01;
  95096. TGATools._ORIGIN_UL = 0x02;
  95097. TGATools._ORIGIN_UR = 0x03;
  95098. return TGATools;
  95099. }());
  95100. BABYLON.TGATools = TGATools;
  95101. })(BABYLON || (BABYLON = {}));
  95102. //# sourceMappingURL=babylon.tga.js.map
  95103. var BABYLON;
  95104. (function (BABYLON) {
  95105. /**
  95106. * Implementation of the TGA Texture Loader.
  95107. */
  95108. var TGATextureLoader = /** @class */ (function () {
  95109. function TGATextureLoader() {
  95110. /**
  95111. * Defines wether the loader supports cascade loading the different faces.
  95112. */
  95113. this.supportCascades = false;
  95114. }
  95115. /**
  95116. * This returns if the loader support the current file information.
  95117. * @param extension defines the file extension of the file being loaded
  95118. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95119. * @param fallback defines the fallback internal texture if any
  95120. * @param isBase64 defines whether the texture is encoded as a base64
  95121. * @param isBuffer defines whether the texture data are stored as a buffer
  95122. * @returns true if the loader can load the specified file
  95123. */
  95124. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95125. return extension.indexOf(".tga") === 0;
  95126. };
  95127. /**
  95128. * Transform the url before loading if required.
  95129. * @param rootUrl the url of the texture
  95130. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95131. * @returns the transformed texture
  95132. */
  95133. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95134. return rootUrl;
  95135. };
  95136. /**
  95137. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95138. * @param rootUrl the url of the texture
  95139. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95140. * @returns the fallback texture
  95141. */
  95142. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95143. return null;
  95144. };
  95145. /**
  95146. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95147. * @param data contains the texture data
  95148. * @param texture defines the BabylonJS internal texture
  95149. * @param createPolynomials will be true if polynomials have been requested
  95150. * @param onLoad defines the callback to trigger once the texture is ready
  95151. * @param onError defines the callback to trigger in case of error
  95152. */
  95153. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95154. throw ".env not supported in Cube.";
  95155. };
  95156. /**
  95157. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95158. * @param data contains the texture data
  95159. * @param texture defines the BabylonJS internal texture
  95160. * @param callback defines the method to call once ready to upload
  95161. */
  95162. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  95163. var uintData = new Uint8Array(data);
  95164. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  95165. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  95166. BABYLON.TGATools.UploadContent(texture, uintData);
  95167. });
  95168. };
  95169. return TGATextureLoader;
  95170. }());
  95171. // Register the loader.
  95172. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  95173. })(BABYLON || (BABYLON = {}));
  95174. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  95175. var BABYLON;
  95176. (function (BABYLON) {
  95177. /**
  95178. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  95179. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  95180. */
  95181. var KhronosTextureContainer = /** @class */ (function () {
  95182. /**
  95183. * Creates a new KhronosTextureContainer
  95184. * @param arrayBuffer contents of the KTX container file
  95185. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  95186. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  95187. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  95188. */
  95189. function KhronosTextureContainer(
  95190. /** contents of the KTX container file */
  95191. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  95192. this.arrayBuffer = arrayBuffer;
  95193. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  95194. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  95195. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  95196. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  95197. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  95198. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  95199. BABYLON.Tools.Error("texture missing KTX identifier");
  95200. return;
  95201. }
  95202. // load the reset of the header in native 32 bit int
  95203. var header = new Int32Array(this.arrayBuffer, 12, 13);
  95204. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  95205. var oppositeEndianess = header[0] === 0x01020304;
  95206. // read all the header elements in order they exist in the file, without modification (sans endainness)
  95207. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  95208. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  95209. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  95210. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  95211. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  95212. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  95213. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  95214. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  95215. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  95216. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  95217. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  95218. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  95219. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  95220. if (this.glType !== 0) {
  95221. BABYLON.Tools.Error("only compressed formats currently supported");
  95222. return;
  95223. }
  95224. else {
  95225. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  95226. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  95227. }
  95228. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  95229. BABYLON.Tools.Error("only 2D textures currently supported");
  95230. return;
  95231. }
  95232. if (this.numberOfArrayElements !== 0) {
  95233. BABYLON.Tools.Error("texture arrays not currently supported");
  95234. return;
  95235. }
  95236. if (this.numberOfFaces !== facesExpected) {
  95237. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  95238. return;
  95239. }
  95240. // we now have a completely validated file, so could use existence of loadType as success
  95241. // would need to make this more elaborate & adjust checks above to support more than one load type
  95242. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  95243. }
  95244. //
  95245. /**
  95246. * Revert the endianness of a value.
  95247. * Not as fast hardware based, but will probably never need to use
  95248. * @param val defines the value to convert
  95249. * @returns the new value
  95250. */
  95251. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  95252. return ((val & 0xFF) << 24)
  95253. | ((val & 0xFF00) << 8)
  95254. | ((val >> 8) & 0xFF00)
  95255. | ((val >> 24) & 0xFF);
  95256. };
  95257. /**
  95258. * Uploads KTX content to a Babylon Texture.
  95259. * It is assumed that the texture has already been created & is currently bound
  95260. * @hidden
  95261. */
  95262. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  95263. switch (this.loadType) {
  95264. case KhronosTextureContainer.COMPRESSED_2D:
  95265. this._upload2DCompressedLevels(texture, loadMipmaps);
  95266. break;
  95267. case KhronosTextureContainer.TEX_2D:
  95268. case KhronosTextureContainer.COMPRESSED_3D:
  95269. case KhronosTextureContainer.TEX_3D:
  95270. }
  95271. };
  95272. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  95273. // initialize width & height for level 1
  95274. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  95275. var width = this.pixelWidth;
  95276. var height = this.pixelHeight;
  95277. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  95278. for (var level = 0; level < mipmapCount; level++) {
  95279. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  95280. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  95281. for (var face = 0; face < this.numberOfFaces; face++) {
  95282. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  95283. var engine = texture.getEngine();
  95284. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  95285. dataOffset += imageSize; // add size of the image for the next face/mipmap
  95286. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  95287. }
  95288. width = Math.max(1.0, width * 0.5);
  95289. height = Math.max(1.0, height * 0.5);
  95290. }
  95291. };
  95292. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  95293. // load types
  95294. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  95295. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  95296. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  95297. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  95298. return KhronosTextureContainer;
  95299. }());
  95300. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  95301. })(BABYLON || (BABYLON = {}));
  95302. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  95303. var BABYLON;
  95304. (function (BABYLON) {
  95305. /**
  95306. * Implementation of the KTX Texture Loader.
  95307. */
  95308. var KTXTextureLoader = /** @class */ (function () {
  95309. function KTXTextureLoader() {
  95310. /**
  95311. * Defines wether the loader supports cascade loading the different faces.
  95312. */
  95313. this.supportCascades = false;
  95314. }
  95315. /**
  95316. * This returns if the loader support the current file information.
  95317. * @param extension defines the file extension of the file being loaded
  95318. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95319. * @param fallback defines the fallback internal texture if any
  95320. * @param isBase64 defines whether the texture is encoded as a base64
  95321. * @param isBuffer defines whether the texture data are stored as a buffer
  95322. * @returns true if the loader can load the specified file
  95323. */
  95324. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95325. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  95326. return true;
  95327. }
  95328. return false;
  95329. };
  95330. /**
  95331. * Transform the url before loading if required.
  95332. * @param rootUrl the url of the texture
  95333. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95334. * @returns the transformed texture
  95335. */
  95336. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95337. var lastDot = rootUrl.lastIndexOf('.');
  95338. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  95339. };
  95340. /**
  95341. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95342. * @param rootUrl the url of the texture
  95343. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95344. * @returns the fallback texture
  95345. */
  95346. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95347. // remove the format appended to the rootUrl in the original createCubeTexture call.
  95348. var exp = new RegExp("" + textureFormatInUse + "$");
  95349. return rootUrl.replace(exp, "");
  95350. };
  95351. /**
  95352. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95353. * @param data contains the texture data
  95354. * @param texture defines the BabylonJS internal texture
  95355. * @param createPolynomials will be true if polynomials have been requested
  95356. * @param onLoad defines the callback to trigger once the texture is ready
  95357. * @param onError defines the callback to trigger in case of error
  95358. */
  95359. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95360. if (Array.isArray(data)) {
  95361. return;
  95362. }
  95363. var engine = texture.getEngine();
  95364. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  95365. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  95366. engine._unpackFlipY(true);
  95367. ktx.uploadLevels(texture, texture.generateMipMaps);
  95368. texture.width = ktx.pixelWidth;
  95369. texture.height = ktx.pixelHeight;
  95370. engine._setCubeMapTextureParams(loadMipmap);
  95371. texture.isReady = true;
  95372. };
  95373. /**
  95374. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95375. * @param data contains the texture data
  95376. * @param texture defines the BabylonJS internal texture
  95377. * @param callback defines the method to call once ready to upload
  95378. */
  95379. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  95380. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  95381. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  95382. ktx.uploadLevels(texture, texture.generateMipMaps);
  95383. });
  95384. };
  95385. return KTXTextureLoader;
  95386. }());
  95387. // Register the loader.
  95388. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  95389. })(BABYLON || (BABYLON = {}));
  95390. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  95391. var BABYLON;
  95392. (function (BABYLON) {
  95393. /**
  95394. * Sets of helpers addressing the serialization and deserialization of environment texture
  95395. * stored in a BabylonJS env file.
  95396. * Those files are usually stored as .env files.
  95397. */
  95398. var EnvironmentTextureTools = /** @class */ (function () {
  95399. function EnvironmentTextureTools() {
  95400. }
  95401. /**
  95402. * Gets the environment info from an env file.
  95403. * @param data The array buffer containing the .env bytes.
  95404. * @returns the environment file info (the json header) if successfully parsed.
  95405. */
  95406. EnvironmentTextureTools.GetEnvInfo = function (data) {
  95407. var dataView = new DataView(data);
  95408. var pos = 0;
  95409. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  95410. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  95411. BABYLON.Tools.Error('Not a babylon environment map');
  95412. return null;
  95413. }
  95414. }
  95415. // Read json manifest - collect characters up to null terminator
  95416. var manifestString = '';
  95417. var charCode = 0x00;
  95418. while ((charCode = dataView.getUint8(pos++))) {
  95419. manifestString += String.fromCharCode(charCode);
  95420. }
  95421. var manifest = JSON.parse(manifestString);
  95422. if (manifest.specular) {
  95423. // Extend the header with the position of the payload.
  95424. manifest.specular.specularDataPosition = pos;
  95425. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  95426. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  95427. }
  95428. return manifest;
  95429. };
  95430. /**
  95431. * Creates an environment texture from a loaded cube texture.
  95432. * @param texture defines the cube texture to convert in env file
  95433. * @return a promise containing the environment data if succesfull.
  95434. */
  95435. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  95436. var _this = this;
  95437. var internalTexture = texture.getInternalTexture();
  95438. if (!internalTexture) {
  95439. return Promise.reject("The cube texture is invalid.");
  95440. }
  95441. if (!texture._prefiltered) {
  95442. return Promise.reject("The cube texture is invalid (not prefiltered).");
  95443. }
  95444. var engine = internalTexture.getEngine();
  95445. if (engine && engine.premultipliedAlpha) {
  95446. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  95447. }
  95448. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  95449. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  95450. }
  95451. var canvas = engine.getRenderingCanvas();
  95452. if (!canvas) {
  95453. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  95454. }
  95455. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95456. if (!engine.getCaps().textureFloatRender) {
  95457. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95458. if (!engine.getCaps().textureHalfFloatRender) {
  95459. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  95460. }
  95461. }
  95462. var cubeWidth = internalTexture.width;
  95463. var hostingScene = new BABYLON.Scene(engine);
  95464. var specularTextures = {};
  95465. var promises = [];
  95466. // Read and collect all mipmaps data from the cube.
  95467. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  95468. mipmapsCount = Math.round(mipmapsCount);
  95469. var _loop_1 = function (i) {
  95470. var faceWidth = Math.pow(2, mipmapsCount - i);
  95471. var _loop_2 = function (face) {
  95472. var data = texture.readPixels(face, i);
  95473. // Creates a temp texture with the face data.
  95474. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  95475. // And rgbdEncode them.
  95476. var promise = new Promise(function (resolve, reject) {
  95477. 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);
  95478. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  95479. rgbdPostProcess.onApply = function (effect) {
  95480. effect._bindTexture("textureSampler", tempTexture);
  95481. };
  95482. // As the process needs to happen on the main canvas, keep track of the current size
  95483. var currentW = engine.getRenderWidth();
  95484. var currentH = engine.getRenderHeight();
  95485. // Set the desired size for the texture
  95486. engine.setSize(faceWidth, faceWidth);
  95487. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  95488. // Reading datas from WebGL
  95489. BABYLON.Tools.ToBlob(canvas, function (blob) {
  95490. var fileReader = new FileReader();
  95491. fileReader.onload = function (event) {
  95492. var arrayBuffer = event.target.result;
  95493. specularTextures[i * 6 + face] = arrayBuffer;
  95494. resolve();
  95495. };
  95496. fileReader.readAsArrayBuffer(blob);
  95497. });
  95498. // Reapply the previous canvas size
  95499. engine.setSize(currentW, currentH);
  95500. });
  95501. });
  95502. promises.push(promise);
  95503. };
  95504. // All faces of the cube.
  95505. for (var face = 0; face < 6; face++) {
  95506. _loop_2(face);
  95507. }
  95508. };
  95509. for (var i = 0; i <= mipmapsCount; i++) {
  95510. _loop_1(i);
  95511. }
  95512. // Once all the textures haves been collected as RGBD stored in PNGs
  95513. return Promise.all(promises).then(function () {
  95514. // We can delete the hosting scene keeping track of all the creation objects
  95515. hostingScene.dispose();
  95516. // Creates the json header for the env texture
  95517. var info = {
  95518. version: 1,
  95519. width: cubeWidth,
  95520. irradiance: _this._CreateEnvTextureIrradiance(texture),
  95521. specular: {
  95522. mipmaps: [],
  95523. lodGenerationScale: texture.lodGenerationScale
  95524. }
  95525. };
  95526. // Sets the specular image data information
  95527. var position = 0;
  95528. for (var i = 0; i <= mipmapsCount; i++) {
  95529. for (var face = 0; face < 6; face++) {
  95530. var byteLength = specularTextures[i * 6 + face].byteLength;
  95531. info.specular.mipmaps.push({
  95532. length: byteLength,
  95533. position: position
  95534. });
  95535. position += byteLength;
  95536. }
  95537. }
  95538. // Encode the JSON as an array buffer
  95539. var infoString = JSON.stringify(info);
  95540. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  95541. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  95542. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  95543. infoView[i] = infoString.charCodeAt(i);
  95544. }
  95545. // Ends up with a null terminator for easier parsing
  95546. infoView[infoString.length] = 0x00;
  95547. // Computes the final required size and creates the storage
  95548. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  95549. var finalBuffer = new ArrayBuffer(totalSize);
  95550. var finalBufferView = new Uint8Array(finalBuffer);
  95551. var dataView = new DataView(finalBuffer);
  95552. // Copy the magic bytes identifying the file in
  95553. var pos = 0;
  95554. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  95555. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  95556. }
  95557. // Add the json info
  95558. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  95559. pos += infoBuffer.byteLength;
  95560. // Finally inserts the texture data
  95561. for (var i = 0; i <= mipmapsCount; i++) {
  95562. for (var face = 0; face < 6; face++) {
  95563. var dataBuffer = specularTextures[i * 6 + face];
  95564. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  95565. pos += dataBuffer.byteLength;
  95566. }
  95567. }
  95568. // Voila
  95569. return finalBuffer;
  95570. });
  95571. };
  95572. /**
  95573. * Creates a JSON representation of the spherical data.
  95574. * @param texture defines the texture containing the polynomials
  95575. * @return the JSON representation of the spherical info
  95576. */
  95577. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  95578. var polynmials = texture.sphericalPolynomial;
  95579. if (polynmials == null) {
  95580. return null;
  95581. }
  95582. return {
  95583. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  95584. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  95585. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  95586. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  95587. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  95588. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  95589. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  95590. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  95591. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  95592. };
  95593. };
  95594. /**
  95595. * Uploads the texture info contained in the env file to the GPU.
  95596. * @param texture defines the internal texture to upload to
  95597. * @param arrayBuffer defines the buffer cotaining the data to load
  95598. * @param info defines the texture info retrieved through the GetEnvInfo method
  95599. * @returns a promise
  95600. */
  95601. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  95602. if (info.version !== 1) {
  95603. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  95604. }
  95605. var specularInfo = info.specular;
  95606. if (!specularInfo) {
  95607. // Nothing else parsed so far
  95608. return Promise.resolve();
  95609. }
  95610. // Double checks the enclosed info
  95611. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  95612. mipmapsCount = Math.round(mipmapsCount) + 1;
  95613. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  95614. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  95615. }
  95616. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  95617. var imageData = new Array(mipmapsCount);
  95618. for (var i = 0; i < mipmapsCount; i++) {
  95619. imageData[i] = new Array(6);
  95620. for (var face = 0; face < 6; face++) {
  95621. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  95622. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  95623. }
  95624. }
  95625. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  95626. };
  95627. /**
  95628. * Uploads the levels of image data to the GPU.
  95629. * @param texture defines the internal texture to upload to
  95630. * @param imageData defines the array buffer views of image data [mipmap][face]
  95631. * @returns a promise
  95632. */
  95633. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  95634. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  95635. throw new Error("Texture size must be a power of two");
  95636. }
  95637. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  95638. // Gets everything ready.
  95639. var engine = texture.getEngine();
  95640. var expandTexture = false;
  95641. var generateNonLODTextures = false;
  95642. var rgbdPostProcess = null;
  95643. var cubeRtt = null;
  95644. var lodTextures = null;
  95645. var caps = engine.getCaps();
  95646. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  95647. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95648. texture.generateMipMaps = true;
  95649. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  95650. // Add extra process if texture lod is not supported
  95651. if (!caps.textureLOD) {
  95652. expandTexture = false;
  95653. generateNonLODTextures = true;
  95654. lodTextures = {};
  95655. }
  95656. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  95657. else if (engine.webGLVersion < 2) {
  95658. expandTexture = false;
  95659. }
  95660. // If half float available we can uncompress the texture
  95661. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  95662. expandTexture = true;
  95663. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95664. }
  95665. // If full float available we can uncompress the texture
  95666. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  95667. expandTexture = true;
  95668. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95669. }
  95670. // Expand the texture if possible
  95671. if (expandTexture) {
  95672. // Simply run through the decode PP
  95673. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  95674. texture._isRGBD = false;
  95675. texture.invertY = false;
  95676. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  95677. generateDepthBuffer: false,
  95678. generateMipMaps: true,
  95679. generateStencilBuffer: false,
  95680. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  95681. type: texture.type,
  95682. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  95683. });
  95684. }
  95685. else {
  95686. texture._isRGBD = true;
  95687. texture.invertY = true;
  95688. // In case of missing support, applies the same patch than DDS files.
  95689. if (generateNonLODTextures) {
  95690. var mipSlices = 3;
  95691. var scale = texture._lodGenerationScale;
  95692. var offset = texture._lodGenerationOffset;
  95693. for (var i = 0; i < mipSlices; i++) {
  95694. //compute LOD from even spacing in smoothness (matching shader calculation)
  95695. var smoothness = i / (mipSlices - 1);
  95696. var roughness = 1 - smoothness;
  95697. var minLODIndex = offset; // roughness = 0
  95698. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  95699. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  95700. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  95701. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  95702. glTextureFromLod.isCube = true;
  95703. glTextureFromLod.invertY = true;
  95704. glTextureFromLod.generateMipMaps = false;
  95705. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  95706. // Wrap in a base texture for easy binding.
  95707. var lodTexture = new BABYLON.BaseTexture(null);
  95708. lodTexture.isCube = true;
  95709. lodTexture._texture = glTextureFromLod;
  95710. lodTextures[mipmapIndex] = lodTexture;
  95711. switch (i) {
  95712. case 0:
  95713. texture._lodTextureLow = lodTexture;
  95714. break;
  95715. case 1:
  95716. texture._lodTextureMid = lodTexture;
  95717. break;
  95718. case 2:
  95719. texture._lodTextureHigh = lodTexture;
  95720. break;
  95721. }
  95722. }
  95723. }
  95724. }
  95725. var promises = [];
  95726. var _loop_3 = function (i) {
  95727. var _loop_4 = function (face) {
  95728. // Constructs an image element from image data
  95729. var bytes = imageData[i][face];
  95730. var blob = new Blob([bytes], { type: 'image/png' });
  95731. var url = URL.createObjectURL(blob);
  95732. var image = new Image();
  95733. image.src = url;
  95734. // Enqueue promise to upload to the texture.
  95735. var promise = new Promise(function (resolve, reject) {
  95736. image.onload = function () {
  95737. if (expandTexture) {
  95738. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  95739. reject(message);
  95740. }, image);
  95741. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  95742. // Uncompress the data to a RTT
  95743. rgbdPostProcess.onApply = function (effect) {
  95744. effect._bindTexture("textureSampler", tempTexture_1);
  95745. effect.setFloat2("scale", 1, 1);
  95746. };
  95747. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  95748. // Cleanup
  95749. engine.restoreDefaultFramebuffer();
  95750. tempTexture_1.dispose();
  95751. window.URL.revokeObjectURL(url);
  95752. resolve();
  95753. });
  95754. }
  95755. else {
  95756. engine._uploadImageToTexture(texture, image, face, i);
  95757. // Upload the face to the non lod texture support
  95758. if (generateNonLODTextures) {
  95759. var lodTexture = lodTextures[i];
  95760. if (lodTexture) {
  95761. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  95762. }
  95763. }
  95764. resolve();
  95765. }
  95766. };
  95767. image.onerror = function (error) {
  95768. reject(error);
  95769. };
  95770. });
  95771. promises.push(promise);
  95772. };
  95773. // All faces
  95774. for (var face = 0; face < 6; face++) {
  95775. _loop_4(face);
  95776. }
  95777. };
  95778. // All mipmaps up to provided number of images
  95779. for (var i = 0; i < imageData.length; i++) {
  95780. _loop_3(i);
  95781. }
  95782. // Fill remaining mipmaps with black textures.
  95783. if (imageData.length < mipmapsCount) {
  95784. var data = void 0;
  95785. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  95786. var dataLength = size * size * 4;
  95787. switch (texture.type) {
  95788. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  95789. data = new Uint8Array(dataLength);
  95790. break;
  95791. }
  95792. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  95793. data = new Uint16Array(dataLength);
  95794. break;
  95795. }
  95796. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  95797. data = new Float32Array(dataLength);
  95798. break;
  95799. }
  95800. }
  95801. for (var i = imageData.length; i < mipmapsCount; i++) {
  95802. for (var face = 0; face < 6; face++) {
  95803. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  95804. }
  95805. }
  95806. }
  95807. // Once all done, finishes the cleanup and return
  95808. return Promise.all(promises).then(function () {
  95809. // Release temp RTT.
  95810. if (cubeRtt) {
  95811. engine._releaseFramebufferObjects(cubeRtt);
  95812. cubeRtt._swapAndDie(texture);
  95813. }
  95814. // Release temp Post Process.
  95815. if (rgbdPostProcess) {
  95816. rgbdPostProcess.dispose();
  95817. }
  95818. // Flag internal texture as ready in case they are in use.
  95819. if (generateNonLODTextures) {
  95820. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  95821. texture._lodTextureHigh._texture.isReady = true;
  95822. }
  95823. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  95824. texture._lodTextureMid._texture.isReady = true;
  95825. }
  95826. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  95827. texture._lodTextureLow._texture.isReady = true;
  95828. }
  95829. }
  95830. });
  95831. };
  95832. /**
  95833. * Uploads spherical polynomials information to the texture.
  95834. * @param texture defines the texture we are trying to upload the information to
  95835. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  95836. */
  95837. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  95838. if (info.version !== 1) {
  95839. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  95840. }
  95841. var irradianceInfo = info.irradiance;
  95842. if (!irradianceInfo) {
  95843. return;
  95844. }
  95845. var sp = new BABYLON.SphericalPolynomial();
  95846. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  95847. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  95848. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  95849. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  95850. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  95851. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  95852. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  95853. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  95854. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  95855. texture._sphericalPolynomial = sp;
  95856. };
  95857. /**
  95858. * Magic number identifying the env file.
  95859. */
  95860. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  95861. return EnvironmentTextureTools;
  95862. }());
  95863. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  95864. })(BABYLON || (BABYLON = {}));
  95865. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  95866. var BABYLON;
  95867. (function (BABYLON) {
  95868. /**
  95869. * Implementation of the ENV Texture Loader.
  95870. */
  95871. var ENVTextureLoader = /** @class */ (function () {
  95872. function ENVTextureLoader() {
  95873. /**
  95874. * Defines wether the loader supports cascade loading the different faces.
  95875. */
  95876. this.supportCascades = false;
  95877. }
  95878. /**
  95879. * This returns if the loader support the current file information.
  95880. * @param extension defines the file extension of the file being loaded
  95881. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95882. * @param fallback defines the fallback internal texture if any
  95883. * @param isBase64 defines whether the texture is encoded as a base64
  95884. * @param isBuffer defines whether the texture data are stored as a buffer
  95885. * @returns true if the loader can load the specified file
  95886. */
  95887. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95888. return extension.indexOf(".env") === 0;
  95889. };
  95890. /**
  95891. * Transform the url before loading if required.
  95892. * @param rootUrl the url of the texture
  95893. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95894. * @returns the transformed texture
  95895. */
  95896. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95897. return rootUrl;
  95898. };
  95899. /**
  95900. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95901. * @param rootUrl the url of the texture
  95902. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95903. * @returns the fallback texture
  95904. */
  95905. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95906. return null;
  95907. };
  95908. /**
  95909. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95910. * @param data contains the texture data
  95911. * @param texture defines the BabylonJS internal texture
  95912. * @param createPolynomials will be true if polynomials have been requested
  95913. * @param onLoad defines the callback to trigger once the texture is ready
  95914. * @param onError defines the callback to trigger in case of error
  95915. */
  95916. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95917. if (Array.isArray(data)) {
  95918. return;
  95919. }
  95920. data = data;
  95921. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  95922. if (info) {
  95923. texture.width = info.width;
  95924. texture.height = info.width;
  95925. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  95926. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  95927. texture.isReady = true;
  95928. if (onLoad) {
  95929. onLoad();
  95930. }
  95931. });
  95932. }
  95933. else if (onError) {
  95934. onError("Can not parse the environment file", null);
  95935. }
  95936. };
  95937. /**
  95938. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95939. * @param data contains the texture data
  95940. * @param texture defines the BabylonJS internal texture
  95941. * @param callback defines the method to call once ready to upload
  95942. */
  95943. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  95944. throw ".env not supported in 2d.";
  95945. };
  95946. return ENVTextureLoader;
  95947. }());
  95948. // Register the loader.
  95949. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  95950. })(BABYLON || (BABYLON = {}));
  95951. //# sourceMappingURL=babylon.envTextureLoader.js.map
  95952. var BABYLON;
  95953. (function (BABYLON) {
  95954. /**
  95955. * Renders a layer on top of an existing scene
  95956. */
  95957. var UtilityLayerRenderer = /** @class */ (function () {
  95958. /**
  95959. * Instantiates a UtilityLayerRenderer
  95960. * @param originalScene the original scene that will be rendered on top of
  95961. */
  95962. function UtilityLayerRenderer(
  95963. /** the original scene that will be rendered on top of */
  95964. originalScene) {
  95965. var _this = this;
  95966. this.originalScene = originalScene;
  95967. this._pointerCaptures = {};
  95968. this._lastPointerEvents = {};
  95969. /**
  95970. * If the utility layer should automatically be rendered on top of existing scene
  95971. */
  95972. this.shouldRender = true;
  95973. /**
  95974. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  95975. */
  95976. this.onlyCheckPointerDownEvents = true;
  95977. /**
  95978. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  95979. */
  95980. this.processAllEvents = false;
  95981. /**
  95982. * Observable raised when the pointer move from the utility layer scene to the main scene
  95983. */
  95984. this.onPointerOutObservable = new BABYLON.Observable();
  95985. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  95986. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  95987. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  95988. this.utilityLayerScene._allowPostProcessClearColor = false;
  95989. originalScene.getEngine().scenes.pop();
  95990. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  95991. this.utilityLayerScene.detachControl();
  95992. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  95993. if (!_this.processAllEvents) {
  95994. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  95995. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  95996. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  95997. return;
  95998. }
  95999. }
  96000. var pointerEvent = (prePointerInfo.event);
  96001. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  96002. _this._pointerCaptures[pointerEvent.pointerId] = false;
  96003. return;
  96004. }
  96005. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  96006. if (!prePointerInfo.ray && utilityScenePick) {
  96007. prePointerInfo.ray = utilityScenePick.ray;
  96008. }
  96009. // always fire the prepointer oversvable
  96010. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  96011. // allow every non pointer down event to flow to the utility layer
  96012. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  96013. if (!prePointerInfo.skipOnPointerObservable) {
  96014. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  96015. }
  96016. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  96017. _this._pointerCaptures[pointerEvent.pointerId] = false;
  96018. }
  96019. return;
  96020. }
  96021. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  96022. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  96023. if (utilityScenePick && utilityScenePick.hit) {
  96024. if (!prePointerInfo.skipOnPointerObservable) {
  96025. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  96026. }
  96027. prePointerInfo.skipOnPointerObservable = true;
  96028. }
  96029. }
  96030. else {
  96031. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  96032. var pointerEvent_1 = (prePointerInfo.event);
  96033. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  96034. if (originalScenePick && utilityScenePick) {
  96035. // No pick in utility scene
  96036. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  96037. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  96038. // We touched an utility mesh present in the main scene
  96039. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  96040. prePointerInfo.skipOnPointerObservable = true;
  96041. }
  96042. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96043. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  96044. }
  96045. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  96046. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  96047. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  96048. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  96049. }
  96050. }
  96051. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  96052. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  96053. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  96054. // If a previous utility layer set this, do not unset this
  96055. if (!prePointerInfo.skipOnPointerObservable) {
  96056. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  96057. }
  96058. }
  96059. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  96060. // We have a pick in both scenes but main is closer than utility
  96061. // We touched an utility mesh present in the main scene
  96062. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  96063. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  96064. prePointerInfo.skipOnPointerObservable = true;
  96065. }
  96066. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  96067. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  96068. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  96069. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  96070. }
  96071. }
  96072. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  96073. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  96074. }
  96075. }
  96076. }
  96077. });
  96078. // Render directly on top of existing scene without clearing
  96079. this.utilityLayerScene.autoClear = false;
  96080. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  96081. if (_this.shouldRender) {
  96082. _this.render();
  96083. }
  96084. });
  96085. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  96086. _this.dispose();
  96087. });
  96088. this._updateCamera();
  96089. }
  96090. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  96091. /**
  96092. * 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)
  96093. */
  96094. get: function () {
  96095. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  96096. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  96097. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  96098. UtilityLayerRenderer._DefaultUtilityLayer = null;
  96099. });
  96100. }
  96101. return UtilityLayerRenderer._DefaultUtilityLayer;
  96102. },
  96103. enumerable: true,
  96104. configurable: true
  96105. });
  96106. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  96107. /**
  96108. * 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)
  96109. */
  96110. get: function () {
  96111. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  96112. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  96113. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  96114. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  96115. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  96116. });
  96117. }
  96118. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  96119. },
  96120. enumerable: true,
  96121. configurable: true
  96122. });
  96123. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  96124. if (!prePointerInfo.skipOnPointerObservable) {
  96125. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  96126. this._lastPointerEvents[pointerEvent.pointerId] = true;
  96127. }
  96128. };
  96129. /**
  96130. * Renders the utility layers scene on top of the original scene
  96131. */
  96132. UtilityLayerRenderer.prototype.render = function () {
  96133. this._updateCamera();
  96134. if (this.utilityLayerScene.activeCamera) {
  96135. // Set the camera's scene to utility layers scene
  96136. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  96137. var camera = this.utilityLayerScene.activeCamera;
  96138. camera._scene = this.utilityLayerScene;
  96139. if (camera.leftCamera) {
  96140. camera.leftCamera._scene = this.utilityLayerScene;
  96141. }
  96142. if (camera.rightCamera) {
  96143. camera.rightCamera._scene = this.utilityLayerScene;
  96144. }
  96145. this.utilityLayerScene.render(false);
  96146. // Reset camera's scene back to original
  96147. camera._scene = oldScene;
  96148. if (camera.leftCamera) {
  96149. camera.leftCamera._scene = oldScene;
  96150. }
  96151. if (camera.rightCamera) {
  96152. camera.rightCamera._scene = oldScene;
  96153. }
  96154. }
  96155. };
  96156. /**
  96157. * Disposes of the renderer
  96158. */
  96159. UtilityLayerRenderer.prototype.dispose = function () {
  96160. this.onPointerOutObservable.clear();
  96161. if (this._afterRenderObserver) {
  96162. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  96163. }
  96164. if (this._sceneDisposeObserver) {
  96165. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96166. }
  96167. if (this._originalPointerObserver) {
  96168. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  96169. }
  96170. this.utilityLayerScene.dispose();
  96171. };
  96172. UtilityLayerRenderer.prototype._updateCamera = function () {
  96173. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  96174. };
  96175. UtilityLayerRenderer._DefaultUtilityLayer = null;
  96176. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  96177. return UtilityLayerRenderer;
  96178. }());
  96179. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  96180. })(BABYLON || (BABYLON = {}));
  96181. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  96182. //# sourceMappingURL=babylon.behavior.js.map
  96183. var BABYLON;
  96184. (function (BABYLON) {
  96185. /**
  96186. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  96187. */
  96188. var PointerDragBehavior = /** @class */ (function () {
  96189. /**
  96190. * Creates a pointer drag behavior that can be attached to a mesh
  96191. * @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)
  96192. */
  96193. function PointerDragBehavior(options) {
  96194. /**
  96195. * 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)
  96196. */
  96197. this.maxDragAngle = 0;
  96198. /**
  96199. * @hidden
  96200. */
  96201. this._useAlternatePickedPointAboveMaxDragAngle = false;
  96202. /**
  96203. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  96204. */
  96205. this.currentDraggingPointerID = -1;
  96206. /**
  96207. * If the behavior is currently in a dragging state
  96208. */
  96209. this.dragging = false;
  96210. /**
  96211. * 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)
  96212. */
  96213. this.dragDeltaRatio = 0.2;
  96214. /**
  96215. * If the drag plane orientation should be updated during the dragging (Default: true)
  96216. */
  96217. this.updateDragPlane = true;
  96218. // Debug mode will display drag planes to help visualize behavior
  96219. this._debugMode = false;
  96220. this._moving = false;
  96221. /**
  96222. * Fires each time the attached mesh is dragged with the pointer
  96223. * * delta between last drag position and current drag position in world space
  96224. * * dragDistance along the drag axis
  96225. * * dragPlaneNormal normal of the current drag plane used during the drag
  96226. * * dragPlanePoint in world space where the drag intersects the drag plane
  96227. */
  96228. this.onDragObservable = new BABYLON.Observable();
  96229. /**
  96230. * Fires each time a drag begins (eg. mouse down on mesh)
  96231. */
  96232. this.onDragStartObservable = new BABYLON.Observable();
  96233. /**
  96234. * Fires each time a drag ends (eg. mouse release after drag)
  96235. */
  96236. this.onDragEndObservable = new BABYLON.Observable();
  96237. /**
  96238. * If the attached mesh should be moved when dragged
  96239. */
  96240. this.moveAttached = true;
  96241. /**
  96242. * If the drag behavior will react to drag events (Default: true)
  96243. */
  96244. this.enabled = true;
  96245. /**
  96246. * If camera controls should be detached during the drag
  96247. */
  96248. this.detachCameraControls = true;
  96249. /**
  96250. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  96251. */
  96252. this.useObjectOrienationForDragging = true;
  96253. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  96254. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  96255. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  96256. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  96257. this._attachedElement = null;
  96258. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  96259. this._lastPointerRay = {};
  96260. this._dragDelta = new BABYLON.Vector3();
  96261. // Variables to avoid instantiation in the below method
  96262. this._pointA = new BABYLON.Vector3(0, 0, 0);
  96263. this._pointB = new BABYLON.Vector3(0, 0, 0);
  96264. this._pointC = new BABYLON.Vector3(0, 0, 0);
  96265. this._lineA = new BABYLON.Vector3(0, 0, 0);
  96266. this._lineB = new BABYLON.Vector3(0, 0, 0);
  96267. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  96268. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  96269. this._options = options ? options : {};
  96270. var optionCount = 0;
  96271. if (this._options.dragAxis) {
  96272. optionCount++;
  96273. }
  96274. if (this._options.dragPlaneNormal) {
  96275. optionCount++;
  96276. }
  96277. if (optionCount > 1) {
  96278. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  96279. }
  96280. }
  96281. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  96282. /**
  96283. * The name of the behavior
  96284. */
  96285. get: function () {
  96286. return "PointerDrag";
  96287. },
  96288. enumerable: true,
  96289. configurable: true
  96290. });
  96291. /**
  96292. * Initializes the behavior
  96293. */
  96294. PointerDragBehavior.prototype.init = function () { };
  96295. /**
  96296. * Attaches the drag behavior the passed in mesh
  96297. * @param ownerNode The mesh that will be dragged around once attached
  96298. */
  96299. PointerDragBehavior.prototype.attach = function (ownerNode) {
  96300. var _this = this;
  96301. this._scene = ownerNode.getScene();
  96302. this._attachedNode = ownerNode;
  96303. // Initialize drag plane to not interfere with existing scene
  96304. if (!PointerDragBehavior._planeScene) {
  96305. if (this._debugMode) {
  96306. PointerDragBehavior._planeScene = this._scene;
  96307. }
  96308. else {
  96309. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  96310. PointerDragBehavior._planeScene.detachControl();
  96311. this._scene.getEngine().scenes.pop();
  96312. this._scene.onDisposeObservable.addOnce(function () {
  96313. PointerDragBehavior._planeScene.dispose();
  96314. PointerDragBehavior._planeScene = null;
  96315. });
  96316. }
  96317. }
  96318. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  96319. // State of the drag
  96320. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  96321. var pickPredicate = function (m) {
  96322. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  96323. };
  96324. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  96325. if (!_this.enabled) {
  96326. return;
  96327. }
  96328. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96329. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  96330. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  96331. }
  96332. }
  96333. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  96334. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  96335. _this.releaseDrag();
  96336. }
  96337. }
  96338. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  96339. var pointerId = pointerInfo.event.pointerId;
  96340. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  96341. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  96342. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  96343. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  96344. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  96345. }
  96346. _this.currentDraggingPointerID = pointerId;
  96347. }
  96348. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  96349. if (!_this._lastPointerRay[pointerId]) {
  96350. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  96351. }
  96352. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  96353. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  96354. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  96355. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  96356. _this._moveDrag(pointerInfo.pickInfo.ray);
  96357. }
  96358. }
  96359. }
  96360. });
  96361. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  96362. if (_this._moving && _this.moveAttached) {
  96363. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  96364. // Slowly move mesh to avoid jitter
  96365. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  96366. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  96367. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  96368. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  96369. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  96370. }
  96371. });
  96372. };
  96373. /**
  96374. * Force relase the drag action by code.
  96375. */
  96376. PointerDragBehavior.prototype.releaseDrag = function () {
  96377. this.dragging = false;
  96378. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  96379. this.currentDraggingPointerID = -1;
  96380. this._moving = false;
  96381. // Reattach camera controls
  96382. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  96383. this._scene.activeCamera.attachControl(this._attachedElement, true);
  96384. }
  96385. };
  96386. /**
  96387. * Simulates the start of a pointer drag event on the behavior
  96388. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  96389. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  96390. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  96391. */
  96392. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  96393. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  96394. this._startDrag(pointerId, fromRay, startPickedPoint);
  96395. var lastRay = this._lastPointerRay[pointerId];
  96396. if (pointerId === PointerDragBehavior._AnyMouseID) {
  96397. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  96398. }
  96399. if (lastRay) {
  96400. // if there was a last pointer ray drag the object there
  96401. this._moveDrag(lastRay);
  96402. }
  96403. };
  96404. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  96405. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  96406. return;
  96407. }
  96408. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  96409. // Create start ray from the camera to the object
  96410. if (fromRay) {
  96411. this._startDragRay.direction.copyFrom(fromRay.direction);
  96412. this._startDragRay.origin.copyFrom(fromRay.origin);
  96413. }
  96414. else {
  96415. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  96416. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  96417. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  96418. }
  96419. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  96420. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  96421. if (pickedPoint) {
  96422. this.dragging = true;
  96423. this.currentDraggingPointerID = pointerId;
  96424. this.lastDragPosition.copyFrom(pickedPoint);
  96425. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  96426. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  96427. // Detatch camera controls
  96428. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  96429. if (this._scene.activeCamera.inputs.attachedElement) {
  96430. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  96431. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  96432. }
  96433. else {
  96434. this._attachedElement = null;
  96435. }
  96436. }
  96437. }
  96438. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  96439. };
  96440. PointerDragBehavior.prototype._moveDrag = function (ray) {
  96441. this._moving = true;
  96442. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  96443. if (pickedPoint) {
  96444. if (this.updateDragPlane) {
  96445. this._updateDragPlanePosition(ray, pickedPoint);
  96446. }
  96447. var dragLength = 0;
  96448. // depending on the drag mode option drag accordingly
  96449. if (this._options.dragAxis) {
  96450. // Convert local drag axis to world
  96451. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  96452. // Project delta drag from the drag plane onto the drag axis
  96453. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  96454. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  96455. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  96456. }
  96457. else {
  96458. dragLength = this._dragDelta.length();
  96459. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  96460. }
  96461. this._targetPosition.addInPlace(this._dragDelta);
  96462. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  96463. this.lastDragPosition.copyFrom(pickedPoint);
  96464. }
  96465. };
  96466. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  96467. var _this = this;
  96468. if (!ray) {
  96469. return null;
  96470. }
  96471. // Calculate angle between plane normal and ray
  96472. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  96473. // Correct if ray is casted from oposite side
  96474. if (angle > Math.PI / 2) {
  96475. angle = Math.PI - angle;
  96476. }
  96477. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  96478. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  96479. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  96480. // Invert ray direction along the towards object axis
  96481. this._tmpVector.copyFrom(ray.direction);
  96482. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  96483. this._alternatePickedPoint.normalize();
  96484. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  96485. this._tmpVector.addInPlace(this._alternatePickedPoint);
  96486. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  96487. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  96488. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  96489. this._alternatePickedPoint.addInPlace(this._tmpVector);
  96490. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  96491. return this._alternatePickedPoint;
  96492. }
  96493. else {
  96494. return null;
  96495. }
  96496. }
  96497. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  96498. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  96499. return pickResult.pickedPoint;
  96500. }
  96501. else {
  96502. return null;
  96503. }
  96504. };
  96505. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  96506. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  96507. this._pointA.copyFrom(dragPlanePosition);
  96508. if (this._options.dragAxis) {
  96509. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  96510. // Calculate plane normal in direction of camera but perpendicular to drag axis
  96511. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  96512. ray.origin.subtractToRef(this._pointA, this._pointC);
  96513. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  96514. // Get perpendicular line from direction to camera and drag axis
  96515. this._pointB.subtractToRef(this._pointA, this._lineA);
  96516. this._pointC.subtractToRef(this._pointA, this._lineB);
  96517. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  96518. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  96519. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  96520. this._lookAt.normalize();
  96521. this._dragPlane.position.copyFrom(this._pointA);
  96522. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  96523. this._dragPlane.lookAt(this._lookAt);
  96524. }
  96525. else if (this._options.dragPlaneNormal) {
  96526. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  96527. this._dragPlane.position.copyFrom(this._pointA);
  96528. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  96529. this._dragPlane.lookAt(this._lookAt);
  96530. }
  96531. else {
  96532. this._dragPlane.position.copyFrom(this._pointA);
  96533. this._dragPlane.lookAt(ray.origin);
  96534. }
  96535. this._dragPlane.computeWorldMatrix(true);
  96536. };
  96537. /**
  96538. * Detaches the behavior from the mesh
  96539. */
  96540. PointerDragBehavior.prototype.detach = function () {
  96541. if (this._pointerObserver) {
  96542. this._scene.onPointerObservable.remove(this._pointerObserver);
  96543. }
  96544. if (this._beforeRenderObserver) {
  96545. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  96546. }
  96547. };
  96548. PointerDragBehavior._AnyMouseID = -2;
  96549. return PointerDragBehavior;
  96550. }());
  96551. BABYLON.PointerDragBehavior = PointerDragBehavior;
  96552. })(BABYLON || (BABYLON = {}));
  96553. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  96554. var BABYLON;
  96555. (function (BABYLON) {
  96556. /**
  96557. * A behavior that when attached to a mesh will allow the mesh to be scaled
  96558. */
  96559. var MultiPointerScaleBehavior = /** @class */ (function () {
  96560. /**
  96561. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  96562. */
  96563. function MultiPointerScaleBehavior() {
  96564. this._startDistance = 0;
  96565. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  96566. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  96567. this._sceneRenderObserver = null;
  96568. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  96569. this._dragBehaviorA.moveAttached = false;
  96570. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  96571. this._dragBehaviorB.moveAttached = false;
  96572. }
  96573. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  96574. /**
  96575. * The name of the behavior
  96576. */
  96577. get: function () {
  96578. return "MultiPointerScale";
  96579. },
  96580. enumerable: true,
  96581. configurable: true
  96582. });
  96583. /**
  96584. * Initializes the behavior
  96585. */
  96586. MultiPointerScaleBehavior.prototype.init = function () { };
  96587. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  96588. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  96589. };
  96590. /**
  96591. * Attaches the scale behavior the passed in mesh
  96592. * @param ownerNode The mesh that will be scaled around once attached
  96593. */
  96594. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  96595. var _this = this;
  96596. this._ownerNode = ownerNode;
  96597. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  96598. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  96599. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96600. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96601. _this._dragBehaviorA.releaseDrag();
  96602. }
  96603. else {
  96604. _this._initialScale.copyFrom(ownerNode.scaling);
  96605. _this._startDistance = _this._getCurrentDistance();
  96606. }
  96607. }
  96608. });
  96609. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  96610. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96611. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96612. _this._dragBehaviorB.releaseDrag();
  96613. }
  96614. else {
  96615. _this._initialScale.copyFrom(ownerNode.scaling);
  96616. _this._startDistance = _this._getCurrentDistance();
  96617. }
  96618. }
  96619. });
  96620. // Once both drag behaviors are active scale based on the distance between the two pointers
  96621. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96622. behavior.onDragObservable.add(function () {
  96623. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96624. var ratio = _this._getCurrentDistance() / _this._startDistance;
  96625. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  96626. }
  96627. });
  96628. });
  96629. ownerNode.addBehavior(this._dragBehaviorA);
  96630. ownerNode.addBehavior(this._dragBehaviorB);
  96631. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96632. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96633. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96634. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  96635. if (change.length() > 0.01) {
  96636. ownerNode.scaling.addInPlace(change);
  96637. }
  96638. }
  96639. });
  96640. };
  96641. /**
  96642. * Detaches the behavior from the mesh
  96643. */
  96644. MultiPointerScaleBehavior.prototype.detach = function () {
  96645. var _this = this;
  96646. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96647. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96648. behavior.onDragStartObservable.clear();
  96649. behavior.onDragObservable.clear();
  96650. _this._ownerNode.removeBehavior(behavior);
  96651. });
  96652. };
  96653. return MultiPointerScaleBehavior;
  96654. }());
  96655. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  96656. })(BABYLON || (BABYLON = {}));
  96657. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  96658. var BABYLON;
  96659. (function (BABYLON) {
  96660. /**
  96661. * 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
  96662. */
  96663. var SixDofDragBehavior = /** @class */ (function () {
  96664. /**
  96665. * 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
  96666. */
  96667. function SixDofDragBehavior() {
  96668. this._sceneRenderObserver = null;
  96669. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  96670. this._moving = false;
  96671. this._startingOrientation = new BABYLON.Quaternion();
  96672. /**
  96673. * 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)
  96674. */
  96675. this.zDragFactor = 3;
  96676. /**
  96677. * If the behavior is currently in a dragging state
  96678. */
  96679. this.dragging = false;
  96680. /**
  96681. * 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)
  96682. */
  96683. this.dragDeltaRatio = 0.2;
  96684. /**
  96685. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  96686. */
  96687. this.currentDraggingPointerID = -1;
  96688. /**
  96689. * If camera controls should be detached during the drag
  96690. */
  96691. this.detachCameraControls = true;
  96692. /**
  96693. * Fires each time a drag starts
  96694. */
  96695. this.onDragStartObservable = new BABYLON.Observable();
  96696. /**
  96697. * Fires each time a drag ends (eg. mouse release after drag)
  96698. */
  96699. this.onDragEndObservable = new BABYLON.Observable();
  96700. }
  96701. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  96702. /**
  96703. * The name of the behavior
  96704. */
  96705. get: function () {
  96706. return "SixDofDrag";
  96707. },
  96708. enumerable: true,
  96709. configurable: true
  96710. });
  96711. /**
  96712. * Initializes the behavior
  96713. */
  96714. SixDofDragBehavior.prototype.init = function () { };
  96715. /**
  96716. * Attaches the scale behavior the passed in mesh
  96717. * @param ownerNode The mesh that will be scaled around once attached
  96718. */
  96719. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  96720. var _this = this;
  96721. this._ownerNode = ownerNode;
  96722. this._scene = this._ownerNode.getScene();
  96723. if (!SixDofDragBehavior._virtualScene) {
  96724. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  96725. this._scene.getEngine().scenes.pop();
  96726. }
  96727. var pickedMesh = null;
  96728. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  96729. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  96730. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96731. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  96732. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96733. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  96734. var pickPredicate = function (m) {
  96735. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  96736. };
  96737. var attachedElement = null;
  96738. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  96739. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96740. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  96741. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96742. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96743. }
  96744. pickedMesh = _this._ownerNode;
  96745. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96746. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96747. // Set position and orientation of the controller
  96748. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96749. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96750. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  96751. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96752. pickedMesh.computeWorldMatrix();
  96753. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  96754. if (!pickedMesh.rotationQuaternion) {
  96755. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  96756. }
  96757. var oldParent = pickedMesh.parent;
  96758. pickedMesh.setParent(null);
  96759. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  96760. pickedMesh.setParent(oldParent);
  96761. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96762. // Update state
  96763. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96764. _this.dragging = true;
  96765. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  96766. // Detatch camera controls
  96767. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96768. if (_this._scene.activeCamera.inputs.attachedElement) {
  96769. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  96770. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  96771. }
  96772. else {
  96773. attachedElement = null;
  96774. }
  96775. }
  96776. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96777. _this.onDragStartObservable.notifyObservers({});
  96778. }
  96779. }
  96780. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  96781. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  96782. _this.dragging = false;
  96783. _this._moving = false;
  96784. _this.currentDraggingPointerID = -1;
  96785. pickedMesh = null;
  96786. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96787. // Reattach camera controls
  96788. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96789. _this._scene.activeCamera.attachControl(attachedElement, true);
  96790. }
  96791. _this.onDragEndObservable.notifyObservers({});
  96792. }
  96793. }
  96794. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  96795. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  96796. var zDragFactor = _this.zDragFactor;
  96797. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96798. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96799. zDragFactor = 0;
  96800. }
  96801. // Calculate controller drag distance in controller space
  96802. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  96803. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96804. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  96805. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96806. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  96807. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  96808. if (_this._virtualDragMesh.position.z < 0) {
  96809. _this._virtualDragMesh.position.z = 0;
  96810. }
  96811. // Update the controller position
  96812. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96813. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96814. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96815. // Move the virtualObjectsPosition into the picked mesh's space if needed
  96816. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96817. if (pickedMesh.parent) {
  96818. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  96819. }
  96820. if (!_this._moving) {
  96821. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  96822. }
  96823. _this._moving = true;
  96824. }
  96825. }
  96826. });
  96827. var tmpQuaternion = new BABYLON.Quaternion();
  96828. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96829. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96830. if (_this.dragging && _this._moving && pickedMesh) {
  96831. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96832. // Slowly move mesh to avoid jitter
  96833. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  96834. // Get change in rotation
  96835. tmpQuaternion.copyFrom(_this._startingOrientation);
  96836. tmpQuaternion.x = -tmpQuaternion.x;
  96837. tmpQuaternion.y = -tmpQuaternion.y;
  96838. tmpQuaternion.z = -tmpQuaternion.z;
  96839. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  96840. // Convert change in rotation to only y axis rotation
  96841. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  96842. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  96843. // Slowly move mesh to avoid jitter
  96844. var oldParent = pickedMesh.parent;
  96845. pickedMesh.setParent(null);
  96846. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  96847. pickedMesh.setParent(oldParent);
  96848. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96849. }
  96850. });
  96851. };
  96852. /**
  96853. * Detaches the behavior from the mesh
  96854. */
  96855. SixDofDragBehavior.prototype.detach = function () {
  96856. if (this._scene) {
  96857. this._scene.onPointerObservable.remove(this._pointerObserver);
  96858. }
  96859. if (this._ownerNode) {
  96860. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96861. }
  96862. if (this._virtualOriginMesh) {
  96863. this._virtualOriginMesh.dispose();
  96864. }
  96865. if (this._virtualDragMesh) {
  96866. this._virtualDragMesh.dispose();
  96867. }
  96868. this.onDragEndObservable.clear();
  96869. this.onDragStartObservable.clear();
  96870. };
  96871. return SixDofDragBehavior;
  96872. }());
  96873. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  96874. })(BABYLON || (BABYLON = {}));
  96875. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  96876. var BABYLON;
  96877. (function (BABYLON) {
  96878. /**
  96879. * @hidden
  96880. */
  96881. var FaceDirectionInfo = /** @class */ (function () {
  96882. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  96883. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  96884. if (diff === void 0) { diff = 0; }
  96885. if (ignore === void 0) { ignore = false; }
  96886. this.direction = direction;
  96887. this.rotatedDirection = rotatedDirection;
  96888. this.diff = diff;
  96889. this.ignore = ignore;
  96890. }
  96891. return FaceDirectionInfo;
  96892. }());
  96893. /**
  96894. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  96895. */
  96896. var AttachToBoxBehavior = /** @class */ (function () {
  96897. /**
  96898. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  96899. * @param ui The transform node that should be attched to the mesh
  96900. */
  96901. function AttachToBoxBehavior(ui) {
  96902. this.ui = ui;
  96903. /**
  96904. * The name of the behavior
  96905. */
  96906. this.name = "AttachToBoxBehavior";
  96907. /**
  96908. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  96909. */
  96910. this.distanceAwayFromFace = 0.15;
  96911. /**
  96912. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  96913. */
  96914. this.distanceAwayFromBottomOfFace = 0.15;
  96915. 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))];
  96916. this._tmpMatrix = new BABYLON.Matrix();
  96917. this._tmpVector = new BABYLON.Vector3();
  96918. this._zeroVector = BABYLON.Vector3.Zero();
  96919. this._lookAtTmpMatrix = new BABYLON.Matrix();
  96920. /* Does nothing */
  96921. }
  96922. /**
  96923. * Initializes the behavior
  96924. */
  96925. AttachToBoxBehavior.prototype.init = function () {
  96926. /* Does nothing */
  96927. };
  96928. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  96929. var _this = this;
  96930. // Go over each face and calculate the angle between the face's normal and targetDirection
  96931. this._faceVectors.forEach(function (v) {
  96932. if (!_this._target.rotationQuaternion) {
  96933. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  96934. }
  96935. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  96936. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  96937. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  96938. });
  96939. // Return the face information of the one with the normal closeset to target direction
  96940. return this._faceVectors.reduce(function (min, p) {
  96941. if (min.ignore) {
  96942. return p;
  96943. }
  96944. else if (p.ignore) {
  96945. return min;
  96946. }
  96947. else {
  96948. return min.diff < p.diff ? min : p;
  96949. }
  96950. }, this._faceVectors[0]);
  96951. };
  96952. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  96953. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  96954. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  96955. this._lookAtTmpMatrix.invert();
  96956. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  96957. };
  96958. /**
  96959. * Attaches the AttachToBoxBehavior to the passed in mesh
  96960. * @param target The mesh that the specified node will be attached to
  96961. */
  96962. AttachToBoxBehavior.prototype.attach = function (target) {
  96963. var _this = this;
  96964. this._target = target;
  96965. this._scene = this._target.getScene();
  96966. // Every frame, update the app bars position
  96967. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  96968. if (!_this._scene.activeCamera) {
  96969. return;
  96970. }
  96971. // Find the face closest to the cameras position
  96972. var cameraPos = _this._scene.activeCamera.position;
  96973. if (_this._scene.activeCamera.devicePosition) {
  96974. cameraPos = _this._scene.activeCamera.devicePosition;
  96975. }
  96976. var facing = _this._closestFace(cameraPos.subtract(target.position));
  96977. if (_this._scene.activeCamera.leftCamera) {
  96978. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96979. }
  96980. else {
  96981. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96982. }
  96983. // Get camera up direction
  96984. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  96985. // Ignore faces to not select a parrelel face for the up vector of the UI
  96986. _this._faceVectors.forEach(function (v) {
  96987. if (facing.direction.x && v.direction.x) {
  96988. v.ignore = true;
  96989. }
  96990. if (facing.direction.y && v.direction.y) {
  96991. v.ignore = true;
  96992. }
  96993. if (facing.direction.z && v.direction.z) {
  96994. v.ignore = true;
  96995. }
  96996. });
  96997. var facingUp = _this._closestFace(_this._tmpVector);
  96998. // Unignore faces
  96999. _this._faceVectors.forEach(function (v) {
  97000. v.ignore = false;
  97001. });
  97002. // Position the app bar on that face
  97003. _this.ui.position.copyFrom(target.position);
  97004. if (facing.direction.x) {
  97005. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  97006. _this.ui.position.addInPlace(_this._tmpVector);
  97007. }
  97008. if (facing.direction.y) {
  97009. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  97010. _this.ui.position.addInPlace(_this._tmpVector);
  97011. }
  97012. if (facing.direction.z) {
  97013. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  97014. _this.ui.position.addInPlace(_this._tmpVector);
  97015. }
  97016. // Rotate to be oriented properly to the camera
  97017. if (!_this.ui.rotationQuaternion) {
  97018. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  97019. }
  97020. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  97021. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  97022. // Place ui the correct distance from the bottom of the mesh
  97023. if (facingUp.direction.x) {
  97024. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  97025. }
  97026. if (facingUp.direction.y) {
  97027. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  97028. }
  97029. if (facingUp.direction.z) {
  97030. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  97031. }
  97032. _this.ui.position.addInPlace(_this._tmpVector);
  97033. });
  97034. };
  97035. /**
  97036. * Detaches the behavior from the mesh
  97037. */
  97038. AttachToBoxBehavior.prototype.detach = function () {
  97039. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  97040. };
  97041. return AttachToBoxBehavior;
  97042. }());
  97043. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  97044. })(BABYLON || (BABYLON = {}));
  97045. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  97046. var BABYLON;
  97047. (function (BABYLON) {
  97048. /**
  97049. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  97050. */
  97051. var FadeInOutBehavior = /** @class */ (function () {
  97052. /**
  97053. * Instatiates the FadeInOutBehavior
  97054. */
  97055. function FadeInOutBehavior() {
  97056. var _this = this;
  97057. /**
  97058. * Time in milliseconds to delay before fading in (Default: 0)
  97059. */
  97060. this.delay = 0;
  97061. /**
  97062. * Time in milliseconds for the mesh to fade in (Default: 300)
  97063. */
  97064. this.fadeInTime = 300;
  97065. this._millisecondsPerFrame = 1000 / 60;
  97066. this._hovered = false;
  97067. this._hoverValue = 0;
  97068. this._ownerNode = null;
  97069. this._update = function () {
  97070. if (_this._ownerNode) {
  97071. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  97072. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  97073. if (_this._ownerNode.visibility > 1) {
  97074. _this._setAllVisibility(_this._ownerNode, 1);
  97075. _this._hoverValue = _this.fadeInTime + _this.delay;
  97076. return;
  97077. }
  97078. else if (_this._ownerNode.visibility < 0) {
  97079. _this._setAllVisibility(_this._ownerNode, 0);
  97080. if (_this._hoverValue < 0) {
  97081. _this._hoverValue = 0;
  97082. return;
  97083. }
  97084. }
  97085. setTimeout(_this._update, _this._millisecondsPerFrame);
  97086. }
  97087. };
  97088. }
  97089. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  97090. /**
  97091. * The name of the behavior
  97092. */
  97093. get: function () {
  97094. return "FadeInOut";
  97095. },
  97096. enumerable: true,
  97097. configurable: true
  97098. });
  97099. /**
  97100. * Initializes the behavior
  97101. */
  97102. FadeInOutBehavior.prototype.init = function () {
  97103. };
  97104. /**
  97105. * Attaches the fade behavior on the passed in mesh
  97106. * @param ownerNode The mesh that will be faded in/out once attached
  97107. */
  97108. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  97109. this._ownerNode = ownerNode;
  97110. this._setAllVisibility(this._ownerNode, 0);
  97111. };
  97112. /**
  97113. * Detaches the behavior from the mesh
  97114. */
  97115. FadeInOutBehavior.prototype.detach = function () {
  97116. this._ownerNode = null;
  97117. };
  97118. /**
  97119. * Triggers the mesh to begin fading in or out
  97120. * @param value if the object should fade in or out (true to fade in)
  97121. */
  97122. FadeInOutBehavior.prototype.fadeIn = function (value) {
  97123. this._hovered = value;
  97124. this._update();
  97125. };
  97126. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  97127. var _this = this;
  97128. mesh.visibility = value;
  97129. mesh.getChildMeshes().forEach(function (c) {
  97130. _this._setAllVisibility(c, value);
  97131. });
  97132. };
  97133. return FadeInOutBehavior;
  97134. }());
  97135. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  97136. })(BABYLON || (BABYLON = {}));
  97137. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  97138. var BABYLON;
  97139. (function (BABYLON) {
  97140. /**
  97141. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  97142. */
  97143. var Gizmo = /** @class */ (function () {
  97144. /**
  97145. * Creates a gizmo
  97146. * @param gizmoLayer The utility layer the gizmo will be added to
  97147. */
  97148. function Gizmo(
  97149. /** The utility layer the gizmo will be added to */
  97150. gizmoLayer) {
  97151. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97152. var _this = this;
  97153. this.gizmoLayer = gizmoLayer;
  97154. /**
  97155. * Ratio for the scale of the gizmo (Default: 1)
  97156. */
  97157. this.scaleRatio = 1;
  97158. this._tmpMatrix = new BABYLON.Matrix();
  97159. /**
  97160. * If a custom mesh has been set (Default: false)
  97161. */
  97162. this._customMeshSet = false;
  97163. /**
  97164. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  97165. */
  97166. this.updateGizmoRotationToMatchAttachedMesh = true;
  97167. /**
  97168. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  97169. */
  97170. this.updateGizmoPositionToMatchAttachedMesh = true;
  97171. /**
  97172. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  97173. */
  97174. this._updateScale = true;
  97175. this._interactionsEnabled = true;
  97176. this._tempVector = new BABYLON.Vector3();
  97177. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  97178. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  97179. _this._update();
  97180. });
  97181. this.attachedMesh = null;
  97182. }
  97183. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  97184. /**
  97185. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  97186. * * When set, interactions will be enabled
  97187. */
  97188. get: function () {
  97189. return this._attachedMesh;
  97190. },
  97191. set: function (value) {
  97192. this._attachedMesh = value;
  97193. this._rootMesh.setEnabled(value ? true : false);
  97194. this._attachedMeshChanged(value);
  97195. },
  97196. enumerable: true,
  97197. configurable: true
  97198. });
  97199. /**
  97200. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  97201. * @param mesh The mesh to replace the default mesh of the gizmo
  97202. */
  97203. Gizmo.prototype.setCustomMesh = function (mesh) {
  97204. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  97205. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  97206. }
  97207. this._rootMesh.getChildMeshes().forEach(function (c) {
  97208. c.dispose();
  97209. });
  97210. mesh.parent = this._rootMesh;
  97211. this._customMeshSet = true;
  97212. };
  97213. Gizmo.prototype._attachedMeshChanged = function (value) {
  97214. };
  97215. /**
  97216. * @hidden
  97217. * Updates the gizmo to match the attached mesh's position/rotation
  97218. */
  97219. Gizmo.prototype._update = function () {
  97220. if (this.attachedMesh) {
  97221. if (this.updateGizmoRotationToMatchAttachedMesh) {
  97222. if (!this._rootMesh.rotationQuaternion) {
  97223. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  97224. }
  97225. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  97226. this._tempVector.copyFrom(this.attachedMesh.scaling);
  97227. if (this.attachedMesh.scaling.x < 0) {
  97228. this.attachedMesh.scaling.x *= -1;
  97229. }
  97230. if (this.attachedMesh.scaling.y < 0) {
  97231. this.attachedMesh.scaling.y *= -1;
  97232. }
  97233. if (this.attachedMesh.scaling.z < 0) {
  97234. this.attachedMesh.scaling.z *= -1;
  97235. }
  97236. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  97237. this.attachedMesh.scaling.copyFrom(this._tempVector);
  97238. this.attachedMesh.computeWorldMatrix();
  97239. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  97240. }
  97241. else if (this._rootMesh.rotationQuaternion) {
  97242. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  97243. }
  97244. if (this.updateGizmoPositionToMatchAttachedMesh) {
  97245. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  97246. }
  97247. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  97248. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  97249. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  97250. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  97251. }
  97252. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  97253. var dist = this._tempVector.length() * this.scaleRatio;
  97254. this._rootMesh.scaling.set(dist, dist, dist);
  97255. }
  97256. }
  97257. };
  97258. /**
  97259. * Disposes of the gizmo
  97260. */
  97261. Gizmo.prototype.dispose = function () {
  97262. this._rootMesh.dispose();
  97263. if (this._beforeRenderObserver) {
  97264. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  97265. }
  97266. };
  97267. return Gizmo;
  97268. }());
  97269. BABYLON.Gizmo = Gizmo;
  97270. })(BABYLON || (BABYLON = {}));
  97271. //# sourceMappingURL=babylon.gizmo.js.map
  97272. var BABYLON;
  97273. (function (BABYLON) {
  97274. /**
  97275. * Single axis drag gizmo
  97276. */
  97277. var AxisDragGizmo = /** @class */ (function (_super) {
  97278. __extends(AxisDragGizmo, _super);
  97279. /**
  97280. * Creates an AxisDragGizmo
  97281. * @param gizmoLayer The utility layer the gizmo will be added to
  97282. * @param dragAxis The axis which the gizmo will be able to drag on
  97283. * @param color The color of the gizmo
  97284. */
  97285. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  97286. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97287. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97288. var _this = _super.call(this, gizmoLayer) || this;
  97289. _this._pointerObserver = null;
  97290. /**
  97291. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97292. */
  97293. _this.snapDistance = 0;
  97294. /**
  97295. * Event that fires each time the gizmo snaps to a new location.
  97296. * * snapDistance is the the change in distance
  97297. */
  97298. _this.onSnapObservable = new BABYLON.Observable();
  97299. // Create Material
  97300. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97301. coloredMaterial.disableLighting = true;
  97302. coloredMaterial.emissiveColor = color;
  97303. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97304. hoverMaterial.disableLighting = true;
  97305. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97306. // Build mesh on root node
  97307. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97308. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  97309. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  97310. arrowTail.color = coloredMaterial.emissiveColor;
  97311. arrow.addChild(arrowMesh);
  97312. arrow.addChild(arrowTail);
  97313. // Position arrow pointing in its drag axis
  97314. arrowMesh.scaling.scaleInPlace(0.05);
  97315. arrowMesh.material = coloredMaterial;
  97316. arrowMesh.rotation.x = Math.PI / 2;
  97317. arrowMesh.position.z += 0.3;
  97318. arrowTail.scaling.scaleInPlace(0.26);
  97319. arrowTail.rotation.x = Math.PI / 2;
  97320. arrowTail.material = coloredMaterial;
  97321. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  97322. arrow.scaling.scaleInPlace(1 / 3);
  97323. _this._rootMesh.addChild(arrow);
  97324. var currentSnapDragDistance = 0;
  97325. var tmpVector = new BABYLON.Vector3();
  97326. var tmpSnapEvent = { snapDistance: 0 };
  97327. // Add drag behavior to handle events when the gizmo is dragged
  97328. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  97329. _this.dragBehavior.moveAttached = false;
  97330. _this._rootMesh.addBehavior(_this.dragBehavior);
  97331. var localDelta = new BABYLON.Vector3();
  97332. var tmpMatrix = new BABYLON.Matrix();
  97333. _this.dragBehavior.onDragObservable.add(function (event) {
  97334. if (_this.attachedMesh) {
  97335. // Convert delta to local translation if it has a parent
  97336. if (_this.attachedMesh.parent) {
  97337. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  97338. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  97339. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  97340. }
  97341. else {
  97342. localDelta.copyFrom(event.delta);
  97343. }
  97344. // Snapping logic
  97345. if (_this.snapDistance == 0) {
  97346. _this.attachedMesh.position.addInPlace(localDelta);
  97347. }
  97348. else {
  97349. currentSnapDragDistance += event.dragDistance;
  97350. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  97351. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  97352. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  97353. localDelta.normalizeToRef(tmpVector);
  97354. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  97355. _this.attachedMesh.position.addInPlace(tmpVector);
  97356. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  97357. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  97358. }
  97359. }
  97360. }
  97361. });
  97362. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97363. if (_this._customMeshSet) {
  97364. return;
  97365. }
  97366. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  97367. var material = isHovered ? hoverMaterial : coloredMaterial;
  97368. _this._rootMesh.getChildMeshes().forEach(function (m) {
  97369. m.material = material;
  97370. if (m.color) {
  97371. m.color = material.emissiveColor;
  97372. }
  97373. });
  97374. });
  97375. return _this;
  97376. }
  97377. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  97378. if (this.dragBehavior) {
  97379. this.dragBehavior.enabled = value ? true : false;
  97380. }
  97381. };
  97382. /**
  97383. * Disposes of the gizmo
  97384. */
  97385. AxisDragGizmo.prototype.dispose = function () {
  97386. this.onSnapObservable.clear();
  97387. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97388. this.dragBehavior.detach();
  97389. _super.prototype.dispose.call(this);
  97390. };
  97391. return AxisDragGizmo;
  97392. }(BABYLON.Gizmo));
  97393. BABYLON.AxisDragGizmo = AxisDragGizmo;
  97394. })(BABYLON || (BABYLON = {}));
  97395. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  97396. var BABYLON;
  97397. (function (BABYLON) {
  97398. /**
  97399. * Single axis scale gizmo
  97400. */
  97401. var AxisScaleGizmo = /** @class */ (function (_super) {
  97402. __extends(AxisScaleGizmo, _super);
  97403. /**
  97404. * Creates an AxisScaleGizmo
  97405. * @param gizmoLayer The utility layer the gizmo will be added to
  97406. * @param dragAxis The axis which the gizmo will be able to scale on
  97407. * @param color The color of the gizmo
  97408. */
  97409. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  97410. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97411. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97412. var _this = _super.call(this, gizmoLayer) || this;
  97413. _this._pointerObserver = null;
  97414. /**
  97415. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97416. */
  97417. _this.snapDistance = 0;
  97418. /**
  97419. * Event that fires each time the gizmo snaps to a new location.
  97420. * * snapDistance is the the change in distance
  97421. */
  97422. _this.onSnapObservable = new BABYLON.Observable();
  97423. /**
  97424. * If the scaling operation should be done on all axis (default: false)
  97425. */
  97426. _this.uniformScaling = false;
  97427. // Create Material
  97428. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97429. _this._coloredMaterial.disableLighting = true;
  97430. _this._coloredMaterial.emissiveColor = color;
  97431. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97432. hoverMaterial.disableLighting = true;
  97433. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97434. // Build mesh on root node
  97435. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97436. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  97437. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  97438. arrowTail.color = _this._coloredMaterial.emissiveColor;
  97439. arrow.addChild(arrowMesh);
  97440. arrow.addChild(arrowTail);
  97441. // Position arrow pointing in its drag axis
  97442. arrowMesh.scaling.scaleInPlace(0.1);
  97443. arrowMesh.material = _this._coloredMaterial;
  97444. arrowMesh.rotation.x = Math.PI / 2;
  97445. arrowMesh.position.z += 0.3;
  97446. arrowTail.scaling.scaleInPlace(0.26);
  97447. arrowTail.rotation.x = Math.PI / 2;
  97448. arrowTail.material = _this._coloredMaterial;
  97449. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  97450. _this._rootMesh.addChild(arrow);
  97451. arrow.scaling.scaleInPlace(1 / 3);
  97452. // Add drag behavior to handle events when the gizmo is dragged
  97453. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  97454. _this.dragBehavior.moveAttached = false;
  97455. _this._rootMesh.addBehavior(_this.dragBehavior);
  97456. var currentSnapDragDistance = 0;
  97457. var tmpVector = new BABYLON.Vector3();
  97458. var tmpSnapEvent = { snapDistance: 0 };
  97459. _this.dragBehavior.onDragObservable.add(function (event) {
  97460. if (_this.attachedMesh) {
  97461. // Snapping logic
  97462. var snapped = false;
  97463. var dragSteps = 0;
  97464. if (_this.uniformScaling) {
  97465. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  97466. if (tmpVector.y < 0) {
  97467. tmpVector.scaleInPlace(-1);
  97468. }
  97469. }
  97470. else {
  97471. tmpVector.copyFrom(dragAxis);
  97472. }
  97473. if (_this.snapDistance == 0) {
  97474. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  97475. }
  97476. else {
  97477. currentSnapDragDistance += event.dragDistance;
  97478. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  97479. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  97480. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  97481. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  97482. snapped = true;
  97483. }
  97484. else {
  97485. tmpVector.scaleInPlace(0);
  97486. }
  97487. }
  97488. _this.attachedMesh.scaling.addInPlace(tmpVector);
  97489. if (snapped) {
  97490. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  97491. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  97492. }
  97493. }
  97494. });
  97495. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97496. if (_this._customMeshSet) {
  97497. return;
  97498. }
  97499. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  97500. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  97501. _this._rootMesh.getChildMeshes().forEach(function (m) {
  97502. m.material = material;
  97503. if (m.color) {
  97504. m.color = material.emissiveColor;
  97505. }
  97506. });
  97507. });
  97508. return _this;
  97509. }
  97510. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  97511. if (this.dragBehavior) {
  97512. this.dragBehavior.enabled = value ? true : false;
  97513. }
  97514. };
  97515. /**
  97516. * Disposes of the gizmo
  97517. */
  97518. AxisScaleGizmo.prototype.dispose = function () {
  97519. this.onSnapObservable.clear();
  97520. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97521. this.dragBehavior.detach();
  97522. _super.prototype.dispose.call(this);
  97523. };
  97524. /**
  97525. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  97526. * @param mesh The mesh to replace the default mesh of the gizmo
  97527. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  97528. */
  97529. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  97530. var _this = this;
  97531. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  97532. _super.prototype.setCustomMesh.call(this, mesh);
  97533. if (useGizmoMaterial) {
  97534. this._rootMesh.getChildMeshes().forEach(function (m) {
  97535. m.material = _this._coloredMaterial;
  97536. if (m.color) {
  97537. m.color = _this._coloredMaterial.emissiveColor;
  97538. }
  97539. });
  97540. this._customMeshSet = false;
  97541. }
  97542. };
  97543. return AxisScaleGizmo;
  97544. }(BABYLON.Gizmo));
  97545. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  97546. })(BABYLON || (BABYLON = {}));
  97547. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  97548. var BABYLON;
  97549. (function (BABYLON) {
  97550. /**
  97551. * Single plane rotation gizmo
  97552. */
  97553. var PlaneRotationGizmo = /** @class */ (function (_super) {
  97554. __extends(PlaneRotationGizmo, _super);
  97555. /**
  97556. * Creates a PlaneRotationGizmo
  97557. * @param gizmoLayer The utility layer the gizmo will be added to
  97558. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  97559. * @param color The color of the gizmo
  97560. */
  97561. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  97562. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97563. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97564. var _this = _super.call(this, gizmoLayer) || this;
  97565. _this._pointerObserver = null;
  97566. /**
  97567. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  97568. */
  97569. _this.snapDistance = 0;
  97570. /**
  97571. * Event that fires each time the gizmo snaps to a new location.
  97572. * * snapDistance is the the change in distance
  97573. */
  97574. _this.onSnapObservable = new BABYLON.Observable();
  97575. // Create Material
  97576. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97577. coloredMaterial.disableLighting = true;
  97578. coloredMaterial.emissiveColor = color;
  97579. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97580. hoverMaterial.disableLighting = true;
  97581. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97582. // Build mesh on root node
  97583. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97584. // Create circle out of lines
  97585. var tessellation = 20;
  97586. var radius = 0.8;
  97587. var points = new Array();
  97588. for (var i = 0; i < tessellation; i++) {
  97589. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  97590. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  97591. }
  97592. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  97593. rotationMesh.color = coloredMaterial.emissiveColor;
  97594. // Position arrow pointing in its drag axis
  97595. rotationMesh.scaling.scaleInPlace(0.26);
  97596. rotationMesh.material = coloredMaterial;
  97597. rotationMesh.rotation.x = Math.PI / 2;
  97598. parentMesh.addChild(rotationMesh);
  97599. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  97600. _this._rootMesh.addChild(parentMesh);
  97601. parentMesh.scaling.scaleInPlace(1 / 3);
  97602. // Add drag behavior to handle events when the gizmo is dragged
  97603. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  97604. _this.dragBehavior.moveAttached = false;
  97605. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  97606. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  97607. _this._rootMesh.addBehavior(_this.dragBehavior);
  97608. var lastDragPosition = new BABYLON.Vector3();
  97609. _this.dragBehavior.onDragStartObservable.add(function (e) {
  97610. if (_this.attachedMesh) {
  97611. lastDragPosition.copyFrom(e.dragPlanePoint);
  97612. }
  97613. });
  97614. var rotationMatrix = new BABYLON.Matrix();
  97615. var planeNormalTowardsCamera = new BABYLON.Vector3();
  97616. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  97617. var tmpSnapEvent = { snapDistance: 0 };
  97618. var currentSnapDragDistance = 0;
  97619. var tmpMatrix = new BABYLON.Matrix();
  97620. var tmpVector = new BABYLON.Vector3();
  97621. var amountToRotate = new BABYLON.Quaternion();
  97622. _this.dragBehavior.onDragObservable.add(function (event) {
  97623. if (_this.attachedMesh) {
  97624. if (!_this.attachedMesh.rotationQuaternion) {
  97625. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  97626. }
  97627. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  97628. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  97629. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  97630. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  97631. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  97632. var angle = Math.atan2(cross.length(), dot);
  97633. planeNormalTowardsCamera.copyFrom(planeNormal);
  97634. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  97635. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97636. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  97637. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  97638. }
  97639. // Flip up vector depending on which side the camera is on
  97640. if (gizmoLayer.utilityLayerScene.activeCamera) {
  97641. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  97642. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  97643. planeNormalTowardsCamera.scaleInPlace(-1);
  97644. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  97645. }
  97646. }
  97647. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  97648. if (halfCircleSide)
  97649. angle = -angle;
  97650. // Snapping logic
  97651. var snapped = false;
  97652. if (_this.snapDistance != 0) {
  97653. currentSnapDragDistance += angle;
  97654. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  97655. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  97656. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  97657. angle = _this.snapDistance * dragSteps;
  97658. snapped = true;
  97659. }
  97660. else {
  97661. angle = 0;
  97662. }
  97663. }
  97664. // If the mesh has a parent, convert needed world rotation to local rotation
  97665. tmpMatrix.reset();
  97666. if (_this.attachedMesh.parent) {
  97667. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  97668. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  97669. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  97670. }
  97671. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  97672. var quaternionCoefficient = Math.sin(angle / 2);
  97673. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  97674. // 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
  97675. if (tmpMatrix.determinant() > 0) {
  97676. amountToRotate.toEulerAnglesToRef(tmpVector);
  97677. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  97678. }
  97679. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97680. // Rotate selected mesh quaternion over fixed axis
  97681. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  97682. }
  97683. else {
  97684. // Rotate selected mesh quaternion over rotated axis
  97685. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  97686. }
  97687. lastDragPosition.copyFrom(event.dragPlanePoint);
  97688. if (snapped) {
  97689. tmpSnapEvent.snapDistance = angle;
  97690. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  97691. }
  97692. }
  97693. });
  97694. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97695. if (_this._customMeshSet) {
  97696. return;
  97697. }
  97698. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  97699. var material = isHovered ? hoverMaterial : coloredMaterial;
  97700. _this._rootMesh.getChildMeshes().forEach(function (m) {
  97701. m.material = material;
  97702. if (m.color) {
  97703. m.color = material.emissiveColor;
  97704. }
  97705. });
  97706. });
  97707. return _this;
  97708. }
  97709. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  97710. if (this.dragBehavior) {
  97711. this.dragBehavior.enabled = value ? true : false;
  97712. }
  97713. };
  97714. /**
  97715. * Disposes of the gizmo
  97716. */
  97717. PlaneRotationGizmo.prototype.dispose = function () {
  97718. this.onSnapObservable.clear();
  97719. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97720. this.dragBehavior.detach();
  97721. _super.prototype.dispose.call(this);
  97722. };
  97723. return PlaneRotationGizmo;
  97724. }(BABYLON.Gizmo));
  97725. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  97726. })(BABYLON || (BABYLON = {}));
  97727. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  97728. var BABYLON;
  97729. (function (BABYLON) {
  97730. /**
  97731. * Gizmo that enables dragging a mesh along 3 axis
  97732. */
  97733. var PositionGizmo = /** @class */ (function (_super) {
  97734. __extends(PositionGizmo, _super);
  97735. /**
  97736. * Creates a PositionGizmo
  97737. * @param gizmoLayer The utility layer the gizmo will be added to
  97738. */
  97739. function PositionGizmo(gizmoLayer) {
  97740. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97741. var _this = _super.call(this, gizmoLayer) || this;
  97742. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97743. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97744. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97745. _this.attachedMesh = null;
  97746. return _this;
  97747. }
  97748. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  97749. set: function (mesh) {
  97750. if (this.xGizmo) {
  97751. this.xGizmo.attachedMesh = mesh;
  97752. this.yGizmo.attachedMesh = mesh;
  97753. this.zGizmo.attachedMesh = mesh;
  97754. }
  97755. },
  97756. enumerable: true,
  97757. configurable: true
  97758. });
  97759. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97760. get: function () {
  97761. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97762. },
  97763. set: function (value) {
  97764. if (this.xGizmo) {
  97765. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97766. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97767. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97768. }
  97769. },
  97770. enumerable: true,
  97771. configurable: true
  97772. });
  97773. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  97774. get: function () {
  97775. return this.xGizmo.snapDistance;
  97776. },
  97777. /**
  97778. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97779. */
  97780. set: function (value) {
  97781. if (this.xGizmo) {
  97782. this.xGizmo.snapDistance = value;
  97783. this.yGizmo.snapDistance = value;
  97784. this.zGizmo.snapDistance = value;
  97785. }
  97786. },
  97787. enumerable: true,
  97788. configurable: true
  97789. });
  97790. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  97791. get: function () {
  97792. return this.xGizmo.scaleRatio;
  97793. },
  97794. /**
  97795. * Ratio for the scale of the gizmo (Default: 1)
  97796. */
  97797. set: function (value) {
  97798. if (this.xGizmo) {
  97799. this.xGizmo.scaleRatio = value;
  97800. this.yGizmo.scaleRatio = value;
  97801. this.zGizmo.scaleRatio = value;
  97802. }
  97803. },
  97804. enumerable: true,
  97805. configurable: true
  97806. });
  97807. /**
  97808. * Disposes of the gizmo
  97809. */
  97810. PositionGizmo.prototype.dispose = function () {
  97811. this.xGizmo.dispose();
  97812. this.yGizmo.dispose();
  97813. this.zGizmo.dispose();
  97814. };
  97815. /**
  97816. * CustomMeshes are not supported by this gizmo
  97817. * @param mesh The mesh to replace the default mesh of the gizmo
  97818. */
  97819. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  97820. 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)");
  97821. };
  97822. return PositionGizmo;
  97823. }(BABYLON.Gizmo));
  97824. BABYLON.PositionGizmo = PositionGizmo;
  97825. })(BABYLON || (BABYLON = {}));
  97826. //# sourceMappingURL=babylon.positionGizmo.js.map
  97827. var BABYLON;
  97828. (function (BABYLON) {
  97829. /**
  97830. * Gizmo that enables rotating a mesh along 3 axis
  97831. */
  97832. var RotationGizmo = /** @class */ (function (_super) {
  97833. __extends(RotationGizmo, _super);
  97834. /**
  97835. * Creates a RotationGizmo
  97836. * @param gizmoLayer The utility layer the gizmo will be added to
  97837. */
  97838. function RotationGizmo(gizmoLayer) {
  97839. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97840. var _this = _super.call(this, gizmoLayer) || this;
  97841. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97842. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97843. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97844. _this.attachedMesh = null;
  97845. return _this;
  97846. }
  97847. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  97848. set: function (mesh) {
  97849. if (this.xGizmo) {
  97850. this.xGizmo.attachedMesh = mesh;
  97851. this.yGizmo.attachedMesh = mesh;
  97852. this.zGizmo.attachedMesh = mesh;
  97853. }
  97854. },
  97855. enumerable: true,
  97856. configurable: true
  97857. });
  97858. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97859. get: function () {
  97860. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97861. },
  97862. set: function (value) {
  97863. if (this.xGizmo) {
  97864. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97865. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97866. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97867. }
  97868. },
  97869. enumerable: true,
  97870. configurable: true
  97871. });
  97872. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  97873. get: function () {
  97874. return this.xGizmo.snapDistance;
  97875. },
  97876. /**
  97877. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97878. */
  97879. set: function (value) {
  97880. if (this.xGizmo) {
  97881. this.xGizmo.snapDistance = value;
  97882. this.yGizmo.snapDistance = value;
  97883. this.zGizmo.snapDistance = value;
  97884. }
  97885. },
  97886. enumerable: true,
  97887. configurable: true
  97888. });
  97889. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  97890. get: function () {
  97891. return this.xGizmo.scaleRatio;
  97892. },
  97893. /**
  97894. * Ratio for the scale of the gizmo (Default: 1)
  97895. */
  97896. set: function (value) {
  97897. if (this.xGizmo) {
  97898. this.xGizmo.scaleRatio = value;
  97899. this.yGizmo.scaleRatio = value;
  97900. this.zGizmo.scaleRatio = value;
  97901. }
  97902. },
  97903. enumerable: true,
  97904. configurable: true
  97905. });
  97906. /**
  97907. * Disposes of the gizmo
  97908. */
  97909. RotationGizmo.prototype.dispose = function () {
  97910. this.xGizmo.dispose();
  97911. this.yGizmo.dispose();
  97912. this.zGizmo.dispose();
  97913. };
  97914. /**
  97915. * CustomMeshes are not supported by this gizmo
  97916. * @param mesh The mesh to replace the default mesh of the gizmo
  97917. */
  97918. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  97919. 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)");
  97920. };
  97921. return RotationGizmo;
  97922. }(BABYLON.Gizmo));
  97923. BABYLON.RotationGizmo = RotationGizmo;
  97924. })(BABYLON || (BABYLON = {}));
  97925. //# sourceMappingURL=babylon.rotationGizmo.js.map
  97926. var BABYLON;
  97927. (function (BABYLON) {
  97928. /**
  97929. * Gizmo that enables scaling a mesh along 3 axis
  97930. */
  97931. var ScaleGizmo = /** @class */ (function (_super) {
  97932. __extends(ScaleGizmo, _super);
  97933. /**
  97934. * Creates a ScaleGizmo
  97935. * @param gizmoLayer The utility layer the gizmo will be added to
  97936. */
  97937. function ScaleGizmo(gizmoLayer) {
  97938. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97939. var _this = _super.call(this, gizmoLayer) || this;
  97940. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97941. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97942. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97943. // Create uniform scale gizmo
  97944. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  97945. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97946. _this.uniformScaleGizmo.uniformScaling = true;
  97947. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  97948. octahedron.scaling.scaleInPlace(0.007);
  97949. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  97950. _this.attachedMesh = null;
  97951. return _this;
  97952. }
  97953. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  97954. set: function (mesh) {
  97955. if (this.xGizmo) {
  97956. this.xGizmo.attachedMesh = mesh;
  97957. this.yGizmo.attachedMesh = mesh;
  97958. this.zGizmo.attachedMesh = mesh;
  97959. this.uniformScaleGizmo.attachedMesh = mesh;
  97960. }
  97961. },
  97962. enumerable: true,
  97963. configurable: true
  97964. });
  97965. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97966. get: function () {
  97967. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97968. },
  97969. set: function (value) {
  97970. if (this.xGizmo) {
  97971. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97972. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97973. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97974. }
  97975. },
  97976. enumerable: true,
  97977. configurable: true
  97978. });
  97979. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  97980. get: function () {
  97981. return this.xGizmo.snapDistance;
  97982. },
  97983. /**
  97984. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97985. */
  97986. set: function (value) {
  97987. if (this.xGizmo) {
  97988. this.xGizmo.snapDistance = value;
  97989. this.yGizmo.snapDistance = value;
  97990. this.zGizmo.snapDistance = value;
  97991. this.uniformScaleGizmo.snapDistance = value;
  97992. }
  97993. },
  97994. enumerable: true,
  97995. configurable: true
  97996. });
  97997. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  97998. get: function () {
  97999. return this.xGizmo.scaleRatio;
  98000. },
  98001. /**
  98002. * Ratio for the scale of the gizmo (Default: 1)
  98003. */
  98004. set: function (value) {
  98005. if (this.xGizmo) {
  98006. this.xGizmo.scaleRatio = value;
  98007. this.yGizmo.scaleRatio = value;
  98008. this.zGizmo.scaleRatio = value;
  98009. this.uniformScaleGizmo.scaleRatio = value;
  98010. }
  98011. },
  98012. enumerable: true,
  98013. configurable: true
  98014. });
  98015. /**
  98016. * Disposes of the gizmo
  98017. */
  98018. ScaleGizmo.prototype.dispose = function () {
  98019. this.xGizmo.dispose();
  98020. this.yGizmo.dispose();
  98021. this.zGizmo.dispose();
  98022. this.uniformScaleGizmo.dispose();
  98023. };
  98024. return ScaleGizmo;
  98025. }(BABYLON.Gizmo));
  98026. BABYLON.ScaleGizmo = ScaleGizmo;
  98027. })(BABYLON || (BABYLON = {}));
  98028. //# sourceMappingURL=babylon.scaleGizmo.js.map
  98029. var BABYLON;
  98030. (function (BABYLON) {
  98031. /**
  98032. * Bounding box gizmo
  98033. */
  98034. var BoundingBoxGizmo = /** @class */ (function (_super) {
  98035. __extends(BoundingBoxGizmo, _super);
  98036. /**
  98037. * Creates an BoundingBoxGizmo
  98038. * @param gizmoLayer The utility layer the gizmo will be added to
  98039. * @param color The color of the gizmo
  98040. */
  98041. function BoundingBoxGizmo(color, gizmoLayer) {
  98042. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98043. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  98044. var _this = _super.call(this, gizmoLayer) || this;
  98045. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  98046. _this._renderObserver = null;
  98047. _this._pointerObserver = null;
  98048. _this._scaleDragSpeed = 0.2;
  98049. _this._tmpQuaternion = new BABYLON.Quaternion();
  98050. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  98051. _this._tmpRotationMatrix = new BABYLON.Matrix();
  98052. /**
  98053. * 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)
  98054. */
  98055. _this.ignoreChildren = false;
  98056. /**
  98057. * 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)
  98058. */
  98059. _this.includeChildPredicate = null;
  98060. /**
  98061. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  98062. */
  98063. _this.rotationSphereSize = 0.1;
  98064. /**
  98065. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  98066. */
  98067. _this.scaleBoxSize = 0.1;
  98068. /**
  98069. * 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)
  98070. */
  98071. _this.fixedDragMeshScreenSize = false;
  98072. /**
  98073. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  98074. */
  98075. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  98076. /**
  98077. * Fired when a rotation sphere or scale box is dragged
  98078. */
  98079. _this.onDragStartObservable = new BABYLON.Observable();
  98080. /**
  98081. * Fired when a scale box is dragged
  98082. */
  98083. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  98084. /**
  98085. * Fired when a scale box drag is ended
  98086. */
  98087. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  98088. /**
  98089. * Fired when a rotation sphere is dragged
  98090. */
  98091. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  98092. /**
  98093. * Fired when a rotation sphere drag is ended
  98094. */
  98095. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  98096. /**
  98097. * 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)
  98098. */
  98099. _this.scalePivot = null;
  98100. _this._existingMeshScale = new BABYLON.Vector3();
  98101. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  98102. _this._updateScale = false;
  98103. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  98104. // Create Materials
  98105. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98106. coloredMaterial.disableLighting = true;
  98107. coloredMaterial.emissiveColor = color;
  98108. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98109. hoverColoredMaterial.disableLighting = true;
  98110. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98111. // Build bounding box out of lines
  98112. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98113. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  98114. var lines = [];
  98115. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  98116. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  98117. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  98118. 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));
  98119. 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));
  98120. 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));
  98121. 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));
  98122. 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));
  98123. 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));
  98124. 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));
  98125. 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));
  98126. 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));
  98127. lines.forEach(function (l) {
  98128. l.color = color;
  98129. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  98130. l.isPickable = false;
  98131. _this._lineBoundingBox.addChild(l);
  98132. });
  98133. _this._rootMesh.addChild(_this._lineBoundingBox);
  98134. // Create rotation spheres
  98135. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98136. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  98137. var _loop_1 = function (i_1) {
  98138. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  98139. sphere.rotationQuaternion = new BABYLON.Quaternion();
  98140. sphere.material = coloredMaterial;
  98141. // Drag behavior
  98142. _dragBehavior = new BABYLON.PointerDragBehavior({});
  98143. _dragBehavior.moveAttached = false;
  98144. _dragBehavior.updateDragPlane = false;
  98145. sphere.addBehavior(_dragBehavior);
  98146. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  98147. var totalTurnAmountOfDrag = 0;
  98148. _dragBehavior.onDragStartObservable.add(function (event) {
  98149. startingTurnDirection.copyFrom(sphere.forward);
  98150. totalTurnAmountOfDrag = 0;
  98151. });
  98152. _dragBehavior.onDragObservable.add(function (event) {
  98153. _this.onRotationSphereDragObservable.notifyObservers({});
  98154. if (_this.attachedMesh) {
  98155. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  98156. var worldDragDirection = startingTurnDirection;
  98157. // Project the world right on to the drag plane
  98158. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  98159. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  98160. // project drag delta on to the resulting drag axis and rotate based on that
  98161. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  98162. // Make rotation relative to size of mesh.
  98163. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  98164. // Rotate based on axis
  98165. if (!_this.attachedMesh.rotationQuaternion) {
  98166. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  98167. }
  98168. if (!_this._anchorMesh.rotationQuaternion) {
  98169. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  98170. }
  98171. // Do not allow the object to turn more than a full circle
  98172. totalTurnAmountOfDrag += projectDist;
  98173. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  98174. if (i_1 >= 8) {
  98175. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  98176. }
  98177. else if (i_1 >= 4) {
  98178. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  98179. }
  98180. else {
  98181. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  98182. }
  98183. // Rotate around center of bounding box
  98184. _this._anchorMesh.addChild(_this.attachedMesh);
  98185. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  98186. _this._anchorMesh.removeChild(_this.attachedMesh);
  98187. }
  98188. _this.updateBoundingBox();
  98189. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  98190. }
  98191. });
  98192. // Selection/deselection
  98193. _dragBehavior.onDragStartObservable.add(function () {
  98194. _this.onDragStartObservable.notifyObservers({});
  98195. _this._selectNode(sphere);
  98196. });
  98197. _dragBehavior.onDragEndObservable.add(function () {
  98198. _this.onRotationSphereDragEndObservable.notifyObservers({});
  98199. _this._selectNode(null);
  98200. });
  98201. this_1._rotateSpheresParent.addChild(sphere);
  98202. };
  98203. var this_1 = this, _dragBehavior;
  98204. for (var i_1 = 0; i_1 < 12; i_1++) {
  98205. _loop_1(i_1);
  98206. }
  98207. _this._rootMesh.addChild(_this._rotateSpheresParent);
  98208. // Create scale cubes
  98209. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98210. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  98211. for (var i = 0; i < 2; i++) {
  98212. for (var j = 0; j < 2; j++) {
  98213. var _loop_2 = function () {
  98214. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  98215. box.material = coloredMaterial;
  98216. // Dragging logic
  98217. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  98218. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98219. _dragBehavior.moveAttached = false;
  98220. box.addBehavior(_dragBehavior);
  98221. _dragBehavior.onDragObservable.add(function (event) {
  98222. _this.onScaleBoxDragObservable.notifyObservers({});
  98223. if (_this.attachedMesh) {
  98224. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  98225. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  98226. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  98227. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  98228. _this.updateBoundingBox();
  98229. if (_this.scalePivot) {
  98230. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  98231. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  98232. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  98233. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  98234. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  98235. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  98236. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  98237. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  98238. }
  98239. else {
  98240. // Scale from the position of the opposite corner
  98241. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  98242. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  98243. }
  98244. _this._anchorMesh.addChild(_this.attachedMesh);
  98245. _this._anchorMesh.scaling.addInPlace(deltaScale);
  98246. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  98247. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  98248. }
  98249. _this._anchorMesh.removeChild(_this.attachedMesh);
  98250. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  98251. }
  98252. });
  98253. // Selection/deselection
  98254. _dragBehavior.onDragStartObservable.add(function () {
  98255. _this.onDragStartObservable.notifyObservers({});
  98256. _this._selectNode(box);
  98257. });
  98258. _dragBehavior.onDragEndObservable.add(function () {
  98259. _this.onScaleBoxDragEndObservable.notifyObservers({});
  98260. _this._selectNode(null);
  98261. });
  98262. this_2._scaleBoxesParent.addChild(box);
  98263. };
  98264. var this_2 = this, _dragBehavior;
  98265. for (var k = 0; k < 2; k++) {
  98266. _loop_2();
  98267. }
  98268. }
  98269. }
  98270. _this._rootMesh.addChild(_this._scaleBoxesParent);
  98271. // Hover color change
  98272. var pointerIds = new Array();
  98273. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98274. if (!pointerIds[pointerInfo.event.pointerId]) {
  98275. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  98276. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  98277. pointerIds[pointerInfo.event.pointerId] = mesh;
  98278. mesh.material = hoverColoredMaterial;
  98279. }
  98280. });
  98281. }
  98282. else {
  98283. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  98284. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  98285. delete pointerIds[pointerInfo.event.pointerId];
  98286. }
  98287. }
  98288. });
  98289. // Update bounding box positions
  98290. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  98291. // Only update the bouding box if scaling has changed
  98292. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  98293. _this.updateBoundingBox();
  98294. }
  98295. });
  98296. _this.updateBoundingBox();
  98297. return _this;
  98298. }
  98299. /** @hidden */
  98300. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  98301. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  98302. // Save old pivot and set pivot to 0,0,0
  98303. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  98304. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  98305. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  98306. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  98307. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  98308. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  98309. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  98310. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  98311. }
  98312. }
  98313. BoundingBoxGizmo._PivotCached++;
  98314. };
  98315. /** @hidden */
  98316. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  98317. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  98318. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  98319. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  98320. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  98321. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  98322. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  98323. }
  98324. this._PivotCached--;
  98325. };
  98326. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  98327. if (value) {
  98328. // Reset anchor mesh to match attached mesh's scale
  98329. // This is needed to avoid invalid box/sphere position on first drag
  98330. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  98331. this._anchorMesh.addChild(value);
  98332. this._anchorMesh.removeChild(value);
  98333. BoundingBoxGizmo._RestorePivotPoint(value);
  98334. this.updateBoundingBox();
  98335. }
  98336. };
  98337. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  98338. this._rotateSpheresParent.getChildMeshes()
  98339. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  98340. m.isVisible = (!selectedMesh || m == selectedMesh);
  98341. });
  98342. };
  98343. /**
  98344. * Updates the bounding box information for the Gizmo
  98345. */
  98346. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  98347. if (this.attachedMesh) {
  98348. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  98349. this._update();
  98350. // Rotate based on axis
  98351. if (!this.attachedMesh.rotationQuaternion) {
  98352. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  98353. }
  98354. if (!this._anchorMesh.rotationQuaternion) {
  98355. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  98356. }
  98357. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  98358. // Store original position and reset mesh to origin before computing the bounding box
  98359. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  98360. this._tmpVector.copyFrom(this.attachedMesh.position);
  98361. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  98362. this.attachedMesh.position.set(0, 0, 0);
  98363. // Update bounding dimensions/positions
  98364. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  98365. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  98366. // Update gizmo to match bounding box scaling and rotation
  98367. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  98368. 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);
  98369. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  98370. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  98371. this._lineBoundingBox.computeWorldMatrix();
  98372. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  98373. // restore position/rotation values
  98374. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  98375. this.attachedMesh.position.copyFrom(this._tmpVector);
  98376. }
  98377. // Update rotation sphere locations
  98378. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  98379. for (var i = 0; i < 3; i++) {
  98380. for (var j = 0; j < 2; j++) {
  98381. for (var k = 0; k < 2; k++) {
  98382. var index = ((i * 4) + (j * 2)) + k;
  98383. if (i == 0) {
  98384. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  98385. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  98386. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  98387. }
  98388. if (i == 1) {
  98389. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  98390. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  98391. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  98392. }
  98393. if (i == 2) {
  98394. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  98395. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  98396. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  98397. }
  98398. if (this.fixedDragMeshScreenSize) {
  98399. this._rootMesh.computeWorldMatrix();
  98400. this._rotateSpheresParent.computeWorldMatrix();
  98401. rotateSpheres[index].computeWorldMatrix();
  98402. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  98403. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  98404. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  98405. }
  98406. else {
  98407. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  98408. }
  98409. }
  98410. }
  98411. }
  98412. // Update scale box locations
  98413. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  98414. for (var i = 0; i < 2; i++) {
  98415. for (var j = 0; j < 2; j++) {
  98416. for (var k = 0; k < 2; k++) {
  98417. var index = ((i * 4) + (j * 2)) + k;
  98418. if (scaleBoxes[index]) {
  98419. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  98420. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  98421. if (this.fixedDragMeshScreenSize) {
  98422. this._rootMesh.computeWorldMatrix();
  98423. this._scaleBoxesParent.computeWorldMatrix();
  98424. scaleBoxes[index].computeWorldMatrix();
  98425. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  98426. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  98427. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  98428. }
  98429. else {
  98430. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  98431. }
  98432. }
  98433. }
  98434. }
  98435. }
  98436. if (this.attachedMesh) {
  98437. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  98438. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  98439. }
  98440. };
  98441. /**
  98442. * Enables rotation on the specified axis and disables rotation on the others
  98443. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  98444. */
  98445. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  98446. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  98447. if (i < 4) {
  98448. m.setEnabled(axis.indexOf("x") != -1);
  98449. }
  98450. else if (i < 8) {
  98451. m.setEnabled(axis.indexOf("y") != -1);
  98452. }
  98453. else {
  98454. m.setEnabled(axis.indexOf("z") != -1);
  98455. }
  98456. });
  98457. };
  98458. /**
  98459. * Disposes of the gizmo
  98460. */
  98461. BoundingBoxGizmo.prototype.dispose = function () {
  98462. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98463. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  98464. this._lineBoundingBox.dispose();
  98465. this._rotateSpheresParent.dispose();
  98466. this._scaleBoxesParent.dispose();
  98467. _super.prototype.dispose.call(this);
  98468. };
  98469. /**
  98470. * 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)
  98471. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  98472. * @returns the bounding box mesh with the passed in mesh as a child
  98473. */
  98474. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  98475. var makeNotPickable = function (root) {
  98476. root.isPickable = false;
  98477. root.getChildMeshes().forEach(function (c) {
  98478. makeNotPickable(c);
  98479. });
  98480. };
  98481. makeNotPickable(mesh);
  98482. // Reset position to get boudning box from origin with no rotation
  98483. if (!mesh.rotationQuaternion) {
  98484. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  98485. }
  98486. var oldPos = mesh.position.clone();
  98487. var oldRot = mesh.rotationQuaternion.clone();
  98488. mesh.rotationQuaternion.set(0, 0, 0, 1);
  98489. mesh.position.set(0, 0, 0);
  98490. // Update bounding dimensions/positions
  98491. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  98492. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  98493. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  98494. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  98495. // Restore original positions
  98496. mesh.addChild(box);
  98497. mesh.rotationQuaternion.copyFrom(oldRot);
  98498. mesh.position.copyFrom(oldPos);
  98499. // Reverse parenting
  98500. mesh.removeChild(box);
  98501. box.addChild(mesh);
  98502. box.visibility = 0;
  98503. return box;
  98504. };
  98505. /**
  98506. * CustomMeshes are not supported by this gizmo
  98507. * @param mesh The mesh to replace the default mesh of the gizmo
  98508. */
  98509. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  98510. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  98511. };
  98512. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  98513. // store/remove pivot point should only be applied during their outermost calls
  98514. BoundingBoxGizmo._PivotCached = 0;
  98515. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  98516. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  98517. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  98518. return BoundingBoxGizmo;
  98519. }(BABYLON.Gizmo));
  98520. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  98521. })(BABYLON || (BABYLON = {}));
  98522. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  98523. var BABYLON;
  98524. (function (BABYLON) {
  98525. /**
  98526. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  98527. */
  98528. var GizmoManager = /** @class */ (function () {
  98529. /**
  98530. * Instatiates a gizmo manager
  98531. * @param scene the scene to overlay the gizmos on top of
  98532. */
  98533. function GizmoManager(scene) {
  98534. var _this = this;
  98535. this.scene = scene;
  98536. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  98537. this._pointerObserver = null;
  98538. this._attachedMesh = null;
  98539. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  98540. /**
  98541. * When bounding box gizmo is enabled, this can be used to track drag/end events
  98542. */
  98543. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  98544. /**
  98545. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  98546. */
  98547. this.attachableMeshes = null;
  98548. /**
  98549. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  98550. */
  98551. this.usePointerToAttachGizmos = true;
  98552. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  98553. // Instatiate/dispose gizmos based on pointer actions
  98554. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  98555. if (!_this.usePointerToAttachGizmos) {
  98556. return;
  98557. }
  98558. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  98559. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  98560. var node = pointerInfo.pickInfo.pickedMesh;
  98561. if (_this.attachableMeshes == null) {
  98562. // Attach to the most parent node
  98563. while (node && node.parent != null) {
  98564. node = node.parent;
  98565. }
  98566. }
  98567. else {
  98568. // Attach to the parent node that is an attachableMesh
  98569. var found = false;
  98570. _this.attachableMeshes.forEach(function (mesh) {
  98571. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  98572. node = mesh;
  98573. found = true;
  98574. }
  98575. });
  98576. if (!found) {
  98577. node = null;
  98578. }
  98579. }
  98580. if (node instanceof BABYLON.AbstractMesh) {
  98581. _this.attachToMesh(node);
  98582. }
  98583. else {
  98584. _this.attachToMesh(null);
  98585. }
  98586. }
  98587. else {
  98588. _this.attachToMesh(null);
  98589. }
  98590. }
  98591. });
  98592. }
  98593. /**
  98594. * Attaches a set of gizmos to the specified mesh
  98595. * @param mesh The mesh the gizmo's should be attached to
  98596. */
  98597. GizmoManager.prototype.attachToMesh = function (mesh) {
  98598. if (this._attachedMesh) {
  98599. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98600. }
  98601. this._attachedMesh = mesh;
  98602. for (var key in this.gizmos) {
  98603. var gizmo = (this.gizmos[key]);
  98604. if (gizmo && this._gizmosEnabled[key]) {
  98605. gizmo.attachedMesh = mesh;
  98606. }
  98607. }
  98608. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  98609. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98610. }
  98611. };
  98612. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  98613. get: function () {
  98614. return this._gizmosEnabled.positionGizmo;
  98615. },
  98616. /**
  98617. * If the position gizmo is enabled
  98618. */
  98619. set: function (value) {
  98620. if (value) {
  98621. if (!this.gizmos.positionGizmo) {
  98622. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  98623. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98624. }
  98625. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  98626. }
  98627. else if (this.gizmos.positionGizmo) {
  98628. this.gizmos.positionGizmo.attachedMesh = null;
  98629. }
  98630. this._gizmosEnabled.positionGizmo = value;
  98631. },
  98632. enumerable: true,
  98633. configurable: true
  98634. });
  98635. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  98636. get: function () {
  98637. return this._gizmosEnabled.rotationGizmo;
  98638. },
  98639. /**
  98640. * If the rotation gizmo is enabled
  98641. */
  98642. set: function (value) {
  98643. if (value) {
  98644. if (!this.gizmos.rotationGizmo) {
  98645. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  98646. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98647. }
  98648. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  98649. }
  98650. else if (this.gizmos.rotationGizmo) {
  98651. this.gizmos.rotationGizmo.attachedMesh = null;
  98652. }
  98653. this._gizmosEnabled.rotationGizmo = value;
  98654. },
  98655. enumerable: true,
  98656. configurable: true
  98657. });
  98658. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  98659. get: function () {
  98660. return this._gizmosEnabled.scaleGizmo;
  98661. },
  98662. /**
  98663. * If the scale gizmo is enabled
  98664. */
  98665. set: function (value) {
  98666. if (value) {
  98667. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  98668. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  98669. }
  98670. else if (this.gizmos.scaleGizmo) {
  98671. this.gizmos.scaleGizmo.attachedMesh = null;
  98672. }
  98673. this._gizmosEnabled.scaleGizmo = value;
  98674. },
  98675. enumerable: true,
  98676. configurable: true
  98677. });
  98678. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  98679. get: function () {
  98680. return this._gizmosEnabled.boundingBoxGizmo;
  98681. },
  98682. /**
  98683. * If the boundingBox gizmo is enabled
  98684. */
  98685. set: function (value) {
  98686. if (value) {
  98687. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  98688. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  98689. if (this._attachedMesh) {
  98690. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98691. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98692. }
  98693. }
  98694. else if (this.gizmos.boundingBoxGizmo) {
  98695. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  98696. }
  98697. this._gizmosEnabled.boundingBoxGizmo = value;
  98698. },
  98699. enumerable: true,
  98700. configurable: true
  98701. });
  98702. /**
  98703. * Disposes of the gizmo manager
  98704. */
  98705. GizmoManager.prototype.dispose = function () {
  98706. this.scene.onPointerObservable.remove(this._pointerObserver);
  98707. for (var key in this.gizmos) {
  98708. var gizmo = (this.gizmos[key]);
  98709. if (gizmo) {
  98710. gizmo.dispose();
  98711. }
  98712. }
  98713. this.boundingBoxDragBehavior.detach();
  98714. };
  98715. return GizmoManager;
  98716. }());
  98717. BABYLON.GizmoManager = GizmoManager;
  98718. })(BABYLON || (BABYLON = {}));
  98719. //# sourceMappingURL=babylon.gizmoManager.js.map
  98720. var BABYLON;
  98721. (function (BABYLON) {
  98722. /**
  98723. * Defines a target to use with MorphTargetManager
  98724. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98725. */
  98726. var MorphTarget = /** @class */ (function () {
  98727. /**
  98728. * Creates a new MorphTarget
  98729. * @param name defines the name of the target
  98730. * @param influence defines the influence to use
  98731. */
  98732. function MorphTarget(
  98733. /** defines the name of the target */
  98734. name, influence, scene) {
  98735. if (influence === void 0) { influence = 0; }
  98736. if (scene === void 0) { scene = null; }
  98737. this.name = name;
  98738. /**
  98739. * Gets or sets the list of animations
  98740. */
  98741. this.animations = new Array();
  98742. this._positions = null;
  98743. this._normals = null;
  98744. this._tangents = null;
  98745. /**
  98746. * Observable raised when the influence changes
  98747. */
  98748. this.onInfluenceChanged = new BABYLON.Observable();
  98749. this._animationPropertiesOverride = null;
  98750. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98751. this.influence = influence;
  98752. }
  98753. Object.defineProperty(MorphTarget.prototype, "influence", {
  98754. /**
  98755. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  98756. */
  98757. get: function () {
  98758. return this._influence;
  98759. },
  98760. set: function (influence) {
  98761. if (this._influence === influence) {
  98762. return;
  98763. }
  98764. var previous = this._influence;
  98765. this._influence = influence;
  98766. if (this.onInfluenceChanged.hasObservers) {
  98767. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  98768. }
  98769. },
  98770. enumerable: true,
  98771. configurable: true
  98772. });
  98773. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  98774. /**
  98775. * Gets or sets the animation properties override
  98776. */
  98777. get: function () {
  98778. if (!this._animationPropertiesOverride && this._scene) {
  98779. return this._scene.animationPropertiesOverride;
  98780. }
  98781. return this._animationPropertiesOverride;
  98782. },
  98783. set: function (value) {
  98784. this._animationPropertiesOverride = value;
  98785. },
  98786. enumerable: true,
  98787. configurable: true
  98788. });
  98789. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  98790. /**
  98791. * Gets a boolean defining if the target contains position data
  98792. */
  98793. get: function () {
  98794. return !!this._positions;
  98795. },
  98796. enumerable: true,
  98797. configurable: true
  98798. });
  98799. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  98800. /**
  98801. * Gets a boolean defining if the target contains normal data
  98802. */
  98803. get: function () {
  98804. return !!this._normals;
  98805. },
  98806. enumerable: true,
  98807. configurable: true
  98808. });
  98809. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  98810. /**
  98811. * Gets a boolean defining if the target contains tangent data
  98812. */
  98813. get: function () {
  98814. return !!this._tangents;
  98815. },
  98816. enumerable: true,
  98817. configurable: true
  98818. });
  98819. /**
  98820. * Affects position data to this target
  98821. * @param data defines the position data to use
  98822. */
  98823. MorphTarget.prototype.setPositions = function (data) {
  98824. this._positions = data;
  98825. };
  98826. /**
  98827. * Gets the position data stored in this target
  98828. * @returns a FloatArray containing the position data (or null if not present)
  98829. */
  98830. MorphTarget.prototype.getPositions = function () {
  98831. return this._positions;
  98832. };
  98833. /**
  98834. * Affects normal data to this target
  98835. * @param data defines the normal data to use
  98836. */
  98837. MorphTarget.prototype.setNormals = function (data) {
  98838. this._normals = data;
  98839. };
  98840. /**
  98841. * Gets the normal data stored in this target
  98842. * @returns a FloatArray containing the normal data (or null if not present)
  98843. */
  98844. MorphTarget.prototype.getNormals = function () {
  98845. return this._normals;
  98846. };
  98847. /**
  98848. * Affects tangent data to this target
  98849. * @param data defines the tangent data to use
  98850. */
  98851. MorphTarget.prototype.setTangents = function (data) {
  98852. this._tangents = data;
  98853. };
  98854. /**
  98855. * Gets the tangent data stored in this target
  98856. * @returns a FloatArray containing the tangent data (or null if not present)
  98857. */
  98858. MorphTarget.prototype.getTangents = function () {
  98859. return this._tangents;
  98860. };
  98861. /**
  98862. * Serializes the current target into a Serialization object
  98863. * @returns the serialized object
  98864. */
  98865. MorphTarget.prototype.serialize = function () {
  98866. var serializationObject = {};
  98867. serializationObject.name = this.name;
  98868. serializationObject.influence = this.influence;
  98869. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  98870. if (this.hasNormals) {
  98871. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  98872. }
  98873. if (this.hasTangents) {
  98874. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  98875. }
  98876. // Animations
  98877. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  98878. return serializationObject;
  98879. };
  98880. // Statics
  98881. /**
  98882. * Creates a new target from serialized data
  98883. * @param serializationObject defines the serialized data to use
  98884. * @returns a new MorphTarget
  98885. */
  98886. MorphTarget.Parse = function (serializationObject) {
  98887. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  98888. result.setPositions(serializationObject.positions);
  98889. if (serializationObject.normals) {
  98890. result.setNormals(serializationObject.normals);
  98891. }
  98892. if (serializationObject.tangents) {
  98893. result.setTangents(serializationObject.tangents);
  98894. }
  98895. // Animations
  98896. if (serializationObject.animations) {
  98897. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  98898. var parsedAnimation = serializationObject.animations[animationIndex];
  98899. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  98900. }
  98901. }
  98902. return result;
  98903. };
  98904. /**
  98905. * Creates a MorphTarget from mesh data
  98906. * @param mesh defines the source mesh
  98907. * @param name defines the name to use for the new target
  98908. * @param influence defines the influence to attach to the target
  98909. * @returns a new MorphTarget
  98910. */
  98911. MorphTarget.FromMesh = function (mesh, name, influence) {
  98912. if (!name) {
  98913. name = mesh.name;
  98914. }
  98915. var result = new MorphTarget(name, influence, mesh.getScene());
  98916. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  98917. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98918. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  98919. }
  98920. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  98921. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  98922. }
  98923. return result;
  98924. };
  98925. return MorphTarget;
  98926. }());
  98927. BABYLON.MorphTarget = MorphTarget;
  98928. })(BABYLON || (BABYLON = {}));
  98929. //# sourceMappingURL=babylon.morphTarget.js.map
  98930. var BABYLON;
  98931. (function (BABYLON) {
  98932. /**
  98933. * This class is used to deform meshes using morphing between different targets
  98934. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98935. */
  98936. var MorphTargetManager = /** @class */ (function () {
  98937. /**
  98938. * Creates a new MorphTargetManager
  98939. * @param scene defines the current scene
  98940. */
  98941. function MorphTargetManager(scene) {
  98942. if (scene === void 0) { scene = null; }
  98943. this._targets = new Array();
  98944. this._targetObservable = new Array();
  98945. this._activeTargets = new BABYLON.SmartArray(16);
  98946. this._supportsNormals = false;
  98947. this._supportsTangents = false;
  98948. this._vertexCount = 0;
  98949. this._uniqueId = 0;
  98950. this._tempInfluences = new Array();
  98951. if (!scene) {
  98952. scene = BABYLON.Engine.LastCreatedScene;
  98953. }
  98954. this._scene = scene;
  98955. if (this._scene) {
  98956. this._scene.morphTargetManagers.push(this);
  98957. this._uniqueId = this._scene.getUniqueId();
  98958. }
  98959. }
  98960. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  98961. /**
  98962. * Gets the unique ID of this manager
  98963. */
  98964. get: function () {
  98965. return this._uniqueId;
  98966. },
  98967. enumerable: true,
  98968. configurable: true
  98969. });
  98970. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  98971. /**
  98972. * Gets the number of vertices handled by this manager
  98973. */
  98974. get: function () {
  98975. return this._vertexCount;
  98976. },
  98977. enumerable: true,
  98978. configurable: true
  98979. });
  98980. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  98981. /**
  98982. * Gets a boolean indicating if this manager supports morphing of normals
  98983. */
  98984. get: function () {
  98985. return this._supportsNormals;
  98986. },
  98987. enumerable: true,
  98988. configurable: true
  98989. });
  98990. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  98991. /**
  98992. * Gets a boolean indicating if this manager supports morphing of tangents
  98993. */
  98994. get: function () {
  98995. return this._supportsTangents;
  98996. },
  98997. enumerable: true,
  98998. configurable: true
  98999. });
  99000. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  99001. /**
  99002. * Gets the number of targets stored in this manager
  99003. */
  99004. get: function () {
  99005. return this._targets.length;
  99006. },
  99007. enumerable: true,
  99008. configurable: true
  99009. });
  99010. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  99011. /**
  99012. * Gets the number of influencers (ie. the number of targets with influences > 0)
  99013. */
  99014. get: function () {
  99015. return this._activeTargets.length;
  99016. },
  99017. enumerable: true,
  99018. configurable: true
  99019. });
  99020. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  99021. /**
  99022. * Gets the list of influences (one per target)
  99023. */
  99024. get: function () {
  99025. return this._influences;
  99026. },
  99027. enumerable: true,
  99028. configurable: true
  99029. });
  99030. /**
  99031. * Gets the active target at specified index. An active target is a target with an influence > 0
  99032. * @param index defines the index to check
  99033. * @returns the requested target
  99034. */
  99035. MorphTargetManager.prototype.getActiveTarget = function (index) {
  99036. return this._activeTargets.data[index];
  99037. };
  99038. /**
  99039. * Gets the target at specified index
  99040. * @param index defines the index to check
  99041. * @returns the requested target
  99042. */
  99043. MorphTargetManager.prototype.getTarget = function (index) {
  99044. return this._targets[index];
  99045. };
  99046. /**
  99047. * Add a new target to this manager
  99048. * @param target defines the target to add
  99049. */
  99050. MorphTargetManager.prototype.addTarget = function (target) {
  99051. var _this = this;
  99052. this._targets.push(target);
  99053. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  99054. _this._syncActiveTargets(needUpdate);
  99055. }));
  99056. this._syncActiveTargets(true);
  99057. };
  99058. /**
  99059. * Removes a target from the manager
  99060. * @param target defines the target to remove
  99061. */
  99062. MorphTargetManager.prototype.removeTarget = function (target) {
  99063. var index = this._targets.indexOf(target);
  99064. if (index >= 0) {
  99065. this._targets.splice(index, 1);
  99066. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  99067. this._syncActiveTargets(true);
  99068. }
  99069. };
  99070. /**
  99071. * Serializes the current manager into a Serialization object
  99072. * @returns the serialized object
  99073. */
  99074. MorphTargetManager.prototype.serialize = function () {
  99075. var serializationObject = {};
  99076. serializationObject.id = this.uniqueId;
  99077. serializationObject.targets = [];
  99078. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  99079. var target = _a[_i];
  99080. serializationObject.targets.push(target.serialize());
  99081. }
  99082. return serializationObject;
  99083. };
  99084. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  99085. var influenceCount = 0;
  99086. this._activeTargets.reset();
  99087. this._supportsNormals = true;
  99088. this._supportsTangents = true;
  99089. this._vertexCount = 0;
  99090. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  99091. var target = _a[_i];
  99092. this._activeTargets.push(target);
  99093. this._tempInfluences[influenceCount++] = target.influence;
  99094. var positions = target.getPositions();
  99095. if (positions) {
  99096. this._supportsNormals = this._supportsNormals && target.hasNormals;
  99097. this._supportsTangents = this._supportsTangents && target.hasTangents;
  99098. var vertexCount = positions.length / 3;
  99099. if (this._vertexCount === 0) {
  99100. this._vertexCount = vertexCount;
  99101. }
  99102. else if (this._vertexCount !== vertexCount) {
  99103. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  99104. return;
  99105. }
  99106. }
  99107. }
  99108. if (!this._influences || this._influences.length !== influenceCount) {
  99109. this._influences = new Float32Array(influenceCount);
  99110. }
  99111. for (var index = 0; index < influenceCount; index++) {
  99112. this._influences[index] = this._tempInfluences[index];
  99113. }
  99114. if (needUpdate) {
  99115. this.synchronize();
  99116. }
  99117. };
  99118. /**
  99119. * Syncrhonize the targets with all the meshes using this morph target manager
  99120. */
  99121. MorphTargetManager.prototype.synchronize = function () {
  99122. if (!this._scene) {
  99123. return;
  99124. }
  99125. // Flag meshes as dirty to resync with the active targets
  99126. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  99127. var mesh = _a[_i];
  99128. if (mesh.morphTargetManager === this) {
  99129. mesh._syncGeometryWithMorphTargetManager();
  99130. }
  99131. }
  99132. };
  99133. // Statics
  99134. /**
  99135. * Creates a new MorphTargetManager from serialized data
  99136. * @param serializationObject defines the serialized data
  99137. * @param scene defines the hosting scene
  99138. * @returns the new MorphTargetManager
  99139. */
  99140. MorphTargetManager.Parse = function (serializationObject, scene) {
  99141. var result = new MorphTargetManager(scene);
  99142. result._uniqueId = serializationObject.id;
  99143. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  99144. var targetData = _a[_i];
  99145. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  99146. }
  99147. return result;
  99148. };
  99149. return MorphTargetManager;
  99150. }());
  99151. BABYLON.MorphTargetManager = MorphTargetManager;
  99152. })(BABYLON || (BABYLON = {}));
  99153. //# sourceMappingURL=babylon.morphTargetManager.js.map
  99154. var BABYLON;
  99155. (function (BABYLON) {
  99156. var Octree = /** @class */ (function () {
  99157. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  99158. if (maxDepth === void 0) { maxDepth = 2; }
  99159. this.maxDepth = maxDepth;
  99160. this.dynamicContent = new Array();
  99161. this._maxBlockCapacity = maxBlockCapacity || 64;
  99162. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  99163. this._creationFunc = creationFunc;
  99164. }
  99165. // Methods
  99166. Octree.prototype.update = function (worldMin, worldMax, entries) {
  99167. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  99168. };
  99169. Octree.prototype.addMesh = function (entry) {
  99170. for (var index = 0; index < this.blocks.length; index++) {
  99171. var block = this.blocks[index];
  99172. block.addEntry(entry);
  99173. }
  99174. };
  99175. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  99176. this._selectionContent.reset();
  99177. for (var index = 0; index < this.blocks.length; index++) {
  99178. var block = this.blocks[index];
  99179. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  99180. }
  99181. if (allowDuplicate) {
  99182. this._selectionContent.concat(this.dynamicContent);
  99183. }
  99184. else {
  99185. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99186. }
  99187. return this._selectionContent;
  99188. };
  99189. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  99190. this._selectionContent.reset();
  99191. for (var index = 0; index < this.blocks.length; index++) {
  99192. var block = this.blocks[index];
  99193. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  99194. }
  99195. if (allowDuplicate) {
  99196. this._selectionContent.concat(this.dynamicContent);
  99197. }
  99198. else {
  99199. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99200. }
  99201. return this._selectionContent;
  99202. };
  99203. Octree.prototype.intersectsRay = function (ray) {
  99204. this._selectionContent.reset();
  99205. for (var index = 0; index < this.blocks.length; index++) {
  99206. var block = this.blocks[index];
  99207. block.intersectsRay(ray, this._selectionContent);
  99208. }
  99209. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99210. return this._selectionContent;
  99211. };
  99212. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  99213. target.blocks = new Array();
  99214. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  99215. // Segmenting space
  99216. for (var x = 0; x < 2; x++) {
  99217. for (var y = 0; y < 2; y++) {
  99218. for (var z = 0; z < 2; z++) {
  99219. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  99220. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  99221. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  99222. block.addEntries(entries);
  99223. target.blocks.push(block);
  99224. }
  99225. }
  99226. }
  99227. };
  99228. Octree.CreationFuncForMeshes = function (entry, block) {
  99229. var boundingInfo = entry.getBoundingInfo();
  99230. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  99231. block.entries.push(entry);
  99232. }
  99233. };
  99234. Octree.CreationFuncForSubMeshes = function (entry, block) {
  99235. var boundingInfo = entry.getBoundingInfo();
  99236. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  99237. block.entries.push(entry);
  99238. }
  99239. };
  99240. return Octree;
  99241. }());
  99242. BABYLON.Octree = Octree;
  99243. })(BABYLON || (BABYLON = {}));
  99244. //# sourceMappingURL=babylon.octree.js.map
  99245. var BABYLON;
  99246. (function (BABYLON) {
  99247. /**
  99248. * Class used to store a cell in an octree
  99249. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  99250. */
  99251. var OctreeBlock = /** @class */ (function () {
  99252. /**
  99253. * Creates a new block
  99254. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  99255. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  99256. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  99257. * @param depth defines the current depth of this block in the octree
  99258. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  99259. * @param creationFunc defines a callback to call when an element is added to the block
  99260. */
  99261. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  99262. /**
  99263. * Gets the content of the current block
  99264. */
  99265. this.entries = new Array();
  99266. this._boundingVectors = new Array();
  99267. this._capacity = capacity;
  99268. this._depth = depth;
  99269. this._maxDepth = maxDepth;
  99270. this._creationFunc = creationFunc;
  99271. this._minPoint = minPoint;
  99272. this._maxPoint = maxPoint;
  99273. this._boundingVectors.push(minPoint.clone());
  99274. this._boundingVectors.push(maxPoint.clone());
  99275. this._boundingVectors.push(minPoint.clone());
  99276. this._boundingVectors[2].x = maxPoint.x;
  99277. this._boundingVectors.push(minPoint.clone());
  99278. this._boundingVectors[3].y = maxPoint.y;
  99279. this._boundingVectors.push(minPoint.clone());
  99280. this._boundingVectors[4].z = maxPoint.z;
  99281. this._boundingVectors.push(maxPoint.clone());
  99282. this._boundingVectors[5].z = minPoint.z;
  99283. this._boundingVectors.push(maxPoint.clone());
  99284. this._boundingVectors[6].x = minPoint.x;
  99285. this._boundingVectors.push(maxPoint.clone());
  99286. this._boundingVectors[7].y = minPoint.y;
  99287. }
  99288. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  99289. // Property
  99290. /**
  99291. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  99292. */
  99293. get: function () {
  99294. return this._capacity;
  99295. },
  99296. enumerable: true,
  99297. configurable: true
  99298. });
  99299. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  99300. /**
  99301. * Gets the minimum vector (in world space) of the block's bounding box
  99302. */
  99303. get: function () {
  99304. return this._minPoint;
  99305. },
  99306. enumerable: true,
  99307. configurable: true
  99308. });
  99309. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  99310. /**
  99311. * Gets the maximum vector (in world space) of the block's bounding box
  99312. */
  99313. get: function () {
  99314. return this._maxPoint;
  99315. },
  99316. enumerable: true,
  99317. configurable: true
  99318. });
  99319. // Methods
  99320. /**
  99321. * Add a new element to this block
  99322. * @param entry defines the element to add
  99323. */
  99324. OctreeBlock.prototype.addEntry = function (entry) {
  99325. if (this.blocks) {
  99326. for (var index = 0; index < this.blocks.length; index++) {
  99327. var block = this.blocks[index];
  99328. block.addEntry(entry);
  99329. }
  99330. return;
  99331. }
  99332. this._creationFunc(entry, this);
  99333. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  99334. this.createInnerBlocks();
  99335. }
  99336. };
  99337. /**
  99338. * Add an array of elements to this block
  99339. * @param entries defines the array of elements to add
  99340. */
  99341. OctreeBlock.prototype.addEntries = function (entries) {
  99342. for (var index = 0; index < entries.length; index++) {
  99343. var mesh = entries[index];
  99344. this.addEntry(mesh);
  99345. }
  99346. };
  99347. /**
  99348. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  99349. * @param frustumPlanes defines the frustum planes to test
  99350. * @param selection defines the array to store current content if selection is positive
  99351. * @param allowDuplicate defines if the selection array can contains duplicated entries
  99352. */
  99353. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  99354. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  99355. if (this.blocks) {
  99356. for (var index = 0; index < this.blocks.length; index++) {
  99357. var block = this.blocks[index];
  99358. block.select(frustumPlanes, selection, allowDuplicate);
  99359. }
  99360. return;
  99361. }
  99362. if (allowDuplicate) {
  99363. selection.concat(this.entries);
  99364. }
  99365. else {
  99366. selection.concatWithNoDuplicate(this.entries);
  99367. }
  99368. }
  99369. };
  99370. /**
  99371. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  99372. * @param sphereCenter defines the bounding sphere center
  99373. * @param sphereRadius defines the bounding sphere radius
  99374. * @param selection defines the array to store current content if selection is positive
  99375. * @param allowDuplicate defines if the selection array can contains duplicated entries
  99376. */
  99377. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  99378. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  99379. if (this.blocks) {
  99380. for (var index = 0; index < this.blocks.length; index++) {
  99381. var block = this.blocks[index];
  99382. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  99383. }
  99384. return;
  99385. }
  99386. if (allowDuplicate) {
  99387. selection.concat(this.entries);
  99388. }
  99389. else {
  99390. selection.concatWithNoDuplicate(this.entries);
  99391. }
  99392. }
  99393. };
  99394. /**
  99395. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  99396. * @param ray defines the ray to test with
  99397. * @param selection defines the array to store current content if selection is positive
  99398. */
  99399. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  99400. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  99401. if (this.blocks) {
  99402. for (var index = 0; index < this.blocks.length; index++) {
  99403. var block = this.blocks[index];
  99404. block.intersectsRay(ray, selection);
  99405. }
  99406. return;
  99407. }
  99408. selection.concatWithNoDuplicate(this.entries);
  99409. }
  99410. };
  99411. /**
  99412. * Subdivide the content into child blocks (this block will then be empty)
  99413. */
  99414. OctreeBlock.prototype.createInnerBlocks = function () {
  99415. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  99416. };
  99417. return OctreeBlock;
  99418. }());
  99419. BABYLON.OctreeBlock = OctreeBlock;
  99420. })(BABYLON || (BABYLON = {}));
  99421. //# sourceMappingURL=babylon.octreeBlock.js.map
  99422. var BABYLON;
  99423. (function (BABYLON) {
  99424. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  99425. if (maxCapacity === void 0) { maxCapacity = 64; }
  99426. if (maxDepth === void 0) { maxDepth = 2; }
  99427. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  99428. if (!component) {
  99429. component = new OctreeSceneComponent(this);
  99430. this._addComponent(component);
  99431. }
  99432. if (!this._selectionOctree) {
  99433. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  99434. }
  99435. var worldExtends = this.getWorldExtends();
  99436. // Update octree
  99437. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  99438. return this._selectionOctree;
  99439. };
  99440. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  99441. get: function () {
  99442. return this._selectionOctree;
  99443. },
  99444. enumerable: true,
  99445. configurable: true
  99446. });
  99447. /**
  99448. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  99449. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  99450. * @param maxCapacity defines the maximum size of each block (64 by default)
  99451. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  99452. * @returns the new octree
  99453. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  99454. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  99455. */
  99456. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  99457. if (maxCapacity === void 0) { maxCapacity = 64; }
  99458. if (maxDepth === void 0) { maxDepth = 2; }
  99459. var scene = this.getScene();
  99460. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  99461. if (!component) {
  99462. component = new OctreeSceneComponent(scene);
  99463. scene._addComponent(component);
  99464. }
  99465. if (!this._submeshesOctree) {
  99466. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  99467. }
  99468. this.computeWorldMatrix(true);
  99469. var boundingInfo = this.getBoundingInfo();
  99470. // Update octree
  99471. var bbox = boundingInfo.boundingBox;
  99472. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  99473. return this._submeshesOctree;
  99474. };
  99475. /**
  99476. * Defines the octree scene component responsible to manage any octrees
  99477. * in a given scene.
  99478. */
  99479. var OctreeSceneComponent = /** @class */ (function () {
  99480. /**
  99481. * Creates a new instance of the component for the given scene
  99482. * @param scene Defines the scene to register the component in
  99483. */
  99484. function OctreeSceneComponent(scene) {
  99485. /**
  99486. * The component name helpfull to identify the component in the list of scene components.
  99487. */
  99488. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  99489. /**
  99490. * Indicates if the meshes have been checked to make sure they are isEnabled()
  99491. */
  99492. this.checksIsEnabled = true;
  99493. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  99494. this.scene = scene;
  99495. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  99496. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  99497. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  99498. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  99499. }
  99500. /**
  99501. * Registers the component in a given scene
  99502. */
  99503. OctreeSceneComponent.prototype.register = function () {
  99504. var _this = this;
  99505. this.scene.onMeshRemovedObservable.add(function (mesh) {
  99506. var sceneOctree = _this.scene.selectionOctree;
  99507. if (sceneOctree !== undefined && sceneOctree !== null) {
  99508. var index = sceneOctree.dynamicContent.indexOf(mesh);
  99509. if (index !== -1) {
  99510. sceneOctree.dynamicContent.splice(index, 1);
  99511. }
  99512. }
  99513. });
  99514. this.scene.onMeshImportedObservable.add(function (mesh) {
  99515. var sceneOctree = _this.scene.selectionOctree;
  99516. if (sceneOctree !== undefined && sceneOctree !== null) {
  99517. sceneOctree.addMesh(mesh);
  99518. }
  99519. });
  99520. };
  99521. /**
  99522. * Return the list of active meshes
  99523. * @returns the list of active meshes
  99524. */
  99525. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  99526. if (this.scene._selectionOctree) {
  99527. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  99528. return selection;
  99529. }
  99530. return this.scene._getDefaultMeshCandidates();
  99531. };
  99532. /**
  99533. * Return the list of active sub meshes
  99534. * @param mesh The mesh to get the candidates sub meshes from
  99535. * @returns the list of active sub meshes
  99536. */
  99537. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  99538. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  99539. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  99540. return intersections;
  99541. }
  99542. return this.scene._getDefaultSubMeshCandidates(mesh);
  99543. };
  99544. /**
  99545. * Return the list of sub meshes intersecting with a given local ray
  99546. * @param mesh defines the mesh to find the submesh for
  99547. * @param localRay defines the ray in local space
  99548. * @returns the list of intersecting sub meshes
  99549. */
  99550. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  99551. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  99552. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  99553. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  99554. return intersections;
  99555. }
  99556. return this.scene._getDefaultSubMeshCandidates(mesh);
  99557. };
  99558. /**
  99559. * Return the list of sub meshes colliding with a collider
  99560. * @param mesh defines the mesh to find the submesh for
  99561. * @param collider defines the collider to evaluate the collision against
  99562. * @returns the list of colliding sub meshes
  99563. */
  99564. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  99565. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  99566. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  99567. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  99568. return intersections;
  99569. }
  99570. return this.scene._getDefaultSubMeshCandidates(mesh);
  99571. };
  99572. /**
  99573. * Rebuilds the elements related to this component in case of
  99574. * context lost for instance.
  99575. */
  99576. OctreeSceneComponent.prototype.rebuild = function () {
  99577. // Nothing to do here.
  99578. };
  99579. /**
  99580. * Disposes the component and the associated ressources.
  99581. */
  99582. OctreeSceneComponent.prototype.dispose = function () {
  99583. // Nothing to do here.
  99584. };
  99585. return OctreeSceneComponent;
  99586. }());
  99587. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  99588. })(BABYLON || (BABYLON = {}));
  99589. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  99590. var BABYLON;
  99591. (function (BABYLON) {
  99592. /**
  99593. * Postprocess used to generate anaglyphic rendering
  99594. */
  99595. var AnaglyphPostProcess = /** @class */ (function (_super) {
  99596. __extends(AnaglyphPostProcess, _super);
  99597. /**
  99598. * Creates a new AnaglyphPostProcess
  99599. * @param name defines postprocess name
  99600. * @param options defines creation options or target ratio scale
  99601. * @param rigCameras defines cameras using this postprocess
  99602. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  99603. * @param engine defines hosting engine
  99604. * @param reusable defines if the postprocess will be reused multiple times per frame
  99605. */
  99606. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  99607. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  99608. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99609. _this.onApplyObservable.add(function (effect) {
  99610. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  99611. });
  99612. return _this;
  99613. }
  99614. return AnaglyphPostProcess;
  99615. }(BABYLON.PostProcess));
  99616. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  99617. })(BABYLON || (BABYLON = {}));
  99618. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  99619. var BABYLON;
  99620. (function (BABYLON) {
  99621. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  99622. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99623. });
  99624. /**
  99625. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  99626. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99627. */
  99628. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  99629. __extends(AnaglyphArcRotateCamera, _super);
  99630. /**
  99631. * Creates a new AnaglyphArcRotateCamera
  99632. * @param name defines camera name
  99633. * @param alpha defines alpha angle (in radians)
  99634. * @param beta defines beta angle (in radians)
  99635. * @param radius defines radius
  99636. * @param target defines camera target
  99637. * @param interaxialDistance defines distance between each color axis
  99638. * @param scene defines the hosting scene
  99639. */
  99640. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  99641. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99642. _this.interaxialDistance = interaxialDistance;
  99643. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99644. return _this;
  99645. }
  99646. /**
  99647. * Gets camera class name
  99648. * @returns AnaglyphArcRotateCamera
  99649. */
  99650. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  99651. return "AnaglyphArcRotateCamera";
  99652. };
  99653. return AnaglyphArcRotateCamera;
  99654. }(BABYLON.ArcRotateCamera));
  99655. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  99656. })(BABYLON || (BABYLON = {}));
  99657. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  99658. var BABYLON;
  99659. (function (BABYLON) {
  99660. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  99661. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99662. });
  99663. /**
  99664. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  99665. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99666. */
  99667. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  99668. __extends(AnaglyphFreeCamera, _super);
  99669. /**
  99670. * Creates a new AnaglyphFreeCamera
  99671. * @param name defines camera name
  99672. * @param position defines initial position
  99673. * @param interaxialDistance defines distance between each color axis
  99674. * @param scene defines the hosting scene
  99675. */
  99676. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  99677. var _this = _super.call(this, name, position, scene) || this;
  99678. _this.interaxialDistance = interaxialDistance;
  99679. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99680. return _this;
  99681. }
  99682. /**
  99683. * Gets camera class name
  99684. * @returns AnaglyphFreeCamera
  99685. */
  99686. AnaglyphFreeCamera.prototype.getClassName = function () {
  99687. return "AnaglyphFreeCamera";
  99688. };
  99689. return AnaglyphFreeCamera;
  99690. }(BABYLON.FreeCamera));
  99691. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  99692. })(BABYLON || (BABYLON = {}));
  99693. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  99694. var BABYLON;
  99695. (function (BABYLON) {
  99696. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  99697. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99698. });
  99699. /**
  99700. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  99701. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99702. */
  99703. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  99704. __extends(AnaglyphGamepadCamera, _super);
  99705. /**
  99706. * Creates a new AnaglyphGamepadCamera
  99707. * @param name defines camera name
  99708. * @param position defines initial position
  99709. * @param interaxialDistance defines distance between each color axis
  99710. * @param scene defines the hosting scene
  99711. */
  99712. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  99713. var _this = _super.call(this, name, position, scene) || this;
  99714. _this.interaxialDistance = interaxialDistance;
  99715. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99716. return _this;
  99717. }
  99718. /**
  99719. * Gets camera class name
  99720. * @returns AnaglyphGamepadCamera
  99721. */
  99722. AnaglyphGamepadCamera.prototype.getClassName = function () {
  99723. return "AnaglyphGamepadCamera";
  99724. };
  99725. return AnaglyphGamepadCamera;
  99726. }(BABYLON.GamepadCamera));
  99727. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  99728. })(BABYLON || (BABYLON = {}));
  99729. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  99730. var BABYLON;
  99731. (function (BABYLON) {
  99732. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  99733. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99734. });
  99735. /**
  99736. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  99737. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99738. */
  99739. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  99740. __extends(AnaglyphUniversalCamera, _super);
  99741. /**
  99742. * Creates a new AnaglyphUniversalCamera
  99743. * @param name defines camera name
  99744. * @param position defines initial position
  99745. * @param interaxialDistance defines distance between each color axis
  99746. * @param scene defines the hosting scene
  99747. */
  99748. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  99749. var _this = _super.call(this, name, position, scene) || this;
  99750. _this.interaxialDistance = interaxialDistance;
  99751. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99752. return _this;
  99753. }
  99754. /**
  99755. * Gets camera class name
  99756. * @returns AnaglyphUniversalCamera
  99757. */
  99758. AnaglyphUniversalCamera.prototype.getClassName = function () {
  99759. return "AnaglyphUniversalCamera";
  99760. };
  99761. return AnaglyphUniversalCamera;
  99762. }(BABYLON.UniversalCamera));
  99763. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  99764. })(BABYLON || (BABYLON = {}));
  99765. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  99766. var BABYLON;
  99767. (function (BABYLON) {
  99768. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  99769. __extends(StereoscopicInterlacePostProcess, _super);
  99770. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  99771. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  99772. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99773. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99774. _this.onSizeChangedObservable.add(function () {
  99775. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99776. });
  99777. _this.onApplyObservable.add(function (effect) {
  99778. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  99779. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  99780. });
  99781. return _this;
  99782. }
  99783. return StereoscopicInterlacePostProcess;
  99784. }(BABYLON.PostProcess));
  99785. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  99786. })(BABYLON || (BABYLON = {}));
  99787. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  99788. var BABYLON;
  99789. (function (BABYLON) {
  99790. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  99791. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99792. });
  99793. /**
  99794. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  99795. * @see http://doc.babylonjs.com/features/cameras
  99796. */
  99797. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  99798. __extends(StereoscopicArcRotateCamera, _super);
  99799. /**
  99800. * Creates a new StereoscopicArcRotateCamera
  99801. * @param name defines camera name
  99802. * @param alpha defines alpha angle (in radians)
  99803. * @param beta defines beta angle (in radians)
  99804. * @param radius defines radius
  99805. * @param target defines camera target
  99806. * @param interaxialDistance defines distance between each color axis
  99807. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99808. * @param scene defines the hosting scene
  99809. */
  99810. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  99811. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99812. _this.interaxialDistance = interaxialDistance;
  99813. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99814. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99815. return _this;
  99816. }
  99817. /**
  99818. * Gets camera class name
  99819. * @returns StereoscopicArcRotateCamera
  99820. */
  99821. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  99822. return "StereoscopicArcRotateCamera";
  99823. };
  99824. return StereoscopicArcRotateCamera;
  99825. }(BABYLON.ArcRotateCamera));
  99826. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  99827. })(BABYLON || (BABYLON = {}));
  99828. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  99829. var BABYLON;
  99830. (function (BABYLON) {
  99831. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99832. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99833. });
  99834. /**
  99835. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  99836. * @see http://doc.babylonjs.com/features/cameras
  99837. */
  99838. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  99839. __extends(StereoscopicFreeCamera, _super);
  99840. /**
  99841. * Creates a new StereoscopicFreeCamera
  99842. * @param name defines camera name
  99843. * @param position defines initial position
  99844. * @param interaxialDistance defines distance between each color axis
  99845. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99846. * @param scene defines the hosting scene
  99847. */
  99848. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99849. var _this = _super.call(this, name, position, scene) || this;
  99850. _this.interaxialDistance = interaxialDistance;
  99851. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99852. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99853. return _this;
  99854. }
  99855. /**
  99856. * Gets camera class name
  99857. * @returns StereoscopicFreeCamera
  99858. */
  99859. StereoscopicFreeCamera.prototype.getClassName = function () {
  99860. return "StereoscopicFreeCamera";
  99861. };
  99862. return StereoscopicFreeCamera;
  99863. }(BABYLON.FreeCamera));
  99864. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  99865. })(BABYLON || (BABYLON = {}));
  99866. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  99867. var BABYLON;
  99868. (function (BABYLON) {
  99869. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  99870. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99871. });
  99872. /**
  99873. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  99874. * @see http://doc.babylonjs.com/features/cameras
  99875. */
  99876. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  99877. __extends(StereoscopicGamepadCamera, _super);
  99878. /**
  99879. * Creates a new StereoscopicGamepadCamera
  99880. * @param name defines camera name
  99881. * @param position defines initial position
  99882. * @param interaxialDistance defines distance between each color axis
  99883. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99884. * @param scene defines the hosting scene
  99885. */
  99886. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99887. var _this = _super.call(this, name, position, scene) || this;
  99888. _this.interaxialDistance = interaxialDistance;
  99889. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99890. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99891. return _this;
  99892. }
  99893. /**
  99894. * Gets camera class name
  99895. * @returns StereoscopicGamepadCamera
  99896. */
  99897. StereoscopicGamepadCamera.prototype.getClassName = function () {
  99898. return "StereoscopicGamepadCamera";
  99899. };
  99900. return StereoscopicGamepadCamera;
  99901. }(BABYLON.GamepadCamera));
  99902. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  99903. })(BABYLON || (BABYLON = {}));
  99904. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  99905. var BABYLON;
  99906. (function (BABYLON) {
  99907. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99908. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99909. });
  99910. /**
  99911. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  99912. * @see http://doc.babylonjs.com/features/cameras
  99913. */
  99914. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  99915. __extends(StereoscopicUniversalCamera, _super);
  99916. /**
  99917. * Creates a new StereoscopicUniversalCamera
  99918. * @param name defines camera name
  99919. * @param position defines initial position
  99920. * @param interaxialDistance defines distance between each color axis
  99921. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99922. * @param scene defines the hosting scene
  99923. */
  99924. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99925. var _this = _super.call(this, name, position, scene) || this;
  99926. _this.interaxialDistance = interaxialDistance;
  99927. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99928. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99929. return _this;
  99930. }
  99931. /**
  99932. * Gets camera class name
  99933. * @returns StereoscopicUniversalCamera
  99934. */
  99935. StereoscopicUniversalCamera.prototype.getClassName = function () {
  99936. return "StereoscopicUniversalCamera";
  99937. };
  99938. return StereoscopicUniversalCamera;
  99939. }(BABYLON.UniversalCamera));
  99940. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  99941. })(BABYLON || (BABYLON = {}));
  99942. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  99943. var BABYLON;
  99944. (function (BABYLON) {
  99945. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  99946. __extends(VRDistortionCorrectionPostProcess, _super);
  99947. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  99948. var _this = _super.call(this, name, "vrDistortionCorrection", [
  99949. 'LensCenter',
  99950. 'Scale',
  99951. 'ScaleIn',
  99952. 'HmdWarpParam'
  99953. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  99954. _this._isRightEye = isRightEye;
  99955. _this._distortionFactors = vrMetrics.distortionK;
  99956. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  99957. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  99958. _this.adaptScaleToCurrentViewport = true;
  99959. _this.onSizeChangedObservable.add(function () {
  99960. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  99961. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  99962. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  99963. });
  99964. _this.onApplyObservable.add(function (effect) {
  99965. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  99966. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  99967. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  99968. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  99969. });
  99970. return _this;
  99971. }
  99972. return VRDistortionCorrectionPostProcess;
  99973. }(BABYLON.PostProcess));
  99974. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  99975. })(BABYLON || (BABYLON = {}));
  99976. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  99977. var BABYLON;
  99978. (function (BABYLON) {
  99979. /**
  99980. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  99981. * Screen rotation is taken into account.
  99982. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99983. */
  99984. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  99985. /**
  99986. * Instantiates a new input
  99987. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99988. */
  99989. function FreeCameraDeviceOrientationInput() {
  99990. var _this = this;
  99991. this._screenOrientationAngle = 0;
  99992. this._screenQuaternion = new BABYLON.Quaternion();
  99993. this._alpha = 0;
  99994. this._beta = 0;
  99995. this._gamma = 0;
  99996. this._orientationChanged = function () {
  99997. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  99998. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  99999. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  100000. };
  100001. this._deviceOrientation = function (evt) {
  100002. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  100003. _this._beta = evt.beta !== null ? evt.beta : 0;
  100004. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  100005. };
  100006. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  100007. this._orientationChanged();
  100008. }
  100009. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  100010. /**
  100011. * Define the camera controlled by the input.
  100012. */
  100013. get: function () {
  100014. return this._camera;
  100015. },
  100016. set: function (camera) {
  100017. this._camera = camera;
  100018. if (this._camera != null && !this._camera.rotationQuaternion) {
  100019. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  100020. }
  100021. },
  100022. enumerable: true,
  100023. configurable: true
  100024. });
  100025. /**
  100026. * Attach the input controls to a specific dom element to get the input from.
  100027. * @param element Defines the element the controls should be listened from
  100028. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  100029. */
  100030. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  100031. window.addEventListener("orientationchange", this._orientationChanged);
  100032. window.addEventListener("deviceorientation", this._deviceOrientation);
  100033. //In certain cases, the attach control is called AFTER orientation was changed,
  100034. //So this is needed.
  100035. this._orientationChanged();
  100036. };
  100037. /**
  100038. * Detach the current controls from the specified dom element.
  100039. * @param element Defines the element to stop listening the inputs from
  100040. */
  100041. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  100042. window.removeEventListener("orientationchange", this._orientationChanged);
  100043. window.removeEventListener("deviceorientation", this._deviceOrientation);
  100044. };
  100045. /**
  100046. * Update the current camera state depending on the inputs that have been used this frame.
  100047. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  100048. */
  100049. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  100050. //if no device orientation provided, don't update the rotation.
  100051. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  100052. if (!this._alpha)
  100053. return;
  100054. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  100055. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  100056. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  100057. //Mirror on XY Plane
  100058. this._camera.rotationQuaternion.z *= -1;
  100059. this._camera.rotationQuaternion.w *= -1;
  100060. };
  100061. /**
  100062. * Gets the class name of the current intput.
  100063. * @returns the class name
  100064. */
  100065. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  100066. return "FreeCameraDeviceOrientationInput";
  100067. };
  100068. /**
  100069. * Get the friendly name associated with the input class.
  100070. * @returns the input friendly name
  100071. */
  100072. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  100073. return "deviceOrientation";
  100074. };
  100075. return FreeCameraDeviceOrientationInput;
  100076. }());
  100077. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  100078. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  100079. })(BABYLON || (BABYLON = {}));
  100080. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  100081. var BABYLON;
  100082. (function (BABYLON) {
  100083. /**
  100084. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  100085. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  100086. */
  100087. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  100088. /**
  100089. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  100090. */
  100091. function ArcRotateCameraVRDeviceOrientationInput() {
  100092. /**
  100093. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  100094. */
  100095. this.alphaCorrection = 1;
  100096. /**
  100097. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  100098. */
  100099. this.betaCorrection = 1;
  100100. /**
  100101. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  100102. */
  100103. this.gammaCorrection = 1;
  100104. this._alpha = 0;
  100105. this._gamma = 0;
  100106. this._dirty = false;
  100107. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  100108. }
  100109. /**
  100110. * Attach the input controls to a specific dom element to get the input from.
  100111. * @param element Defines the element the controls should be listened from
  100112. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  100113. */
  100114. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  100115. this.camera.attachControl(element, noPreventDefault);
  100116. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  100117. };
  100118. /** @hidden */
  100119. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  100120. if (evt.alpha !== null) {
  100121. this._alpha = +evt.alpha | 0;
  100122. }
  100123. if (evt.gamma !== null) {
  100124. this._gamma = +evt.gamma | 0;
  100125. }
  100126. this._dirty = true;
  100127. };
  100128. /**
  100129. * Update the current camera state depending on the inputs that have been used this frame.
  100130. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  100131. */
  100132. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  100133. if (this._dirty) {
  100134. this._dirty = false;
  100135. if (this._gamma < 0) {
  100136. this._gamma = 180 + this._gamma;
  100137. }
  100138. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  100139. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  100140. }
  100141. };
  100142. /**
  100143. * Detach the current controls from the specified dom element.
  100144. * @param element Defines the element to stop listening the inputs from
  100145. */
  100146. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  100147. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  100148. };
  100149. /**
  100150. * Gets the class name of the current intput.
  100151. * @returns the class name
  100152. */
  100153. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  100154. return "ArcRotateCameraVRDeviceOrientationInput";
  100155. };
  100156. /**
  100157. * Get the friendly name associated with the input class.
  100158. * @returns the input friendly name
  100159. */
  100160. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  100161. return "VRDeviceOrientation";
  100162. };
  100163. return ArcRotateCameraVRDeviceOrientationInput;
  100164. }());
  100165. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  100166. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  100167. })(BABYLON || (BABYLON = {}));
  100168. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  100169. var BABYLON;
  100170. (function (BABYLON) {
  100171. /**
  100172. * This represents all the required metrics to create a VR camera.
  100173. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  100174. */
  100175. var VRCameraMetrics = /** @class */ (function () {
  100176. function VRCameraMetrics() {
  100177. /**
  100178. * Define if the current vr camera should compensate the distortion of the lense or not.
  100179. */
  100180. this.compensateDistortion = true;
  100181. }
  100182. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  100183. /**
  100184. * Gets the rendering aspect ratio based on the provided resolutions.
  100185. */
  100186. get: function () {
  100187. return this.hResolution / (2 * this.vResolution);
  100188. },
  100189. enumerable: true,
  100190. configurable: true
  100191. });
  100192. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  100193. /**
  100194. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  100195. */
  100196. get: function () {
  100197. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  100198. },
  100199. enumerable: true,
  100200. configurable: true
  100201. });
  100202. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  100203. /**
  100204. * @hidden
  100205. */
  100206. get: function () {
  100207. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  100208. var h = (4 * meters) / this.hScreenSize;
  100209. return BABYLON.Matrix.Translation(h, 0, 0);
  100210. },
  100211. enumerable: true,
  100212. configurable: true
  100213. });
  100214. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  100215. /**
  100216. * @hidden
  100217. */
  100218. get: function () {
  100219. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  100220. var h = (4 * meters) / this.hScreenSize;
  100221. return BABYLON.Matrix.Translation(-h, 0, 0);
  100222. },
  100223. enumerable: true,
  100224. configurable: true
  100225. });
  100226. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  100227. /**
  100228. * @hidden
  100229. */
  100230. get: function () {
  100231. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  100232. },
  100233. enumerable: true,
  100234. configurable: true
  100235. });
  100236. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  100237. /**
  100238. * @hidden
  100239. */
  100240. get: function () {
  100241. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  100242. },
  100243. enumerable: true,
  100244. configurable: true
  100245. });
  100246. /**
  100247. * Get the default VRMetrics based on the most generic setup.
  100248. * @returns the default vr metrics
  100249. */
  100250. VRCameraMetrics.GetDefault = function () {
  100251. var result = new VRCameraMetrics();
  100252. result.hResolution = 1280;
  100253. result.vResolution = 800;
  100254. result.hScreenSize = 0.149759993;
  100255. result.vScreenSize = 0.0935999975;
  100256. result.vScreenCenter = 0.0467999987;
  100257. result.eyeToScreenDistance = 0.0410000011;
  100258. result.lensSeparationDistance = 0.0635000020;
  100259. result.interpupillaryDistance = 0.0640000030;
  100260. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  100261. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  100262. result.postProcessScaleFactor = 1.714605507808412;
  100263. result.lensCenterOffset = 0.151976421;
  100264. return result;
  100265. };
  100266. return VRCameraMetrics;
  100267. }());
  100268. BABYLON.VRCameraMetrics = VRCameraMetrics;
  100269. })(BABYLON || (BABYLON = {}));
  100270. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  100271. var BABYLON;
  100272. (function (BABYLON) {
  100273. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  100274. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  100275. });
  100276. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  100277. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  100278. });
  100279. /**
  100280. * This represents a WebVR camera.
  100281. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  100282. * @example http://doc.babylonjs.com/how_to/webvr_camera
  100283. */
  100284. var WebVRFreeCamera = /** @class */ (function (_super) {
  100285. __extends(WebVRFreeCamera, _super);
  100286. /**
  100287. * Instantiates a WebVRFreeCamera.
  100288. * @param name The name of the WebVRFreeCamera
  100289. * @param position The starting anchor position for the camera
  100290. * @param scene The scene the camera belongs to
  100291. * @param webVROptions a set of customizable options for the webVRCamera
  100292. */
  100293. function WebVRFreeCamera(name, position, scene, webVROptions) {
  100294. if (webVROptions === void 0) { webVROptions = {}; }
  100295. var _this = _super.call(this, name, position, scene) || this;
  100296. _this.webVROptions = webVROptions;
  100297. /**
  100298. * @hidden
  100299. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  100300. */
  100301. _this._vrDevice = null;
  100302. /**
  100303. * The rawPose of the vrDevice.
  100304. */
  100305. _this.rawPose = null;
  100306. _this._specsVersion = "1.1";
  100307. _this._attached = false;
  100308. _this._descendants = [];
  100309. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  100310. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  100311. /** @hidden */
  100312. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  100313. _this._standingMatrix = null;
  100314. /**
  100315. * Represents device position in babylon space.
  100316. */
  100317. _this.devicePosition = BABYLON.Vector3.Zero();
  100318. /**
  100319. * Represents device rotation in babylon space.
  100320. */
  100321. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  100322. /**
  100323. * The scale of the device to be used when translating from device space to babylon space.
  100324. */
  100325. _this.deviceScaleFactor = 1;
  100326. _this._deviceToWorld = BABYLON.Matrix.Identity();
  100327. _this._worldToDevice = BABYLON.Matrix.Identity();
  100328. /**
  100329. * References to the webVR controllers for the vrDevice.
  100330. */
  100331. _this.controllers = [];
  100332. /**
  100333. * Emits an event when a controller is attached.
  100334. */
  100335. _this.onControllersAttachedObservable = new BABYLON.Observable();
  100336. /**
  100337. * Emits an event when a controller's mesh has been loaded;
  100338. */
  100339. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  100340. /**
  100341. * Emits an event when the HMD's pose has been updated.
  100342. */
  100343. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  100344. _this._poseSet = false;
  100345. /**
  100346. * If the rig cameras be used as parent instead of this camera.
  100347. */
  100348. _this.rigParenting = true;
  100349. _this._defaultHeight = undefined;
  100350. _this._htmlElementAttached = null;
  100351. _this._detachIfAttached = function () {
  100352. var vrDisplay = _this.getEngine().getVRDevice();
  100353. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  100354. _this.detachControl(_this._htmlElementAttached);
  100355. }
  100356. };
  100357. _this._workingVector = BABYLON.Vector3.Zero();
  100358. _this._oneVector = BABYLON.Vector3.One();
  100359. _this._workingMatrix = BABYLON.Matrix.Identity();
  100360. _this._tmpMatrix = new BABYLON.Matrix();
  100361. _this._cache.position = BABYLON.Vector3.Zero();
  100362. if (webVROptions.defaultHeight) {
  100363. _this._defaultHeight = webVROptions.defaultHeight;
  100364. _this.position.y = _this._defaultHeight;
  100365. }
  100366. _this.minZ = 0.1;
  100367. //legacy support - the compensation boolean was removed.
  100368. if (arguments.length === 5) {
  100369. _this.webVROptions = arguments[4];
  100370. }
  100371. // default webVR options
  100372. if (_this.webVROptions.trackPosition == undefined) {
  100373. _this.webVROptions.trackPosition = true;
  100374. }
  100375. if (_this.webVROptions.controllerMeshes == undefined) {
  100376. _this.webVROptions.controllerMeshes = true;
  100377. }
  100378. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  100379. _this.webVROptions.defaultLightingOnControllers = true;
  100380. }
  100381. _this.rotationQuaternion = new BABYLON.Quaternion();
  100382. if (_this.webVROptions && _this.webVROptions.positionScale) {
  100383. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  100384. }
  100385. //enable VR
  100386. var engine = _this.getEngine();
  100387. _this._onVREnabled = function (success) { if (success) {
  100388. _this.initControllers();
  100389. } };
  100390. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  100391. engine.initWebVR().add(function (event) {
  100392. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  100393. return;
  100394. }
  100395. _this._vrDevice = event.vrDisplay;
  100396. //reset the rig parameters.
  100397. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  100398. if (_this._attached) {
  100399. _this.getEngine().enableVR();
  100400. }
  100401. });
  100402. if (typeof (VRFrameData) !== "undefined")
  100403. _this._frameData = new VRFrameData();
  100404. /**
  100405. * The idea behind the following lines:
  100406. * objects that have the camera as parent should actually have the rig cameras as a parent.
  100407. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  100408. * the second will not show it correctly.
  100409. *
  100410. * To solve this - each object that has the camera as parent will be added to a protected array.
  100411. * When the rig camera renders, it will take this array and set all of those to be its children.
  100412. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  100413. * Amazing!
  100414. */
  100415. scene.onBeforeCameraRenderObservable.add(function (camera) {
  100416. if (camera.parent === _this && _this.rigParenting) {
  100417. _this._descendants = _this.getDescendants(true, function (n) {
  100418. // don't take the cameras or the controllers!
  100419. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  100420. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  100421. return !isController && !isRigCamera;
  100422. });
  100423. _this._descendants.forEach(function (node) {
  100424. node.parent = camera;
  100425. });
  100426. }
  100427. });
  100428. scene.onAfterCameraRenderObservable.add(function (camera) {
  100429. if (camera.parent === _this && _this.rigParenting) {
  100430. _this._descendants.forEach(function (node) {
  100431. node.parent = _this;
  100432. });
  100433. }
  100434. });
  100435. return _this;
  100436. }
  100437. /**
  100438. * Gets the device distance from the ground in meters.
  100439. * @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.
  100440. */
  100441. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  100442. if (this._standingMatrix) {
  100443. // Add standing matrix offset to get real offset from ground in room
  100444. this._standingMatrix.getTranslationToRef(this._workingVector);
  100445. return this._deviceRoomPosition.y + this._workingVector.y;
  100446. }
  100447. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  100448. return this._defaultHeight || 0;
  100449. };
  100450. /**
  100451. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  100452. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  100453. */
  100454. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  100455. var _this = this;
  100456. if (callback === void 0) { callback = function (bool) { }; }
  100457. // Use standing matrix if available
  100458. this.getEngine().initWebVRAsync().then(function (result) {
  100459. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  100460. callback(false);
  100461. }
  100462. else {
  100463. _this._standingMatrix = new BABYLON.Matrix();
  100464. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  100465. if (!_this.getScene().useRightHandedSystem) {
  100466. [2, 6, 8, 9, 14].forEach(function (num) {
  100467. if (_this._standingMatrix) {
  100468. _this._standingMatrix.m[num] *= -1;
  100469. }
  100470. });
  100471. }
  100472. callback(true);
  100473. }
  100474. });
  100475. };
  100476. /**
  100477. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  100478. * @returns A promise with a boolean set to if the standing matrix is supported.
  100479. */
  100480. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  100481. var _this = this;
  100482. return new Promise(function (res, rej) {
  100483. _this.useStandingMatrix(function (supported) {
  100484. res(supported);
  100485. });
  100486. });
  100487. };
  100488. /**
  100489. * Disposes the camera
  100490. */
  100491. WebVRFreeCamera.prototype.dispose = function () {
  100492. this._detachIfAttached();
  100493. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  100494. if (this._updateCacheWhenTrackingDisabledObserver) {
  100495. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  100496. }
  100497. _super.prototype.dispose.call(this);
  100498. };
  100499. /**
  100500. * Gets a vrController by name.
  100501. * @param name The name of the controller to retreive
  100502. * @returns the controller matching the name specified or null if not found
  100503. */
  100504. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  100505. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  100506. var gp = _a[_i];
  100507. if (gp.hand === name) {
  100508. return gp;
  100509. }
  100510. }
  100511. return null;
  100512. };
  100513. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  100514. /**
  100515. * The controller corrisponding to the users left hand.
  100516. */
  100517. get: function () {
  100518. if (!this._leftController) {
  100519. this._leftController = this.getControllerByName("left");
  100520. }
  100521. return this._leftController;
  100522. },
  100523. enumerable: true,
  100524. configurable: true
  100525. });
  100526. ;
  100527. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  100528. /**
  100529. * The controller corrisponding to the users right hand.
  100530. */
  100531. get: function () {
  100532. if (!this._rightController) {
  100533. this._rightController = this.getControllerByName("right");
  100534. }
  100535. return this._rightController;
  100536. },
  100537. enumerable: true,
  100538. configurable: true
  100539. });
  100540. ;
  100541. /**
  100542. * Casts a ray forward from the vrCamera's gaze.
  100543. * @param length Length of the ray (default: 100)
  100544. * @returns the ray corrisponding to the gaze
  100545. */
  100546. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  100547. if (length === void 0) { length = 100; }
  100548. if (this.leftCamera) {
  100549. // Use left eye to avoid computation to compute center on every call
  100550. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  100551. }
  100552. else {
  100553. return _super.prototype.getForwardRay.call(this, length);
  100554. }
  100555. };
  100556. /**
  100557. * @hidden
  100558. * Updates the camera based on device's frame data
  100559. */
  100560. WebVRFreeCamera.prototype._checkInputs = function () {
  100561. if (this._vrDevice && this._vrDevice.isPresenting) {
  100562. this._vrDevice.getFrameData(this._frameData);
  100563. this.updateFromDevice(this._frameData.pose);
  100564. }
  100565. _super.prototype._checkInputs.call(this);
  100566. };
  100567. /**
  100568. * Updates the poseControlled values based on the input device pose.
  100569. * @param poseData Pose coming from the device
  100570. */
  100571. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  100572. if (poseData && poseData.orientation) {
  100573. this.rawPose = poseData;
  100574. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  100575. if (this.getScene().useRightHandedSystem) {
  100576. this._deviceRoomRotationQuaternion.z *= -1;
  100577. this._deviceRoomRotationQuaternion.w *= -1;
  100578. }
  100579. if (this.webVROptions.trackPosition && this.rawPose.position) {
  100580. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  100581. if (this.getScene().useRightHandedSystem) {
  100582. this._deviceRoomPosition.z *= -1;
  100583. }
  100584. }
  100585. this._poseSet = true;
  100586. }
  100587. };
  100588. /**
  100589. * WebVR's attach control will start broadcasting frames to the device.
  100590. * Note that in certain browsers (chrome for example) this function must be called
  100591. * within a user-interaction callback. Example:
  100592. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  100593. *
  100594. * @param element html element to attach the vrDevice to
  100595. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  100596. */
  100597. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  100598. _super.prototype.attachControl.call(this, element, noPreventDefault);
  100599. this._attached = true;
  100600. this._htmlElementAttached = element;
  100601. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  100602. if (this._vrDevice) {
  100603. this.getEngine().enableVR();
  100604. }
  100605. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100606. };
  100607. /**
  100608. * Detaches the camera from the html element and disables VR
  100609. *
  100610. * @param element html element to detach from
  100611. */
  100612. WebVRFreeCamera.prototype.detachControl = function (element) {
  100613. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  100614. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  100615. _super.prototype.detachControl.call(this, element);
  100616. this._attached = false;
  100617. this.getEngine().disableVR();
  100618. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100619. };
  100620. /**
  100621. * @returns the name of this class
  100622. */
  100623. WebVRFreeCamera.prototype.getClassName = function () {
  100624. return "WebVRFreeCamera";
  100625. };
  100626. /**
  100627. * Calls resetPose on the vrDisplay
  100628. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  100629. */
  100630. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  100631. //uses the vrDisplay's "resetPose()".
  100632. //pitch and roll won't be affected.
  100633. this._vrDevice.resetPose();
  100634. };
  100635. /**
  100636. * @hidden
  100637. * Updates the rig cameras (left and right eye)
  100638. */
  100639. WebVRFreeCamera.prototype._updateRigCameras = function () {
  100640. var camLeft = this._rigCameras[0];
  100641. var camRight = this._rigCameras[1];
  100642. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100643. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100644. camLeft.position.copyFrom(this._deviceRoomPosition);
  100645. camRight.position.copyFrom(this._deviceRoomPosition);
  100646. };
  100647. // Remove translation from 6dof headset if trackposition is set to false
  100648. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  100649. if (isViewMatrix === void 0) { isViewMatrix = false; }
  100650. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  100651. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  100652. if (!isViewMatrix) {
  100653. this._tmpMatrix.invert();
  100654. }
  100655. this._tmpMatrix.multiplyToRef(matrix, matrix);
  100656. }
  100657. };
  100658. /**
  100659. * @hidden
  100660. * Updates the cached values of the camera
  100661. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  100662. */
  100663. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  100664. var _this = this;
  100665. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  100666. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  100667. if (!this.updateCacheCalled) {
  100668. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  100669. this.updateCacheCalled = true;
  100670. this.update();
  100671. }
  100672. // Set working vector to the device position in room space rotated by the new rotation
  100673. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  100674. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  100675. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  100676. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  100677. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  100678. // Add translation from anchor position
  100679. this._deviceToWorld.getTranslationToRef(this._workingVector);
  100680. this._workingVector.addInPlace(this.position);
  100681. this._workingVector.subtractInPlace(this._cache.position);
  100682. this._deviceToWorld.setTranslation(this._workingVector);
  100683. // Set an inverted matrix to be used when updating the camera
  100684. this._deviceToWorld.invertToRef(this._worldToDevice);
  100685. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  100686. this.controllers.forEach(function (controller) {
  100687. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  100688. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  100689. controller.update();
  100690. });
  100691. }
  100692. if (!ignoreParentClass) {
  100693. _super.prototype._updateCache.call(this);
  100694. }
  100695. this.updateCacheCalled = false;
  100696. };
  100697. /**
  100698. * @hidden
  100699. * Get current device position in babylon world
  100700. */
  100701. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  100702. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  100703. };
  100704. /**
  100705. * Updates the current device position and rotation in the babylon world
  100706. */
  100707. WebVRFreeCamera.prototype.update = function () {
  100708. this._computeDevicePosition();
  100709. // Get current device rotation in babylon world
  100710. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  100711. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  100712. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  100713. if (this._poseSet) {
  100714. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  100715. }
  100716. _super.prototype.update.call(this);
  100717. };
  100718. /**
  100719. * @hidden
  100720. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  100721. * @returns an identity matrix
  100722. */
  100723. WebVRFreeCamera.prototype._getViewMatrix = function () {
  100724. return BABYLON.Matrix.Identity();
  100725. };
  100726. /**
  100727. * This function is called by the two RIG cameras.
  100728. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  100729. */
  100730. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  100731. var _this = this;
  100732. // Update the parent camera prior to using a child camera to avoid desynchronization
  100733. var parentCamera = this._cameraRigParams["parentCamera"];
  100734. parentCamera._updateCache();
  100735. //WebVR 1.1
  100736. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  100737. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  100738. if (!this.getScene().useRightHandedSystem) {
  100739. [2, 6, 8, 9, 14].forEach(function (num) {
  100740. _this._webvrViewMatrix.m[num] *= -1;
  100741. });
  100742. }
  100743. // update the camera rotation matrix
  100744. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  100745. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  100746. // Computing target and final matrix
  100747. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  100748. // should the view matrix be updated with scale and position offset?
  100749. if (parentCamera.deviceScaleFactor !== 1) {
  100750. this._webvrViewMatrix.invert();
  100751. // scale the position, if set
  100752. if (parentCamera.deviceScaleFactor) {
  100753. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  100754. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  100755. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  100756. }
  100757. this._webvrViewMatrix.invert();
  100758. }
  100759. // Remove translation from 6dof headset if trackposition is set to false
  100760. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  100761. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  100762. // Compute global position
  100763. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  100764. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  100765. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  100766. this._workingMatrix.getTranslationToRef(this._globalPosition);
  100767. this._markSyncedWithParent();
  100768. return this._webvrViewMatrix;
  100769. };
  100770. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  100771. var _this = this;
  100772. var parentCamera = this.parent;
  100773. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  100774. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  100775. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  100776. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  100777. //babylon compatible matrix
  100778. if (!this.getScene().useRightHandedSystem) {
  100779. [8, 9, 10, 11].forEach(function (num) {
  100780. _this._projectionMatrix.m[num] *= -1;
  100781. });
  100782. }
  100783. return this._projectionMatrix;
  100784. };
  100785. /**
  100786. * Initializes the controllers and their meshes
  100787. */
  100788. WebVRFreeCamera.prototype.initControllers = function () {
  100789. var _this = this;
  100790. this.controllers = [];
  100791. var manager = this.getScene().gamepadManager;
  100792. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  100793. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100794. var webVrController = gamepad;
  100795. if (webVrController.defaultModel) {
  100796. webVrController.defaultModel.setEnabled(false);
  100797. }
  100798. if (webVrController.hand === "right") {
  100799. _this._rightController = null;
  100800. }
  100801. if (webVrController.hand === "left") {
  100802. _this._leftController = null;
  100803. }
  100804. var controllerIndex = _this.controllers.indexOf(webVrController);
  100805. if (controllerIndex !== -1) {
  100806. _this.controllers.splice(controllerIndex, 1);
  100807. }
  100808. }
  100809. });
  100810. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  100811. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100812. var webVrController_1 = gamepad;
  100813. if (!_this.webVROptions.trackPosition) {
  100814. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  100815. // Cache must be updated before rendering controllers to avoid them being one frame behind
  100816. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  100817. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  100818. _this._updateCache();
  100819. });
  100820. }
  100821. }
  100822. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  100823. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  100824. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  100825. if (_this.webVROptions.controllerMeshes) {
  100826. if (webVrController_1.defaultModel) {
  100827. webVrController_1.defaultModel.setEnabled(true);
  100828. }
  100829. else {
  100830. // Load the meshes
  100831. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  100832. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  100833. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  100834. if (_this.webVROptions.defaultLightingOnControllers) {
  100835. if (!_this._lightOnControllers) {
  100836. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  100837. }
  100838. var activateLightOnSubMeshes_1 = function (mesh, light) {
  100839. var children = mesh.getChildren();
  100840. if (children && children.length !== 0) {
  100841. children.forEach(function (mesh) {
  100842. light.includedOnlyMeshes.push(mesh);
  100843. activateLightOnSubMeshes_1(mesh, light);
  100844. });
  100845. }
  100846. };
  100847. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  100848. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  100849. }
  100850. });
  100851. }
  100852. }
  100853. webVrController_1.attachToPoseControlledCamera(_this);
  100854. // since this is async - sanity check. Is the controller already stored?
  100855. if (_this.controllers.indexOf(webVrController_1) === -1) {
  100856. //add to the controllers array
  100857. _this.controllers.push(webVrController_1);
  100858. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  100859. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  100860. // So we're overriding setting left & right manually to be sure
  100861. var firstViveWandDetected = false;
  100862. for (var i = 0; i < _this.controllers.length; i++) {
  100863. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  100864. if (!firstViveWandDetected) {
  100865. firstViveWandDetected = true;
  100866. _this.controllers[i].hand = "left";
  100867. }
  100868. else {
  100869. _this.controllers[i].hand = "right";
  100870. }
  100871. }
  100872. }
  100873. //did we find enough controllers? Great! let the developer know.
  100874. if (_this.controllers.length >= 2) {
  100875. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  100876. }
  100877. }
  100878. }
  100879. });
  100880. };
  100881. return WebVRFreeCamera;
  100882. }(BABYLON.FreeCamera));
  100883. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  100884. })(BABYLON || (BABYLON = {}));
  100885. //# sourceMappingURL=babylon.webVRCamera.js.map
  100886. var BABYLON;
  100887. (function (BABYLON) {
  100888. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  100889. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  100890. });
  100891. // We're mainly based on the logic defined into the FreeCamera code
  100892. /**
  100893. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  100894. * being tilted forward or back and left or right.
  100895. */
  100896. var DeviceOrientationCamera = /** @class */ (function (_super) {
  100897. __extends(DeviceOrientationCamera, _super);
  100898. /**
  100899. * Creates a new device orientation camera
  100900. * @param name The name of the camera
  100901. * @param position The start position camera
  100902. * @param scene The scene the camera belongs to
  100903. */
  100904. function DeviceOrientationCamera(name, position, scene) {
  100905. var _this = _super.call(this, name, position, scene) || this;
  100906. _this._quaternionCache = new BABYLON.Quaternion();
  100907. _this.inputs.addDeviceOrientation();
  100908. return _this;
  100909. }
  100910. /**
  100911. * Gets the current instance class name ("DeviceOrientationCamera").
  100912. * This helps avoiding instanceof at run time.
  100913. * @returns the class name
  100914. */
  100915. DeviceOrientationCamera.prototype.getClassName = function () {
  100916. return "DeviceOrientationCamera";
  100917. };
  100918. /**
  100919. * @hidden
  100920. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  100921. */
  100922. DeviceOrientationCamera.prototype._checkInputs = function () {
  100923. _super.prototype._checkInputs.call(this);
  100924. this._quaternionCache.copyFrom(this.rotationQuaternion);
  100925. if (this._initialQuaternion) {
  100926. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100927. }
  100928. };
  100929. /**
  100930. * Reset the camera to its default orientation on the specified axis only.
  100931. * @param axis The axis to reset
  100932. */
  100933. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  100934. var _this = this;
  100935. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  100936. //can only work if this camera has a rotation quaternion already.
  100937. if (!this.rotationQuaternion)
  100938. return;
  100939. if (!this._initialQuaternion) {
  100940. this._initialQuaternion = new BABYLON.Quaternion();
  100941. }
  100942. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  100943. ['x', 'y', 'z'].forEach(function (axisName) {
  100944. if (!axis[axisName]) {
  100945. _this._initialQuaternion[axisName] = 0;
  100946. }
  100947. else {
  100948. _this._initialQuaternion[axisName] *= -1;
  100949. }
  100950. });
  100951. this._initialQuaternion.normalize();
  100952. //force rotation update
  100953. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100954. };
  100955. return DeviceOrientationCamera;
  100956. }(BABYLON.FreeCamera));
  100957. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  100958. })(BABYLON || (BABYLON = {}));
  100959. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  100960. var BABYLON;
  100961. (function (BABYLON) {
  100962. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100963. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  100964. });
  100965. /**
  100966. * Camera used to simulate VR rendering (based on FreeCamera)
  100967. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100968. */
  100969. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  100970. __extends(VRDeviceOrientationFreeCamera, _super);
  100971. /**
  100972. * Creates a new VRDeviceOrientationFreeCamera
  100973. * @param name defines camera name
  100974. * @param position defines the start position of the camera
  100975. * @param scene defines the scene the camera belongs to
  100976. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100977. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100978. */
  100979. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  100980. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100981. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100982. var _this = _super.call(this, name, position, scene) || this;
  100983. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100984. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  100985. return _this;
  100986. }
  100987. /**
  100988. * Gets camera class name
  100989. * @returns VRDeviceOrientationFreeCamera
  100990. */
  100991. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  100992. return "VRDeviceOrientationFreeCamera";
  100993. };
  100994. return VRDeviceOrientationFreeCamera;
  100995. }(BABYLON.DeviceOrientationCamera));
  100996. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  100997. })(BABYLON || (BABYLON = {}));
  100998. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  100999. var BABYLON;
  101000. (function (BABYLON) {
  101001. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  101002. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  101003. });
  101004. /**
  101005. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  101006. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  101007. */
  101008. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  101009. __extends(VRDeviceOrientationArcRotateCamera, _super);
  101010. /**
  101011. * Creates a new VRDeviceOrientationArcRotateCamera
  101012. * @param name defines camera name
  101013. * @param alpha defines the camera rotation along the logitudinal axis
  101014. * @param beta defines the camera rotation along the latitudinal axis
  101015. * @param radius defines the camera distance from its target
  101016. * @param target defines the camera target
  101017. * @param scene defines the scene the camera belongs to
  101018. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  101019. * @param vrCameraMetrics defines the vr metrics associated to the camera
  101020. */
  101021. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  101022. if (compensateDistortion === void 0) { compensateDistortion = true; }
  101023. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  101024. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101025. vrCameraMetrics.compensateDistortion = compensateDistortion;
  101026. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  101027. _this.inputs.addVRDeviceOrientation();
  101028. return _this;
  101029. }
  101030. /**
  101031. * Gets camera class name
  101032. * @returns VRDeviceOrientationArcRotateCamera
  101033. */
  101034. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  101035. return "VRDeviceOrientationArcRotateCamera";
  101036. };
  101037. return VRDeviceOrientationArcRotateCamera;
  101038. }(BABYLON.ArcRotateCamera));
  101039. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  101040. })(BABYLON || (BABYLON = {}));
  101041. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  101042. var BABYLON;
  101043. (function (BABYLON) {
  101044. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  101045. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  101046. });
  101047. /**
  101048. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  101049. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  101050. */
  101051. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  101052. __extends(VRDeviceOrientationGamepadCamera, _super);
  101053. /**
  101054. * Creates a new VRDeviceOrientationGamepadCamera
  101055. * @param name defines camera name
  101056. * @param position defines the start position of the camera
  101057. * @param scene defines the scene the camera belongs to
  101058. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  101059. * @param vrCameraMetrics defines the vr metrics associated to the camera
  101060. */
  101061. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  101062. if (compensateDistortion === void 0) { compensateDistortion = true; }
  101063. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  101064. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  101065. _this.inputs.addGamepad();
  101066. return _this;
  101067. }
  101068. /**
  101069. * Gets camera class name
  101070. * @returns VRDeviceOrientationGamepadCamera
  101071. */
  101072. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  101073. return "VRDeviceOrientationGamepadCamera";
  101074. };
  101075. return VRDeviceOrientationGamepadCamera;
  101076. }(BABYLON.VRDeviceOrientationFreeCamera));
  101077. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  101078. })(BABYLON || (BABYLON = {}));
  101079. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  101080. var BABYLON;
  101081. (function (BABYLON) {
  101082. var VRExperienceHelperGazer = /** @class */ (function () {
  101083. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  101084. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  101085. this.scene = scene;
  101086. /** @hidden */
  101087. this._pointerDownOnMeshAsked = false;
  101088. /** @hidden */
  101089. this._isActionableMesh = false;
  101090. /** @hidden */
  101091. this._teleportationRequestInitiated = false;
  101092. /** @hidden */
  101093. this._teleportationBackRequestInitiated = false;
  101094. /** @hidden */
  101095. this._rotationRightAsked = false;
  101096. /** @hidden */
  101097. this._rotationLeftAsked = false;
  101098. /** @hidden */
  101099. this._dpadPressed = true;
  101100. /** @hidden */
  101101. this._activePointer = false;
  101102. this._id = VRExperienceHelperGazer._idCounter++;
  101103. // Gaze tracker
  101104. if (!gazeTrackerToClone) {
  101105. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  101106. this._gazeTracker.bakeCurrentTransformIntoVertices();
  101107. this._gazeTracker.isPickable = false;
  101108. this._gazeTracker.isVisible = false;
  101109. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  101110. targetMat.specularColor = BABYLON.Color3.Black();
  101111. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  101112. targetMat.backFaceCulling = false;
  101113. this._gazeTracker.material = targetMat;
  101114. }
  101115. else {
  101116. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  101117. }
  101118. }
  101119. /** @hidden */
  101120. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  101121. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  101122. };
  101123. /** @hidden */
  101124. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  101125. this._pointerDownOnMeshAsked = true;
  101126. if (this._currentHit) {
  101127. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  101128. }
  101129. };
  101130. /** @hidden */
  101131. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  101132. if (this._currentHit) {
  101133. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  101134. }
  101135. this._pointerDownOnMeshAsked = false;
  101136. };
  101137. /** @hidden */
  101138. VRExperienceHelperGazer.prototype._activatePointer = function () {
  101139. this._activePointer = true;
  101140. };
  101141. /** @hidden */
  101142. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  101143. this._activePointer = false;
  101144. };
  101145. /** @hidden */
  101146. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  101147. if (distance === void 0) { distance = 100; }
  101148. };
  101149. VRExperienceHelperGazer.prototype.dispose = function () {
  101150. this._interactionsEnabled = false;
  101151. this._teleportationEnabled = false;
  101152. if (this._gazeTracker) {
  101153. this._gazeTracker.dispose();
  101154. }
  101155. };
  101156. VRExperienceHelperGazer._idCounter = 0;
  101157. return VRExperienceHelperGazer;
  101158. }());
  101159. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  101160. __extends(VRExperienceHelperControllerGazer, _super);
  101161. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  101162. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  101163. _this.webVRController = webVRController;
  101164. // Laser pointer
  101165. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  101166. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  101167. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  101168. laserPointerMaterial.alpha = 0.6;
  101169. _this._laserPointer.material = laserPointerMaterial;
  101170. _this._laserPointer.rotation.x = Math.PI / 2;
  101171. _this._laserPointer.position.z = -0.5;
  101172. _this._laserPointer.isVisible = false;
  101173. _this._laserPointer.isPickable = false;
  101174. if (!webVRController.mesh) {
  101175. // Create an empty mesh that is used prior to loading the high quality model
  101176. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  101177. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  101178. preloadPointerPose.rotation.x = -0.7;
  101179. preloadMesh.addChild(preloadPointerPose);
  101180. webVRController.attachToMesh(preloadMesh);
  101181. }
  101182. _this._setLaserPointerParent(webVRController.mesh);
  101183. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  101184. _this._setLaserPointerParent(mesh);
  101185. });
  101186. return _this;
  101187. }
  101188. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  101189. return this.webVRController.getForwardRay(length);
  101190. };
  101191. /** @hidden */
  101192. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  101193. _super.prototype._activatePointer.call(this);
  101194. this._laserPointer.isVisible = true;
  101195. };
  101196. /** @hidden */
  101197. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  101198. _super.prototype._deactivatePointer.call(this);
  101199. this._laserPointer.isVisible = false;
  101200. };
  101201. /** @hidden */
  101202. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  101203. this._laserPointer.material.emissiveColor = color;
  101204. };
  101205. /** @hidden */
  101206. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  101207. var makeNotPick = function (root) {
  101208. root.isPickable = false;
  101209. root.getChildMeshes().forEach(function (c) {
  101210. makeNotPick(c);
  101211. });
  101212. };
  101213. makeNotPick(mesh);
  101214. var childMeshes = mesh.getChildMeshes();
  101215. this.webVRController._pointingPoseNode = null;
  101216. for (var i = 0; i < childMeshes.length; i++) {
  101217. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  101218. mesh = childMeshes[i];
  101219. this.webVRController._pointingPoseNode = mesh;
  101220. break;
  101221. }
  101222. }
  101223. this._laserPointer.parent = mesh;
  101224. };
  101225. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  101226. if (distance === void 0) { distance = 100; }
  101227. this._laserPointer.scaling.y = distance;
  101228. this._laserPointer.position.z = -distance / 2;
  101229. };
  101230. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  101231. _super.prototype.dispose.call(this);
  101232. this._laserPointer.dispose();
  101233. if (this._meshAttachedObserver) {
  101234. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  101235. }
  101236. };
  101237. return VRExperienceHelperControllerGazer;
  101238. }(VRExperienceHelperGazer));
  101239. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  101240. __extends(VRExperienceHelperCameraGazer, _super);
  101241. function VRExperienceHelperCameraGazer(getCamera, scene) {
  101242. var _this = _super.call(this, scene) || this;
  101243. _this.getCamera = getCamera;
  101244. return _this;
  101245. }
  101246. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  101247. var camera = this.getCamera();
  101248. if (camera) {
  101249. return camera.getForwardRay(length);
  101250. }
  101251. else {
  101252. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  101253. }
  101254. };
  101255. return VRExperienceHelperCameraGazer;
  101256. }(VRExperienceHelperGazer));
  101257. /**
  101258. * Helps to quickly add VR support to an existing scene.
  101259. * See http://doc.babylonjs.com/how_to/webvr_helper
  101260. */
  101261. var VRExperienceHelper = /** @class */ (function () {
  101262. /**
  101263. * Instantiates a VRExperienceHelper.
  101264. * Helps to quickly add VR support to an existing scene.
  101265. * @param scene The scene the VRExperienceHelper belongs to.
  101266. * @param webVROptions Options to modify the vr experience helper's behavior.
  101267. */
  101268. function VRExperienceHelper(scene,
  101269. /** Options to modify the vr experience helper's behavior. */
  101270. webVROptions) {
  101271. if (webVROptions === void 0) { webVROptions = {}; }
  101272. var _this = this;
  101273. this.webVROptions = webVROptions;
  101274. // Can the system support WebVR, even if a headset isn't plugged in?
  101275. this._webVRsupported = false;
  101276. // If WebVR is supported, is a headset plugged in and are we ready to present?
  101277. this._webVRready = false;
  101278. // Are we waiting for the requestPresent callback to complete?
  101279. this._webVRrequesting = false;
  101280. // Are we presenting to the headset right now? (this is the vrDevice state)
  101281. this._webVRpresenting = false;
  101282. // Are we presenting in the fullscreen fallback?
  101283. this._fullscreenVRpresenting = false;
  101284. /**
  101285. * Observable raised when entering VR.
  101286. */
  101287. this.onEnteringVRObservable = new BABYLON.Observable();
  101288. /**
  101289. * Observable raised when exiting VR.
  101290. */
  101291. this.onExitingVRObservable = new BABYLON.Observable();
  101292. /**
  101293. * Observable raised when controller mesh is loaded.
  101294. */
  101295. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  101296. this._useCustomVRButton = false;
  101297. this._teleportationRequested = false;
  101298. this._teleportActive = false;
  101299. this._floorMeshesCollection = [];
  101300. this._rotationAllowed = true;
  101301. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  101302. this._isDefaultTeleportationTarget = true;
  101303. this._teleportationFillColor = "#444444";
  101304. this._teleportationBorderColor = "#FFFFFF";
  101305. this._rotationAngle = 0;
  101306. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  101307. this._padSensibilityUp = 0.65;
  101308. this._padSensibilityDown = 0.35;
  101309. this._leftController = null;
  101310. this._rightController = null;
  101311. /**
  101312. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  101313. */
  101314. this.onNewMeshSelected = new BABYLON.Observable();
  101315. /**
  101316. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  101317. */
  101318. this.onNewMeshPicked = new BABYLON.Observable();
  101319. /**
  101320. * Observable raised before camera teleportation
  101321. */
  101322. this.onBeforeCameraTeleport = new BABYLON.Observable();
  101323. /**
  101324. * Observable raised after camera teleportation
  101325. */
  101326. this.onAfterCameraTeleport = new BABYLON.Observable();
  101327. /**
  101328. * Observable raised when current selected mesh gets unselected
  101329. */
  101330. this.onSelectedMeshUnselected = new BABYLON.Observable();
  101331. /**
  101332. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  101333. */
  101334. this.teleportationEnabled = true;
  101335. this._teleportationInitialized = false;
  101336. this._interactionsEnabled = false;
  101337. this._interactionsRequested = false;
  101338. this._displayGaze = true;
  101339. this._displayLaserPointer = true;
  101340. /**
  101341. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  101342. */
  101343. this.updateGazeTrackerScale = true;
  101344. this._onResize = function () {
  101345. _this.moveButtonToBottomRight();
  101346. if (_this._fullscreenVRpresenting && _this._webVRready) {
  101347. _this.exitVR();
  101348. }
  101349. };
  101350. this._onFullscreenChange = function () {
  101351. if (document.fullscreen !== undefined) {
  101352. _this._fullscreenVRpresenting = document.fullscreen;
  101353. }
  101354. else if (document.mozFullScreen !== undefined) {
  101355. _this._fullscreenVRpresenting = document.mozFullScreen;
  101356. }
  101357. else if (document.webkitIsFullScreen !== undefined) {
  101358. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  101359. }
  101360. else if (document.msIsFullScreen !== undefined) {
  101361. _this._fullscreenVRpresenting = document.msIsFullScreen;
  101362. }
  101363. else if (document.msFullscreenElement !== undefined) {
  101364. _this._fullscreenVRpresenting = document.msFullscreenElement;
  101365. }
  101366. if (!_this._fullscreenVRpresenting && _this._canvas) {
  101367. _this.exitVR();
  101368. if (!_this._useCustomVRButton) {
  101369. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  101370. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  101371. }
  101372. }
  101373. };
  101374. this.beforeRender = function () {
  101375. if (_this._leftController && _this._leftController._activePointer) {
  101376. _this._castRayAndSelectObject(_this._leftController);
  101377. }
  101378. if (_this._rightController && _this._rightController._activePointer) {
  101379. _this._castRayAndSelectObject(_this._rightController);
  101380. }
  101381. if (_this._noControllerIsActive) {
  101382. _this._castRayAndSelectObject(_this._cameraGazer);
  101383. }
  101384. else {
  101385. _this._cameraGazer._gazeTracker.isVisible = false;
  101386. }
  101387. };
  101388. this._onNewGamepadConnected = function (gamepad) {
  101389. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  101390. if (gamepad.leftStick) {
  101391. gamepad.onleftstickchanged(function (stickValues) {
  101392. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  101393. // Listening to classic/xbox gamepad only if no VR controller is active
  101394. if ((!_this._leftController && !_this._rightController) ||
  101395. ((_this._leftController && !_this._leftController._activePointer) &&
  101396. (_this._rightController && !_this._rightController._activePointer))) {
  101397. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  101398. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  101399. }
  101400. }
  101401. });
  101402. }
  101403. if (gamepad.rightStick) {
  101404. gamepad.onrightstickchanged(function (stickValues) {
  101405. if (_this._teleportationInitialized) {
  101406. _this._checkRotate(stickValues, _this._cameraGazer);
  101407. }
  101408. });
  101409. }
  101410. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  101411. gamepad.onbuttondown(function (buttonPressed) {
  101412. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  101413. _this._cameraGazer._selectionPointerDown();
  101414. }
  101415. });
  101416. gamepad.onbuttonup(function (buttonPressed) {
  101417. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  101418. _this._cameraGazer._selectionPointerUp();
  101419. }
  101420. });
  101421. }
  101422. }
  101423. else {
  101424. var webVRController = gamepad;
  101425. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  101426. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  101427. _this._rightController = controller;
  101428. }
  101429. else {
  101430. _this._leftController = controller;
  101431. }
  101432. _this._tryEnableInteractionOnController(controller);
  101433. }
  101434. };
  101435. // 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
  101436. this._tryEnableInteractionOnController = function (controller) {
  101437. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  101438. _this._enableInteractionOnController(controller);
  101439. }
  101440. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  101441. _this._enableTeleportationOnController(controller);
  101442. }
  101443. };
  101444. this._onNewGamepadDisconnected = function (gamepad) {
  101445. if (gamepad instanceof BABYLON.WebVRController) {
  101446. if (gamepad.hand === "left" && _this._leftController != null) {
  101447. _this._leftController.dispose();
  101448. _this._leftController = null;
  101449. }
  101450. if (gamepad.hand === "right" && _this._rightController != null) {
  101451. _this._rightController.dispose();
  101452. _this._rightController = null;
  101453. }
  101454. }
  101455. };
  101456. this._workingVector = BABYLON.Vector3.Zero();
  101457. this._workingQuaternion = BABYLON.Quaternion.Identity();
  101458. this._workingMatrix = BABYLON.Matrix.Identity();
  101459. this._scene = scene;
  101460. this._canvas = scene.getEngine().getRenderingCanvas();
  101461. // Parse options
  101462. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  101463. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  101464. }
  101465. if (webVROptions.createDeviceOrientationCamera === undefined) {
  101466. webVROptions.createDeviceOrientationCamera = true;
  101467. }
  101468. if (webVROptions.laserToggle === undefined) {
  101469. webVROptions.laserToggle = true;
  101470. }
  101471. if (webVROptions.defaultHeight === undefined) {
  101472. webVROptions.defaultHeight = 1.7;
  101473. }
  101474. if (webVROptions.useCustomVRButton) {
  101475. this._useCustomVRButton = true;
  101476. if (webVROptions.customVRButton) {
  101477. this._btnVR = webVROptions.customVRButton;
  101478. }
  101479. }
  101480. if (webVROptions.rayLength) {
  101481. this._rayLength = webVROptions.rayLength;
  101482. }
  101483. this._defaultHeight = webVROptions.defaultHeight;
  101484. if (webVROptions.positionScale) {
  101485. this._rayLength *= webVROptions.positionScale;
  101486. this._defaultHeight *= webVROptions.positionScale;
  101487. }
  101488. this._hasEnteredVR = false;
  101489. // Set position
  101490. if (this._scene.activeCamera) {
  101491. this._position = this._scene.activeCamera.position.clone();
  101492. }
  101493. else {
  101494. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  101495. }
  101496. // Set non-vr camera
  101497. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  101498. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  101499. // Copy data from existing camera
  101500. if (this._scene.activeCamera) {
  101501. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  101502. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  101503. // Set rotation from previous camera
  101504. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  101505. var targetCamera = this._scene.activeCamera;
  101506. if (targetCamera.rotationQuaternion) {
  101507. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  101508. }
  101509. else {
  101510. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  101511. }
  101512. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  101513. }
  101514. }
  101515. this._scene.activeCamera = this._deviceOrientationCamera;
  101516. if (this._canvas) {
  101517. this._scene.activeCamera.attachControl(this._canvas);
  101518. }
  101519. }
  101520. else {
  101521. this._existingCamera = this._scene.activeCamera;
  101522. }
  101523. // Create VR cameras
  101524. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  101525. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  101526. }
  101527. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  101528. this._webVRCamera.useStandingMatrix();
  101529. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  101530. // Create default button
  101531. if (!this._useCustomVRButton) {
  101532. this._btnVR = document.createElement("BUTTON");
  101533. this._btnVR.className = "babylonVRicon";
  101534. this._btnVR.id = "babylonVRiconbtn";
  101535. this._btnVR.title = "Click to switch to VR";
  101536. 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) }";
  101537. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  101538. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  101539. // css += ".babylonVRicon.vrdisplaysupported { }";
  101540. // css += ".babylonVRicon.vrdisplayready { }";
  101541. // css += ".babylonVRicon.vrdisplayrequesting { }";
  101542. var style = document.createElement('style');
  101543. style.appendChild(document.createTextNode(css));
  101544. document.getElementsByTagName('head')[0].appendChild(style);
  101545. this.moveButtonToBottomRight();
  101546. }
  101547. // VR button click event
  101548. if (this._btnVR) {
  101549. this._btnVR.addEventListener("click", function () {
  101550. if (!_this.isInVRMode) {
  101551. _this.enterVR();
  101552. }
  101553. else {
  101554. _this.exitVR();
  101555. }
  101556. });
  101557. }
  101558. // Window events
  101559. window.addEventListener("resize", this._onResize);
  101560. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  101561. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  101562. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  101563. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  101564. document.onmsfullscreenchange = this._onFullscreenChange;
  101565. // Display vr button when headset is connected
  101566. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  101567. this.displayVRButton();
  101568. }
  101569. else {
  101570. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  101571. if (e.vrDisplay) {
  101572. _this.displayVRButton();
  101573. }
  101574. });
  101575. }
  101576. // Exiting VR mode using 'ESC' key on desktop
  101577. this._onKeyDown = function (event) {
  101578. if (event.keyCode === 27 && _this.isInVRMode) {
  101579. _this.exitVR();
  101580. }
  101581. };
  101582. document.addEventListener("keydown", this._onKeyDown);
  101583. // Exiting VR mode double tapping the touch screen
  101584. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  101585. if (_this.isInVRMode) {
  101586. _this.exitVR();
  101587. if (_this._fullscreenVRpresenting) {
  101588. _this._scene.getEngine().switchFullscreen(true);
  101589. }
  101590. }
  101591. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  101592. // Listen for WebVR display changes
  101593. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  101594. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  101595. this._onVRRequestPresentStart = function () {
  101596. _this._webVRrequesting = true;
  101597. _this.updateButtonVisibility();
  101598. };
  101599. this._onVRRequestPresentComplete = function (success) {
  101600. _this._webVRrequesting = false;
  101601. _this.updateButtonVisibility();
  101602. };
  101603. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  101604. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  101605. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  101606. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101607. scene.onDisposeObservable.add(function () {
  101608. _this.dispose();
  101609. });
  101610. // Gamepad connection events
  101611. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  101612. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  101613. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  101614. this.updateButtonVisibility();
  101615. //create easing functions
  101616. this._circleEase = new BABYLON.CircleEase();
  101617. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101618. if (this.webVROptions.floorMeshes) {
  101619. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  101620. }
  101621. }
  101622. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  101623. /** Return this.onEnteringVRObservable
  101624. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  101625. */
  101626. get: function () {
  101627. return this.onEnteringVRObservable;
  101628. },
  101629. enumerable: true,
  101630. configurable: true
  101631. });
  101632. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  101633. /** Return this.onExitingVRObservable
  101634. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  101635. */
  101636. get: function () {
  101637. return this.onExitingVRObservable;
  101638. },
  101639. enumerable: true,
  101640. configurable: true
  101641. });
  101642. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  101643. /** Return this.onControllerMeshLoadedObservable
  101644. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  101645. */
  101646. get: function () {
  101647. return this.onControllerMeshLoadedObservable;
  101648. },
  101649. enumerable: true,
  101650. configurable: true
  101651. });
  101652. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  101653. /**
  101654. * The mesh used to display where the user is going to teleport.
  101655. */
  101656. get: function () {
  101657. return this._teleportationTarget;
  101658. },
  101659. /**
  101660. * Sets the mesh to be used to display where the user is going to teleport.
  101661. */
  101662. set: function (value) {
  101663. if (value) {
  101664. value.name = "teleportationTarget";
  101665. this._isDefaultTeleportationTarget = false;
  101666. this._teleportationTarget = value;
  101667. }
  101668. },
  101669. enumerable: true,
  101670. configurable: true
  101671. });
  101672. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  101673. /**
  101674. * 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
  101675. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  101676. * See http://doc.babylonjs.com/resources/baking_transformations
  101677. */
  101678. get: function () {
  101679. return this._cameraGazer._gazeTracker;
  101680. },
  101681. set: function (value) {
  101682. if (value) {
  101683. // Dispose of existing meshes
  101684. if (this._cameraGazer._gazeTracker) {
  101685. this._cameraGazer._gazeTracker.dispose();
  101686. }
  101687. if (this._leftController && this._leftController._gazeTracker) {
  101688. this._leftController._gazeTracker.dispose();
  101689. }
  101690. if (this._rightController && this._rightController._gazeTracker) {
  101691. this._rightController._gazeTracker.dispose();
  101692. }
  101693. // Set and create gaze trackers on head and controllers
  101694. this._cameraGazer._gazeTracker = value;
  101695. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  101696. this._cameraGazer._gazeTracker.isPickable = false;
  101697. this._cameraGazer._gazeTracker.isVisible = false;
  101698. this._cameraGazer._gazeTracker.name = "gazeTracker";
  101699. if (this._leftController) {
  101700. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101701. }
  101702. if (this._rightController) {
  101703. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101704. }
  101705. }
  101706. },
  101707. enumerable: true,
  101708. configurable: true
  101709. });
  101710. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  101711. /**
  101712. * The gaze tracking mesh corresponding to the left controller
  101713. */
  101714. get: function () {
  101715. if (this._leftController) {
  101716. return this._leftController._gazeTracker;
  101717. }
  101718. return null;
  101719. },
  101720. enumerable: true,
  101721. configurable: true
  101722. });
  101723. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  101724. /**
  101725. * The gaze tracking mesh corresponding to the right controller
  101726. */
  101727. get: function () {
  101728. if (this._rightController) {
  101729. return this._rightController._gazeTracker;
  101730. }
  101731. return null;
  101732. },
  101733. enumerable: true,
  101734. configurable: true
  101735. });
  101736. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  101737. /**
  101738. * If the ray of the gaze should be displayed.
  101739. */
  101740. get: function () {
  101741. return this._displayGaze;
  101742. },
  101743. /**
  101744. * Sets if the ray of the gaze should be displayed.
  101745. */
  101746. set: function (value) {
  101747. this._displayGaze = value;
  101748. if (!value) {
  101749. this._cameraGazer._gazeTracker.isVisible = false;
  101750. if (this._leftController) {
  101751. this._leftController._gazeTracker.isVisible = false;
  101752. }
  101753. if (this._rightController) {
  101754. this._rightController._gazeTracker.isVisible = false;
  101755. }
  101756. }
  101757. },
  101758. enumerable: true,
  101759. configurable: true
  101760. });
  101761. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  101762. /**
  101763. * If the ray of the LaserPointer should be displayed.
  101764. */
  101765. get: function () {
  101766. return this._displayLaserPointer;
  101767. },
  101768. /**
  101769. * Sets if the ray of the LaserPointer should be displayed.
  101770. */
  101771. set: function (value) {
  101772. this._displayLaserPointer = value;
  101773. if (!value) {
  101774. if (this._rightController) {
  101775. this._rightController._deactivatePointer();
  101776. this._rightController._gazeTracker.isVisible = false;
  101777. }
  101778. if (this._leftController) {
  101779. this._leftController._deactivatePointer();
  101780. this._leftController._gazeTracker.isVisible = false;
  101781. }
  101782. }
  101783. else {
  101784. if (this._rightController) {
  101785. this._rightController._activatePointer();
  101786. }
  101787. if (this._leftController) {
  101788. this._leftController._activatePointer();
  101789. }
  101790. }
  101791. },
  101792. enumerable: true,
  101793. configurable: true
  101794. });
  101795. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  101796. /**
  101797. * The deviceOrientationCamera used as the camera when not in VR.
  101798. */
  101799. get: function () {
  101800. return this._deviceOrientationCamera;
  101801. },
  101802. enumerable: true,
  101803. configurable: true
  101804. });
  101805. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  101806. /**
  101807. * Based on the current WebVR support, returns the current VR camera used.
  101808. */
  101809. get: function () {
  101810. if (this._webVRready) {
  101811. return this._webVRCamera;
  101812. }
  101813. else {
  101814. return this._scene.activeCamera;
  101815. }
  101816. },
  101817. enumerable: true,
  101818. configurable: true
  101819. });
  101820. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  101821. /**
  101822. * The webVRCamera which is used when in VR.
  101823. */
  101824. get: function () {
  101825. return this._webVRCamera;
  101826. },
  101827. enumerable: true,
  101828. configurable: true
  101829. });
  101830. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  101831. /**
  101832. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  101833. */
  101834. get: function () {
  101835. return this._vrDeviceOrientationCamera;
  101836. },
  101837. enumerable: true,
  101838. configurable: true
  101839. });
  101840. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  101841. get: function () {
  101842. var result = this._cameraGazer._teleportationRequestInitiated
  101843. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  101844. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  101845. return result;
  101846. },
  101847. enumerable: true,
  101848. configurable: true
  101849. });
  101850. // Raised when one of the controller has loaded successfully its associated default mesh
  101851. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  101852. if (this._leftController && this._leftController.webVRController == webVRController) {
  101853. if (webVRController.mesh) {
  101854. this._leftController._setLaserPointerParent(webVRController.mesh);
  101855. }
  101856. }
  101857. if (this._rightController && this._rightController.webVRController == webVRController) {
  101858. if (webVRController.mesh) {
  101859. this._rightController._setLaserPointerParent(webVRController.mesh);
  101860. }
  101861. }
  101862. try {
  101863. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  101864. }
  101865. catch (err) {
  101866. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  101867. }
  101868. };
  101869. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  101870. /**
  101871. * Gets a value indicating if we are currently in VR mode.
  101872. */
  101873. get: function () {
  101874. return this._webVRpresenting || this._fullscreenVRpresenting;
  101875. },
  101876. enumerable: true,
  101877. configurable: true
  101878. });
  101879. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  101880. var vrDisplay = this._scene.getEngine().getVRDevice();
  101881. if (vrDisplay) {
  101882. var wasPresenting = this._webVRpresenting;
  101883. this._webVRpresenting = vrDisplay.isPresenting;
  101884. if (wasPresenting && !this._webVRpresenting)
  101885. this.exitVR();
  101886. }
  101887. else {
  101888. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  101889. }
  101890. this.updateButtonVisibility();
  101891. };
  101892. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  101893. this._webVRsupported = eventArgs.vrSupported;
  101894. this._webVRready = !!eventArgs.vrDisplay;
  101895. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  101896. this.updateButtonVisibility();
  101897. };
  101898. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  101899. if (this._canvas && !this._useCustomVRButton) {
  101900. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  101901. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  101902. }
  101903. };
  101904. VRExperienceHelper.prototype.displayVRButton = function () {
  101905. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  101906. document.body.appendChild(this._btnVR);
  101907. this._btnVRDisplayed = true;
  101908. }
  101909. };
  101910. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  101911. if (!this._btnVR || this._useCustomVRButton) {
  101912. return;
  101913. }
  101914. this._btnVR.className = "babylonVRicon";
  101915. if (this.isInVRMode) {
  101916. this._btnVR.className += " vrdisplaypresenting";
  101917. }
  101918. else {
  101919. if (this._webVRready)
  101920. this._btnVR.className += " vrdisplayready";
  101921. if (this._webVRsupported)
  101922. this._btnVR.className += " vrdisplaysupported";
  101923. if (this._webVRrequesting)
  101924. this._btnVR.className += " vrdisplayrequesting";
  101925. }
  101926. };
  101927. /**
  101928. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  101929. * Otherwise, will use the fullscreen API.
  101930. */
  101931. VRExperienceHelper.prototype.enterVR = function () {
  101932. if (this.onEnteringVRObservable) {
  101933. try {
  101934. this.onEnteringVRObservable.notifyObservers(this);
  101935. }
  101936. catch (err) {
  101937. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  101938. }
  101939. }
  101940. if (this._scene.activeCamera) {
  101941. this._position = this._scene.activeCamera.position.clone();
  101942. // make sure that we return to the last active camera
  101943. this._existingCamera = this._scene.activeCamera;
  101944. }
  101945. if (this._webVRrequesting)
  101946. return;
  101947. // If WebVR is supported and a headset is connected
  101948. if (this._webVRready) {
  101949. if (!this._webVRpresenting) {
  101950. this._webVRCamera.position = this._position;
  101951. this._scene.activeCamera = this._webVRCamera;
  101952. }
  101953. }
  101954. else if (this._vrDeviceOrientationCamera) {
  101955. this._vrDeviceOrientationCamera.position = this._position;
  101956. if (this._scene.activeCamera) {
  101957. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  101958. }
  101959. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  101960. this._scene.getEngine().switchFullscreen(true);
  101961. this.updateButtonVisibility();
  101962. }
  101963. if (this._scene.activeCamera && this._canvas) {
  101964. this._scene.activeCamera.attachControl(this._canvas);
  101965. }
  101966. if (this._interactionsEnabled) {
  101967. this._scene.registerBeforeRender(this.beforeRender);
  101968. }
  101969. this._hasEnteredVR = true;
  101970. };
  101971. /**
  101972. * Attempt to exit VR, or fullscreen.
  101973. */
  101974. VRExperienceHelper.prototype.exitVR = function () {
  101975. if (this._hasEnteredVR) {
  101976. if (this.onExitingVRObservable) {
  101977. try {
  101978. this.onExitingVRObservable.notifyObservers(this);
  101979. }
  101980. catch (err) {
  101981. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  101982. }
  101983. }
  101984. if (this._webVRpresenting) {
  101985. this._scene.getEngine().disableVR();
  101986. }
  101987. if (this._scene.activeCamera) {
  101988. this._position = this._scene.activeCamera.position.clone();
  101989. }
  101990. if (this._deviceOrientationCamera) {
  101991. this._deviceOrientationCamera.position = this._position;
  101992. this._scene.activeCamera = this._deviceOrientationCamera;
  101993. if (this._canvas) {
  101994. this._scene.activeCamera.attachControl(this._canvas);
  101995. }
  101996. }
  101997. else if (this._existingCamera) {
  101998. this._existingCamera.position = this._position;
  101999. this._scene.activeCamera = this._existingCamera;
  102000. }
  102001. this.updateButtonVisibility();
  102002. if (this._interactionsEnabled) {
  102003. this._scene.unregisterBeforeRender(this.beforeRender);
  102004. this._cameraGazer._gazeTracker.isVisible = false;
  102005. if (this._leftController) {
  102006. this._leftController._gazeTracker.isVisible = false;
  102007. }
  102008. if (this._rightController) {
  102009. this._rightController._gazeTracker.isVisible = false;
  102010. }
  102011. }
  102012. // resize to update width and height when exiting vr exits fullscreen
  102013. this._scene.getEngine().resize();
  102014. this._hasEnteredVR = false;
  102015. }
  102016. };
  102017. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  102018. /**
  102019. * The position of the vr experience helper.
  102020. */
  102021. get: function () {
  102022. return this._position;
  102023. },
  102024. /**
  102025. * Sets the position of the vr experience helper.
  102026. */
  102027. set: function (value) {
  102028. this._position = value;
  102029. if (this._scene.activeCamera) {
  102030. this._scene.activeCamera.position = value;
  102031. }
  102032. },
  102033. enumerable: true,
  102034. configurable: true
  102035. });
  102036. /**
  102037. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  102038. */
  102039. VRExperienceHelper.prototype.enableInteractions = function () {
  102040. var _this = this;
  102041. if (!this._interactionsEnabled) {
  102042. this._interactionsRequested = true;
  102043. if (this._leftController) {
  102044. this._enableInteractionOnController(this._leftController);
  102045. }
  102046. if (this._rightController) {
  102047. this._enableInteractionOnController(this._rightController);
  102048. }
  102049. this.raySelectionPredicate = function (mesh) {
  102050. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  102051. };
  102052. this.meshSelectionPredicate = function (mesh) {
  102053. return true;
  102054. };
  102055. this._raySelectionPredicate = function (mesh) {
  102056. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  102057. && mesh.name.indexOf("teleportationTarget") === -1
  102058. && mesh.name.indexOf("torusTeleportation") === -1)) {
  102059. return _this.raySelectionPredicate(mesh);
  102060. }
  102061. return false;
  102062. };
  102063. this._interactionsEnabled = true;
  102064. }
  102065. };
  102066. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  102067. get: function () {
  102068. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  102069. },
  102070. enumerable: true,
  102071. configurable: true
  102072. });
  102073. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  102074. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  102075. if (this._floorMeshesCollection[i].id === mesh.id) {
  102076. return true;
  102077. }
  102078. }
  102079. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  102080. return true;
  102081. }
  102082. return false;
  102083. };
  102084. /**
  102085. * Adds a floor mesh to be used for teleportation.
  102086. * @param floorMesh the mesh to be used for teleportation.
  102087. */
  102088. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  102089. if (!this._floorMeshesCollection) {
  102090. return;
  102091. }
  102092. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  102093. return;
  102094. }
  102095. this._floorMeshesCollection.push(floorMesh);
  102096. };
  102097. /**
  102098. * Removes a floor mesh from being used for teleportation.
  102099. * @param floorMesh the mesh to be removed.
  102100. */
  102101. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  102102. if (!this._floorMeshesCollection) {
  102103. return;
  102104. }
  102105. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  102106. if (meshIndex !== -1) {
  102107. this._floorMeshesCollection.splice(meshIndex, 1);
  102108. }
  102109. };
  102110. /**
  102111. * Enables interactions and teleportation using the VR controllers and gaze.
  102112. * @param vrTeleportationOptions options to modify teleportation behavior.
  102113. */
  102114. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  102115. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  102116. if (!this._teleportationInitialized) {
  102117. this._teleportationRequested = true;
  102118. this.enableInteractions();
  102119. if (vrTeleportationOptions.floorMeshName) {
  102120. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  102121. }
  102122. if (vrTeleportationOptions.floorMeshes) {
  102123. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  102124. }
  102125. if (this._leftController != null) {
  102126. this._enableTeleportationOnController(this._leftController);
  102127. }
  102128. if (this._rightController != null) {
  102129. this._enableTeleportationOnController(this._rightController);
  102130. }
  102131. // Creates an image processing post process for the vignette not relying
  102132. // on the main scene configuration for image processing to reduce setup and spaces
  102133. // (gamma/linear) conflicts.
  102134. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  102135. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  102136. imageProcessingConfiguration.vignetteEnabled = true;
  102137. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  102138. this._webVRCamera.detachPostProcess(this._postProcessMove);
  102139. this._teleportationInitialized = true;
  102140. if (this._isDefaultTeleportationTarget) {
  102141. this._createTeleportationCircles();
  102142. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  102143. }
  102144. }
  102145. };
  102146. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  102147. var _this = this;
  102148. var controllerMesh = controller.webVRController.mesh;
  102149. if (controllerMesh) {
  102150. controller._interactionsEnabled = true;
  102151. controller._activatePointer();
  102152. if (this.webVROptions.laserToggle) {
  102153. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  102154. // Enabling / disabling laserPointer
  102155. if (_this._displayLaserPointer && stateObject.value === 1) {
  102156. if (controller._activePointer) {
  102157. controller._deactivatePointer();
  102158. }
  102159. else {
  102160. controller._activatePointer();
  102161. }
  102162. if (_this.displayGaze) {
  102163. controller._gazeTracker.isVisible = controller._activePointer;
  102164. }
  102165. }
  102166. });
  102167. }
  102168. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  102169. var gazer = controller;
  102170. if (_this._noControllerIsActive) {
  102171. gazer = _this._cameraGazer;
  102172. }
  102173. if (!gazer._pointerDownOnMeshAsked) {
  102174. if (stateObject.value > _this._padSensibilityUp) {
  102175. gazer._selectionPointerDown();
  102176. }
  102177. }
  102178. else if (stateObject.value < _this._padSensibilityDown) {
  102179. gazer._selectionPointerUp();
  102180. }
  102181. });
  102182. }
  102183. };
  102184. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  102185. // Dont teleport if another gaze already requested teleportation
  102186. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  102187. return;
  102188. }
  102189. if (!gazer._teleportationRequestInitiated) {
  102190. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  102191. gazer._activatePointer();
  102192. gazer._teleportationRequestInitiated = true;
  102193. }
  102194. }
  102195. else {
  102196. // Listening to the proper controller values changes to confirm teleportation
  102197. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  102198. if (this._teleportActive) {
  102199. this.teleportCamera(this._haloCenter);
  102200. }
  102201. gazer._teleportationRequestInitiated = false;
  102202. }
  102203. }
  102204. };
  102205. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  102206. // Only rotate when user is not currently selecting a teleportation location
  102207. if (gazer._teleportationRequestInitiated) {
  102208. return;
  102209. }
  102210. if (!gazer._rotationLeftAsked) {
  102211. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  102212. gazer._rotationLeftAsked = true;
  102213. if (this._rotationAllowed) {
  102214. this._rotateCamera(false);
  102215. }
  102216. }
  102217. }
  102218. else {
  102219. if (stateObject.x > -this._padSensibilityDown) {
  102220. gazer._rotationLeftAsked = false;
  102221. }
  102222. }
  102223. if (!gazer._rotationRightAsked) {
  102224. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  102225. gazer._rotationRightAsked = true;
  102226. if (this._rotationAllowed) {
  102227. this._rotateCamera(true);
  102228. }
  102229. }
  102230. }
  102231. else {
  102232. if (stateObject.x < this._padSensibilityDown) {
  102233. gazer._rotationRightAsked = false;
  102234. }
  102235. }
  102236. };
  102237. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  102238. // Only teleport backwards when user is not currently selecting a teleportation location
  102239. if (gazer._teleportationRequestInitiated) {
  102240. return;
  102241. }
  102242. // Teleport backwards
  102243. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  102244. if (!gazer._teleportationBackRequestInitiated) {
  102245. if (!this.currentVRCamera) {
  102246. return;
  102247. }
  102248. // Get rotation and position of the current camera
  102249. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  102250. var position = this.currentVRCamera.position;
  102251. // If the camera has device position, use that instead
  102252. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  102253. rotation = this.currentVRCamera.deviceRotationQuaternion;
  102254. position = this.currentVRCamera.devicePosition;
  102255. }
  102256. // Get matrix with only the y rotation of the device rotation
  102257. rotation.toEulerAnglesToRef(this._workingVector);
  102258. this._workingVector.z = 0;
  102259. this._workingVector.x = 0;
  102260. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  102261. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  102262. // Rotate backwards ray by device rotation to cast at the ground behind the user
  102263. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  102264. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  102265. var ray = new BABYLON.Ray(position, this._workingVector);
  102266. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  102267. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  102268. this.teleportCamera(hit.pickedPoint);
  102269. }
  102270. gazer._teleportationBackRequestInitiated = true;
  102271. }
  102272. }
  102273. else {
  102274. gazer._teleportationBackRequestInitiated = false;
  102275. }
  102276. };
  102277. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  102278. var _this = this;
  102279. var controllerMesh = controller.webVRController.mesh;
  102280. if (controllerMesh) {
  102281. if (!controller._interactionsEnabled) {
  102282. this._enableInteractionOnController(controller);
  102283. }
  102284. controller._interactionsEnabled = true;
  102285. controller._teleportationEnabled = true;
  102286. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  102287. controller._dpadPressed = false;
  102288. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  102289. controller._dpadPressed = stateObject.pressed;
  102290. if (!controller._dpadPressed) {
  102291. controller._rotationLeftAsked = false;
  102292. controller._rotationRightAsked = false;
  102293. controller._teleportationBackRequestInitiated = false;
  102294. }
  102295. });
  102296. }
  102297. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  102298. if (_this.teleportationEnabled) {
  102299. _this._checkTeleportBackwards(stateObject, controller);
  102300. _this._checkTeleportWithRay(stateObject, controller);
  102301. }
  102302. _this._checkRotate(stateObject, controller);
  102303. });
  102304. }
  102305. };
  102306. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  102307. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  102308. this._teleportationTarget.isPickable = false;
  102309. var length = 512;
  102310. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  102311. dynamicTexture.hasAlpha = true;
  102312. var context = dynamicTexture.getContext();
  102313. var centerX = length / 2;
  102314. var centerY = length / 2;
  102315. var radius = 200;
  102316. context.beginPath();
  102317. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  102318. context.fillStyle = this._teleportationFillColor;
  102319. context.fill();
  102320. context.lineWidth = 10;
  102321. context.strokeStyle = this._teleportationBorderColor;
  102322. context.stroke();
  102323. context.closePath();
  102324. dynamicTexture.update();
  102325. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  102326. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  102327. this._teleportationTarget.material = teleportationCircleMaterial;
  102328. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  102329. torus.isPickable = false;
  102330. torus.parent = this._teleportationTarget;
  102331. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  102332. var keys = [];
  102333. keys.push({
  102334. frame: 0,
  102335. value: 0
  102336. });
  102337. keys.push({
  102338. frame: 30,
  102339. value: 0.4
  102340. });
  102341. keys.push({
  102342. frame: 60,
  102343. value: 0
  102344. });
  102345. animationInnerCircle.setKeys(keys);
  102346. var easingFunction = new BABYLON.SineEase();
  102347. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  102348. animationInnerCircle.setEasingFunction(easingFunction);
  102349. torus.animations = [];
  102350. torus.animations.push(animationInnerCircle);
  102351. this._scene.beginAnimation(torus, 0, 60, true);
  102352. this._hideTeleportationTarget();
  102353. };
  102354. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  102355. this._teleportActive = true;
  102356. if (this._teleportationInitialized) {
  102357. this._teleportationTarget.isVisible = true;
  102358. if (this._isDefaultTeleportationTarget) {
  102359. this._teleportationTarget.getChildren()[0].isVisible = true;
  102360. }
  102361. }
  102362. };
  102363. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  102364. this._teleportActive = false;
  102365. if (this._teleportationInitialized) {
  102366. this._teleportationTarget.isVisible = false;
  102367. if (this._isDefaultTeleportationTarget) {
  102368. this._teleportationTarget.getChildren()[0].isVisible = false;
  102369. }
  102370. }
  102371. };
  102372. VRExperienceHelper.prototype._rotateCamera = function (right) {
  102373. var _this = this;
  102374. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  102375. return;
  102376. }
  102377. if (right) {
  102378. this._rotationAngle++;
  102379. }
  102380. else {
  102381. this._rotationAngle--;
  102382. }
  102383. this.currentVRCamera.animations = [];
  102384. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  102385. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102386. var animationRotationKeys = [];
  102387. animationRotationKeys.push({
  102388. frame: 0,
  102389. value: this.currentVRCamera.rotationQuaternion
  102390. });
  102391. animationRotationKeys.push({
  102392. frame: 6,
  102393. value: target
  102394. });
  102395. animationRotation.setKeys(animationRotationKeys);
  102396. animationRotation.setEasingFunction(this._circleEase);
  102397. this.currentVRCamera.animations.push(animationRotation);
  102398. this._postProcessMove.animations = [];
  102399. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102400. var vignetteWeightKeys = [];
  102401. vignetteWeightKeys.push({
  102402. frame: 0,
  102403. value: 0
  102404. });
  102405. vignetteWeightKeys.push({
  102406. frame: 3,
  102407. value: 4
  102408. });
  102409. vignetteWeightKeys.push({
  102410. frame: 6,
  102411. value: 0
  102412. });
  102413. animationPP.setKeys(vignetteWeightKeys);
  102414. animationPP.setEasingFunction(this._circleEase);
  102415. this._postProcessMove.animations.push(animationPP);
  102416. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102417. var vignetteStretchKeys = [];
  102418. vignetteStretchKeys.push({
  102419. frame: 0,
  102420. value: 0
  102421. });
  102422. vignetteStretchKeys.push({
  102423. frame: 3,
  102424. value: 10
  102425. });
  102426. vignetteStretchKeys.push({
  102427. frame: 6,
  102428. value: 0
  102429. });
  102430. animationPP2.setKeys(vignetteStretchKeys);
  102431. animationPP2.setEasingFunction(this._circleEase);
  102432. this._postProcessMove.animations.push(animationPP2);
  102433. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  102434. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  102435. this._postProcessMove.samples = 4;
  102436. this._webVRCamera.attachPostProcess(this._postProcessMove);
  102437. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  102438. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  102439. });
  102440. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  102441. };
  102442. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  102443. if (hit.pickedPoint) {
  102444. if (gazer._teleportationRequestInitiated) {
  102445. this._displayTeleportationTarget();
  102446. this._haloCenter.copyFrom(hit.pickedPoint);
  102447. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  102448. }
  102449. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  102450. if (pickNormal) {
  102451. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  102452. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  102453. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  102454. }
  102455. this._teleportationTarget.position.y += 0.1;
  102456. }
  102457. };
  102458. /**
  102459. * Teleports the users feet to the desired location
  102460. * @param location The location where the user's feet should be placed
  102461. */
  102462. VRExperienceHelper.prototype.teleportCamera = function (location) {
  102463. var _this = this;
  102464. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  102465. return;
  102466. }
  102467. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  102468. // offset of the headset from the anchor.
  102469. if (this.webVRCamera.leftCamera) {
  102470. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  102471. this._workingVector.subtractInPlace(this.webVRCamera.position);
  102472. location.subtractToRef(this._workingVector, this._workingVector);
  102473. }
  102474. else {
  102475. this._workingVector.copyFrom(location);
  102476. }
  102477. // Add height to account for user's height offset
  102478. if (this.isInVRMode) {
  102479. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  102480. }
  102481. else {
  102482. this._workingVector.y += this._defaultHeight;
  102483. }
  102484. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  102485. // Create animation from the camera's position to the new location
  102486. this.currentVRCamera.animations = [];
  102487. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102488. var animationCameraTeleportationKeys = [{
  102489. frame: 0,
  102490. value: this.currentVRCamera.position
  102491. },
  102492. {
  102493. frame: 11,
  102494. value: this._workingVector
  102495. }
  102496. ];
  102497. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  102498. animationCameraTeleportation.setEasingFunction(this._circleEase);
  102499. this.currentVRCamera.animations.push(animationCameraTeleportation);
  102500. this._postProcessMove.animations = [];
  102501. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102502. var vignetteWeightKeys = [];
  102503. vignetteWeightKeys.push({
  102504. frame: 0,
  102505. value: 0
  102506. });
  102507. vignetteWeightKeys.push({
  102508. frame: 5,
  102509. value: 8
  102510. });
  102511. vignetteWeightKeys.push({
  102512. frame: 11,
  102513. value: 0
  102514. });
  102515. animationPP.setKeys(vignetteWeightKeys);
  102516. this._postProcessMove.animations.push(animationPP);
  102517. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102518. var vignetteStretchKeys = [];
  102519. vignetteStretchKeys.push({
  102520. frame: 0,
  102521. value: 0
  102522. });
  102523. vignetteStretchKeys.push({
  102524. frame: 5,
  102525. value: 10
  102526. });
  102527. vignetteStretchKeys.push({
  102528. frame: 11,
  102529. value: 0
  102530. });
  102531. animationPP2.setKeys(vignetteStretchKeys);
  102532. this._postProcessMove.animations.push(animationPP2);
  102533. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  102534. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  102535. this._webVRCamera.attachPostProcess(this._postProcessMove);
  102536. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  102537. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  102538. });
  102539. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  102540. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  102541. });
  102542. this._hideTeleportationTarget();
  102543. };
  102544. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  102545. if (normal) {
  102546. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  102547. if (angle < Math.PI / 2) {
  102548. normal.scaleInPlace(-1);
  102549. }
  102550. }
  102551. return normal;
  102552. };
  102553. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  102554. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  102555. return;
  102556. }
  102557. var ray = gazer._getForwardRay(this._rayLength);
  102558. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  102559. if (hit) {
  102560. // Populate the contrllers mesh that can be used for drag/drop
  102561. if (gazer._laserPointer) {
  102562. hit.originMesh = gazer._laserPointer.parent;
  102563. }
  102564. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  102565. }
  102566. gazer._currentHit = hit;
  102567. // Moving the gazeTracker on the mesh face targetted
  102568. if (hit && hit.pickedPoint) {
  102569. if (this._displayGaze) {
  102570. var multiplier = 1;
  102571. gazer._gazeTracker.isVisible = true;
  102572. if (gazer._isActionableMesh) {
  102573. multiplier = 3;
  102574. }
  102575. if (this.updateGazeTrackerScale) {
  102576. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  102577. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  102578. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  102579. }
  102580. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  102581. // To avoid z-fighting
  102582. var deltaFighting = 0.002;
  102583. if (pickNormal) {
  102584. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  102585. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  102586. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  102587. }
  102588. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  102589. if (gazer._gazeTracker.position.x < 0) {
  102590. gazer._gazeTracker.position.x += deltaFighting;
  102591. }
  102592. else {
  102593. gazer._gazeTracker.position.x -= deltaFighting;
  102594. }
  102595. if (gazer._gazeTracker.position.y < 0) {
  102596. gazer._gazeTracker.position.y += deltaFighting;
  102597. }
  102598. else {
  102599. gazer._gazeTracker.position.y -= deltaFighting;
  102600. }
  102601. if (gazer._gazeTracker.position.z < 0) {
  102602. gazer._gazeTracker.position.z += deltaFighting;
  102603. }
  102604. else {
  102605. gazer._gazeTracker.position.z -= deltaFighting;
  102606. }
  102607. }
  102608. // Changing the size of the laser pointer based on the distance from the targetted point
  102609. gazer._updatePointerDistance(hit.distance);
  102610. }
  102611. else {
  102612. gazer._updatePointerDistance();
  102613. gazer._gazeTracker.isVisible = false;
  102614. }
  102615. if (hit && hit.pickedMesh) {
  102616. // The object selected is the floor, we're in a teleportation scenario
  102617. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  102618. // Moving the teleportation area to this targetted point
  102619. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  102620. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  102621. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102622. }
  102623. gazer._currentMeshSelected = null;
  102624. if (gazer._teleportationRequestInitiated) {
  102625. this._moveTeleportationSelectorTo(hit, gazer, ray);
  102626. }
  102627. return;
  102628. }
  102629. // If not, we're in a selection scenario
  102630. //this._teleportationAllowed = false;
  102631. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  102632. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  102633. this.onNewMeshPicked.notifyObservers(hit);
  102634. gazer._currentMeshSelected = hit.pickedMesh;
  102635. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  102636. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  102637. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  102638. gazer._isActionableMesh = true;
  102639. }
  102640. else {
  102641. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102642. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102643. gazer._isActionableMesh = false;
  102644. }
  102645. try {
  102646. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  102647. }
  102648. catch (err) {
  102649. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  102650. }
  102651. }
  102652. else {
  102653. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102654. gazer._currentMeshSelected = null;
  102655. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102656. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102657. }
  102658. }
  102659. }
  102660. else {
  102661. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102662. gazer._currentMeshSelected = null;
  102663. //this._teleportationAllowed = false;
  102664. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102665. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102666. }
  102667. };
  102668. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  102669. if (mesh) {
  102670. this.onSelectedMeshUnselected.notifyObservers(mesh);
  102671. }
  102672. };
  102673. /**
  102674. * Sets the color of the laser ray from the vr controllers.
  102675. * @param color new color for the ray.
  102676. */
  102677. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  102678. if (this._leftController) {
  102679. this._leftController._setLaserPointerColor(color);
  102680. }
  102681. if (this._rightController) {
  102682. this._rightController._setLaserPointerColor(color);
  102683. }
  102684. };
  102685. /**
  102686. * Sets the color of the ray from the vr headsets gaze.
  102687. * @param color new color for the ray.
  102688. */
  102689. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  102690. if (!this._cameraGazer._gazeTracker.material) {
  102691. return;
  102692. }
  102693. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  102694. if (this._leftController) {
  102695. this._leftController._gazeTracker.material.emissiveColor = color;
  102696. }
  102697. if (this._rightController) {
  102698. this._rightController._gazeTracker.material.emissiveColor = color;
  102699. }
  102700. };
  102701. /**
  102702. * Exits VR and disposes of the vr experience helper
  102703. */
  102704. VRExperienceHelper.prototype.dispose = function () {
  102705. if (this.isInVRMode) {
  102706. this.exitVR();
  102707. }
  102708. if (this._postProcessMove) {
  102709. this._postProcessMove.dispose();
  102710. }
  102711. if (this._webVRCamera) {
  102712. this._webVRCamera.dispose();
  102713. }
  102714. if (this._vrDeviceOrientationCamera) {
  102715. this._vrDeviceOrientationCamera.dispose();
  102716. }
  102717. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  102718. document.body.removeChild(this._btnVR);
  102719. }
  102720. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  102721. this._deviceOrientationCamera.dispose();
  102722. }
  102723. if (this._cameraGazer) {
  102724. this._cameraGazer.dispose();
  102725. }
  102726. if (this._leftController) {
  102727. this._leftController.dispose();
  102728. }
  102729. if (this._rightController) {
  102730. this._rightController.dispose();
  102731. }
  102732. if (this._teleportationTarget) {
  102733. this._teleportationTarget.dispose();
  102734. }
  102735. this._floorMeshesCollection = [];
  102736. document.removeEventListener("keydown", this._onKeyDown);
  102737. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102738. window.removeEventListener("resize", this._onResize);
  102739. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  102740. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  102741. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  102742. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  102743. document.onmsfullscreenchange = null;
  102744. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  102745. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  102746. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  102747. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102748. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  102749. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  102750. this._scene.unregisterBeforeRender(this.beforeRender);
  102751. };
  102752. /**
  102753. * Gets the name of the VRExperienceHelper class
  102754. * @returns "VRExperienceHelper"
  102755. */
  102756. VRExperienceHelper.prototype.getClassName = function () {
  102757. return "VRExperienceHelper";
  102758. };
  102759. return VRExperienceHelper;
  102760. }());
  102761. BABYLON.VRExperienceHelper = VRExperienceHelper;
  102762. })(BABYLON || (BABYLON = {}));
  102763. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  102764. // Mainly based on these 2 articles :
  102765. // 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
  102766. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  102767. var BABYLON;
  102768. (function (BABYLON) {
  102769. /**
  102770. * Defines the potential axis of a Joystick
  102771. */
  102772. var JoystickAxis;
  102773. (function (JoystickAxis) {
  102774. /** X axis */
  102775. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  102776. /** Y axis */
  102777. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  102778. /** Z axis */
  102779. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  102780. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  102781. /**
  102782. * Class used to define virtual joystick (used in touch mode)
  102783. */
  102784. var VirtualJoystick = /** @class */ (function () {
  102785. /**
  102786. * Creates a new virtual joystick
  102787. * @param leftJoystick defines that the joystick is for left hand (false by default)
  102788. */
  102789. function VirtualJoystick(leftJoystick) {
  102790. var _this = this;
  102791. if (leftJoystick) {
  102792. this._leftJoystick = true;
  102793. }
  102794. else {
  102795. this._leftJoystick = false;
  102796. }
  102797. VirtualJoystick._globalJoystickIndex++;
  102798. // By default left & right arrow keys are moving the X
  102799. // and up & down keys are moving the Y
  102800. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102801. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102802. this.reverseLeftRight = false;
  102803. this.reverseUpDown = false;
  102804. // collections of pointers
  102805. this._touches = new BABYLON.StringDictionary();
  102806. this.deltaPosition = BABYLON.Vector3.Zero();
  102807. this._joystickSensibility = 25;
  102808. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102809. this._onResize = function (evt) {
  102810. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102811. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102812. if (VirtualJoystick.vjCanvas) {
  102813. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  102814. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  102815. }
  102816. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  102817. };
  102818. // injecting a canvas element on top of the canvas 3D game
  102819. if (!VirtualJoystick.vjCanvas) {
  102820. window.addEventListener("resize", this._onResize, false);
  102821. VirtualJoystick.vjCanvas = document.createElement("canvas");
  102822. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102823. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102824. VirtualJoystick.vjCanvas.width = window.innerWidth;
  102825. VirtualJoystick.vjCanvas.height = window.innerHeight;
  102826. VirtualJoystick.vjCanvas.style.width = "100%";
  102827. VirtualJoystick.vjCanvas.style.height = "100%";
  102828. VirtualJoystick.vjCanvas.style.position = "absolute";
  102829. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  102830. VirtualJoystick.vjCanvas.style.top = "0px";
  102831. VirtualJoystick.vjCanvas.style.left = "0px";
  102832. VirtualJoystick.vjCanvas.style.zIndex = "5";
  102833. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  102834. // Support for jQuery PEP polyfill
  102835. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  102836. var context = VirtualJoystick.vjCanvas.getContext('2d');
  102837. if (!context) {
  102838. throw new Error("Unable to create canvas for virtual joystick");
  102839. }
  102840. VirtualJoystick.vjCanvasContext = context;
  102841. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  102842. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  102843. document.body.appendChild(VirtualJoystick.vjCanvas);
  102844. }
  102845. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  102846. this.pressed = false;
  102847. // default joystick color
  102848. this._joystickColor = "cyan";
  102849. this._joystickPointerID = -1;
  102850. // current joystick position
  102851. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  102852. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  102853. // origin joystick position
  102854. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  102855. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  102856. this._onPointerDownHandlerRef = function (evt) {
  102857. _this._onPointerDown(evt);
  102858. };
  102859. this._onPointerMoveHandlerRef = function (evt) {
  102860. _this._onPointerMove(evt);
  102861. };
  102862. this._onPointerUpHandlerRef = function (evt) {
  102863. _this._onPointerUp(evt);
  102864. };
  102865. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  102866. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  102867. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  102868. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  102869. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  102870. evt.preventDefault(); // Disables system menu
  102871. }, false);
  102872. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  102873. }
  102874. /**
  102875. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  102876. * @param newJoystickSensibility defines the new sensibility
  102877. */
  102878. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  102879. this._joystickSensibility = newJoystickSensibility;
  102880. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102881. };
  102882. VirtualJoystick.prototype._onPointerDown = function (e) {
  102883. var positionOnScreenCondition;
  102884. e.preventDefault();
  102885. if (this._leftJoystick === true) {
  102886. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  102887. }
  102888. else {
  102889. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  102890. }
  102891. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  102892. // First contact will be dedicated to the virtual joystick
  102893. this._joystickPointerID = e.pointerId;
  102894. this._joystickPointerStartPos.x = e.clientX;
  102895. this._joystickPointerStartPos.y = e.clientY;
  102896. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  102897. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  102898. this._deltaJoystickVector.x = 0;
  102899. this._deltaJoystickVector.y = 0;
  102900. this.pressed = true;
  102901. this._touches.add(e.pointerId.toString(), e);
  102902. }
  102903. else {
  102904. // You can only trigger the action buttons with a joystick declared
  102905. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  102906. this._action();
  102907. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  102908. }
  102909. }
  102910. };
  102911. VirtualJoystick.prototype._onPointerMove = function (e) {
  102912. // If the current pointer is the one associated to the joystick (first touch contact)
  102913. if (this._joystickPointerID == e.pointerId) {
  102914. this._joystickPointerPos.x = e.clientX;
  102915. this._joystickPointerPos.y = e.clientY;
  102916. this._deltaJoystickVector = this._joystickPointerPos.clone();
  102917. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  102918. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  102919. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  102920. switch (this._axisTargetedByLeftAndRight) {
  102921. case JoystickAxis.X:
  102922. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  102923. break;
  102924. case JoystickAxis.Y:
  102925. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  102926. break;
  102927. case JoystickAxis.Z:
  102928. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  102929. break;
  102930. }
  102931. var directionUpDown = this.reverseUpDown ? 1 : -1;
  102932. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  102933. switch (this._axisTargetedByUpAndDown) {
  102934. case JoystickAxis.X:
  102935. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  102936. break;
  102937. case JoystickAxis.Y:
  102938. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  102939. break;
  102940. case JoystickAxis.Z:
  102941. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  102942. break;
  102943. }
  102944. }
  102945. else {
  102946. var data = this._touches.get(e.pointerId.toString());
  102947. if (data) {
  102948. data.x = e.clientX;
  102949. data.y = e.clientY;
  102950. }
  102951. }
  102952. };
  102953. VirtualJoystick.prototype._onPointerUp = function (e) {
  102954. if (this._joystickPointerID == e.pointerId) {
  102955. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  102956. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  102957. this._joystickPointerID = -1;
  102958. this.pressed = false;
  102959. }
  102960. else {
  102961. var touch = this._touches.get(e.pointerId.toString());
  102962. if (touch) {
  102963. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  102964. }
  102965. }
  102966. this._deltaJoystickVector.x = 0;
  102967. this._deltaJoystickVector.y = 0;
  102968. this._touches.remove(e.pointerId.toString());
  102969. };
  102970. /**
  102971. * Change the color of the virtual joystick
  102972. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  102973. */
  102974. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  102975. this._joystickColor = newColor;
  102976. };
  102977. /**
  102978. * Defines a callback to call when the joystick is touched
  102979. * @param action defines the callback
  102980. */
  102981. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  102982. this._action = action;
  102983. };
  102984. /**
  102985. * Defines which axis you'd like to control for left & right
  102986. * @param axis defines the axis to use
  102987. */
  102988. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  102989. switch (axis) {
  102990. case JoystickAxis.X:
  102991. case JoystickAxis.Y:
  102992. case JoystickAxis.Z:
  102993. this._axisTargetedByLeftAndRight = axis;
  102994. break;
  102995. default:
  102996. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102997. break;
  102998. }
  102999. };
  103000. /**
  103001. * Defines which axis you'd like to control for up & down
  103002. * @param axis defines the axis to use
  103003. */
  103004. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  103005. switch (axis) {
  103006. case JoystickAxis.X:
  103007. case JoystickAxis.Y:
  103008. case JoystickAxis.Z:
  103009. this._axisTargetedByUpAndDown = axis;
  103010. break;
  103011. default:
  103012. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  103013. break;
  103014. }
  103015. };
  103016. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  103017. var _this = this;
  103018. if (this.pressed) {
  103019. this._touches.forEach(function (key, touch) {
  103020. if (touch.pointerId === _this._joystickPointerID) {
  103021. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  103022. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  103023. VirtualJoystick.vjCanvasContext.beginPath();
  103024. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  103025. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103026. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  103027. VirtualJoystick.vjCanvasContext.stroke();
  103028. VirtualJoystick.vjCanvasContext.closePath();
  103029. VirtualJoystick.vjCanvasContext.beginPath();
  103030. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103031. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  103032. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  103033. VirtualJoystick.vjCanvasContext.stroke();
  103034. VirtualJoystick.vjCanvasContext.closePath();
  103035. VirtualJoystick.vjCanvasContext.beginPath();
  103036. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103037. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  103038. VirtualJoystick.vjCanvasContext.stroke();
  103039. VirtualJoystick.vjCanvasContext.closePath();
  103040. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  103041. }
  103042. else {
  103043. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  103044. VirtualJoystick.vjCanvasContext.beginPath();
  103045. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  103046. VirtualJoystick.vjCanvasContext.beginPath();
  103047. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  103048. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  103049. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  103050. VirtualJoystick.vjCanvasContext.stroke();
  103051. VirtualJoystick.vjCanvasContext.closePath();
  103052. touch.prevX = touch.x;
  103053. touch.prevY = touch.y;
  103054. }
  103055. ;
  103056. });
  103057. }
  103058. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  103059. };
  103060. /**
  103061. * Release internal HTML canvas
  103062. */
  103063. VirtualJoystick.prototype.releaseCanvas = function () {
  103064. if (VirtualJoystick.vjCanvas) {
  103065. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  103066. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  103067. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  103068. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  103069. window.removeEventListener("resize", this._onResize);
  103070. document.body.removeChild(VirtualJoystick.vjCanvas);
  103071. VirtualJoystick.vjCanvas = null;
  103072. }
  103073. };
  103074. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  103075. VirtualJoystick._globalJoystickIndex = 0;
  103076. return VirtualJoystick;
  103077. }());
  103078. BABYLON.VirtualJoystick = VirtualJoystick;
  103079. })(BABYLON || (BABYLON = {}));
  103080. //# sourceMappingURL=babylon.virtualJoystick.js.map
  103081. var BABYLON;
  103082. (function (BABYLON) {
  103083. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  103084. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  103085. });
  103086. /**
  103087. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  103088. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  103089. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  103090. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  103091. */
  103092. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  103093. __extends(VirtualJoysticksCamera, _super);
  103094. /**
  103095. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  103096. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  103097. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  103098. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  103099. * @param name Define the name of the camera in the scene
  103100. * @param position Define the start position of the camera in the scene
  103101. * @param scene Define the scene the camera belongs to
  103102. */
  103103. function VirtualJoysticksCamera(name, position, scene) {
  103104. var _this = _super.call(this, name, position, scene) || this;
  103105. _this.inputs.addVirtualJoystick();
  103106. return _this;
  103107. }
  103108. /**
  103109. * Gets the current object class name.
  103110. * @return the class name
  103111. */
  103112. VirtualJoysticksCamera.prototype.getClassName = function () {
  103113. return "VirtualJoysticksCamera";
  103114. };
  103115. return VirtualJoysticksCamera;
  103116. }(BABYLON.FreeCamera));
  103117. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  103118. })(BABYLON || (BABYLON = {}));
  103119. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  103120. var BABYLON;
  103121. (function (BABYLON) {
  103122. /**
  103123. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  103124. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103125. */
  103126. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  103127. function FreeCameraVirtualJoystickInput() {
  103128. }
  103129. /**
  103130. * Gets the left stick of the virtual joystick.
  103131. * @returns The virtual Joystick
  103132. */
  103133. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  103134. return this._leftjoystick;
  103135. };
  103136. /**
  103137. * Gets the right stick of the virtual joystick.
  103138. * @returns The virtual Joystick
  103139. */
  103140. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  103141. return this._rightjoystick;
  103142. };
  103143. /**
  103144. * Update the current camera state depending on the inputs that have been used this frame.
  103145. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103146. */
  103147. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  103148. if (this._leftjoystick) {
  103149. var camera = this.camera;
  103150. var speed = camera._computeLocalCameraSpeed() * 50;
  103151. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  103152. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  103153. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  103154. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  103155. if (!this._leftjoystick.pressed) {
  103156. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  103157. }
  103158. if (!this._rightjoystick.pressed) {
  103159. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  103160. }
  103161. }
  103162. };
  103163. /**
  103164. * Attach the input controls to a specific dom element to get the input from.
  103165. * @param element Defines the element the controls should be listened from
  103166. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103167. */
  103168. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  103169. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  103170. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  103171. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  103172. this._leftjoystick.setJoystickSensibility(0.15);
  103173. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  103174. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  103175. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  103176. this._rightjoystick.reverseUpDown = true;
  103177. this._rightjoystick.setJoystickSensibility(0.05);
  103178. this._rightjoystick.setJoystickColor("yellow");
  103179. };
  103180. /**
  103181. * Detach the current controls from the specified dom element.
  103182. * @param element Defines the element to stop listening the inputs from
  103183. */
  103184. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  103185. this._leftjoystick.releaseCanvas();
  103186. this._rightjoystick.releaseCanvas();
  103187. };
  103188. /**
  103189. * Gets the class name of the current intput.
  103190. * @returns the class name
  103191. */
  103192. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  103193. return "FreeCameraVirtualJoystickInput";
  103194. };
  103195. /**
  103196. * Get the friendly name associated with the input class.
  103197. * @returns the input friendly name
  103198. */
  103199. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  103200. return "virtualJoystick";
  103201. };
  103202. return FreeCameraVirtualJoystickInput;
  103203. }());
  103204. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  103205. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  103206. })(BABYLON || (BABYLON = {}));
  103207. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  103208. var BABYLON;
  103209. (function (BABYLON) {
  103210. /**
  103211. * Class used to specify simplification options
  103212. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  103213. */
  103214. var SimplificationSettings = /** @class */ (function () {
  103215. /**
  103216. * Creates a SimplificationSettings
  103217. * @param quality expected quality
  103218. * @param distance distance when this optimized version should be used
  103219. * @param optimizeMesh already optimized mesh
  103220. */
  103221. function SimplificationSettings(
  103222. /** expected quality */
  103223. quality,
  103224. /** distance when this optimized version should be used */
  103225. distance,
  103226. /** already optimized mesh */
  103227. optimizeMesh) {
  103228. this.quality = quality;
  103229. this.distance = distance;
  103230. this.optimizeMesh = optimizeMesh;
  103231. }
  103232. return SimplificationSettings;
  103233. }());
  103234. BABYLON.SimplificationSettings = SimplificationSettings;
  103235. /**
  103236. * Queue used to order the simplification tasks
  103237. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  103238. */
  103239. var SimplificationQueue = /** @class */ (function () {
  103240. /**
  103241. * Creates a new queue
  103242. */
  103243. function SimplificationQueue() {
  103244. this.running = false;
  103245. this._simplificationArray = [];
  103246. }
  103247. /**
  103248. * Adds a new simplification task
  103249. * @param task defines a task to add
  103250. */
  103251. SimplificationQueue.prototype.addTask = function (task) {
  103252. this._simplificationArray.push(task);
  103253. };
  103254. /**
  103255. * Execute next task
  103256. */
  103257. SimplificationQueue.prototype.executeNext = function () {
  103258. var task = this._simplificationArray.pop();
  103259. if (task) {
  103260. this.running = true;
  103261. this.runSimplification(task);
  103262. }
  103263. else {
  103264. this.running = false;
  103265. }
  103266. };
  103267. /**
  103268. * Execute a simplification task
  103269. * @param task defines the task to run
  103270. */
  103271. SimplificationQueue.prototype.runSimplification = function (task) {
  103272. var _this = this;
  103273. if (task.parallelProcessing) {
  103274. //parallel simplifier
  103275. task.settings.forEach(function (setting) {
  103276. var simplifier = _this.getSimplifier(task);
  103277. simplifier.simplify(setting, function (newMesh) {
  103278. task.mesh.addLODLevel(setting.distance, newMesh);
  103279. newMesh.isVisible = true;
  103280. //check if it is the last
  103281. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  103282. //all done, run the success callback.
  103283. task.successCallback();
  103284. }
  103285. _this.executeNext();
  103286. });
  103287. });
  103288. }
  103289. else {
  103290. //single simplifier.
  103291. var simplifier = this.getSimplifier(task);
  103292. var runDecimation = function (setting, callback) {
  103293. simplifier.simplify(setting, function (newMesh) {
  103294. task.mesh.addLODLevel(setting.distance, newMesh);
  103295. newMesh.isVisible = true;
  103296. //run the next quality level
  103297. callback();
  103298. });
  103299. };
  103300. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  103301. runDecimation(task.settings[loop.index], function () {
  103302. loop.executeNext();
  103303. });
  103304. }, function () {
  103305. //execution ended, run the success callback.
  103306. if (task.successCallback) {
  103307. task.successCallback();
  103308. }
  103309. _this.executeNext();
  103310. });
  103311. }
  103312. };
  103313. SimplificationQueue.prototype.getSimplifier = function (task) {
  103314. switch (task.simplificationType) {
  103315. case SimplificationType.QUADRATIC:
  103316. default:
  103317. return new QuadraticErrorSimplification(task.mesh);
  103318. }
  103319. };
  103320. return SimplificationQueue;
  103321. }());
  103322. BABYLON.SimplificationQueue = SimplificationQueue;
  103323. /**
  103324. * The implemented types of simplification
  103325. * At the moment only Quadratic Error Decimation is implemented
  103326. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  103327. */
  103328. var SimplificationType;
  103329. (function (SimplificationType) {
  103330. /** Quadratic error decimation */
  103331. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  103332. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  103333. var DecimationTriangle = /** @class */ (function () {
  103334. function DecimationTriangle(vertices) {
  103335. this.vertices = vertices;
  103336. this.error = new Array(4);
  103337. this.deleted = false;
  103338. this.isDirty = false;
  103339. this.deletePending = false;
  103340. this.borderFactor = 0;
  103341. }
  103342. return DecimationTriangle;
  103343. }());
  103344. var DecimationVertex = /** @class */ (function () {
  103345. function DecimationVertex(position, id) {
  103346. this.position = position;
  103347. this.id = id;
  103348. this.isBorder = true;
  103349. this.q = new QuadraticMatrix();
  103350. this.triangleCount = 0;
  103351. this.triangleStart = 0;
  103352. this.originalOffsets = [];
  103353. }
  103354. DecimationVertex.prototype.updatePosition = function (newPosition) {
  103355. this.position.copyFrom(newPosition);
  103356. };
  103357. return DecimationVertex;
  103358. }());
  103359. var QuadraticMatrix = /** @class */ (function () {
  103360. function QuadraticMatrix(data) {
  103361. this.data = new Array(10);
  103362. for (var i = 0; i < 10; ++i) {
  103363. if (data && data[i]) {
  103364. this.data[i] = data[i];
  103365. }
  103366. else {
  103367. this.data[i] = 0;
  103368. }
  103369. }
  103370. }
  103371. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  103372. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  103373. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  103374. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  103375. return det;
  103376. };
  103377. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  103378. for (var i = 0; i < 10; ++i) {
  103379. this.data[i] += matrix.data[i];
  103380. }
  103381. };
  103382. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  103383. for (var i = 0; i < 10; ++i) {
  103384. this.data[i] += data[i];
  103385. }
  103386. };
  103387. QuadraticMatrix.prototype.add = function (matrix) {
  103388. var m = new QuadraticMatrix();
  103389. for (var i = 0; i < 10; ++i) {
  103390. m.data[i] = this.data[i] + matrix.data[i];
  103391. }
  103392. return m;
  103393. };
  103394. QuadraticMatrix.FromData = function (a, b, c, d) {
  103395. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  103396. };
  103397. //returning an array to avoid garbage collection
  103398. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  103399. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  103400. };
  103401. return QuadraticMatrix;
  103402. }());
  103403. var Reference = /** @class */ (function () {
  103404. function Reference(vertexId, triangleId) {
  103405. this.vertexId = vertexId;
  103406. this.triangleId = triangleId;
  103407. }
  103408. return Reference;
  103409. }());
  103410. /**
  103411. * An implementation of the Quadratic Error simplification algorithm.
  103412. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  103413. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  103414. * @author RaananW
  103415. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  103416. */
  103417. var QuadraticErrorSimplification = /** @class */ (function () {
  103418. function QuadraticErrorSimplification(_mesh) {
  103419. this._mesh = _mesh;
  103420. this.syncIterations = 5000;
  103421. this.aggressiveness = 7;
  103422. this.decimationIterations = 100;
  103423. this.boundingBoxEpsilon = BABYLON.Epsilon;
  103424. }
  103425. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  103426. var _this = this;
  103427. this.initDecimatedMesh();
  103428. //iterating through the submeshes array, one after the other.
  103429. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  103430. _this.initWithMesh(loop.index, function () {
  103431. _this.runDecimation(settings, loop.index, function () {
  103432. loop.executeNext();
  103433. });
  103434. }, settings.optimizeMesh);
  103435. }, function () {
  103436. setTimeout(function () {
  103437. successCallback(_this._reconstructedMesh);
  103438. }, 0);
  103439. });
  103440. };
  103441. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  103442. var _this = this;
  103443. var targetCount = ~~(this.triangles.length * settings.quality);
  103444. var deletedTriangles = 0;
  103445. var triangleCount = this.triangles.length;
  103446. var iterationFunction = function (iteration, callback) {
  103447. setTimeout(function () {
  103448. if (iteration % 5 === 0) {
  103449. _this.updateMesh(iteration === 0);
  103450. }
  103451. for (var i = 0; i < _this.triangles.length; ++i) {
  103452. _this.triangles[i].isDirty = false;
  103453. }
  103454. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  103455. var trianglesIterator = function (i) {
  103456. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  103457. var t = _this.triangles[tIdx];
  103458. if (!t)
  103459. return;
  103460. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  103461. return;
  103462. }
  103463. for (var j = 0; j < 3; ++j) {
  103464. if (t.error[j] < threshold) {
  103465. var deleted0 = [];
  103466. var deleted1 = [];
  103467. var v0 = t.vertices[j];
  103468. var v1 = t.vertices[(j + 1) % 3];
  103469. if (v0.isBorder || v1.isBorder)
  103470. continue;
  103471. var p = BABYLON.Vector3.Zero();
  103472. var n = BABYLON.Vector3.Zero();
  103473. var uv = BABYLON.Vector2.Zero();
  103474. var color = new BABYLON.Color4(0, 0, 0, 1);
  103475. _this.calculateError(v0, v1, p, n, uv, color);
  103476. var delTr = new Array();
  103477. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  103478. continue;
  103479. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  103480. continue;
  103481. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  103482. continue;
  103483. var uniqueArray = new Array();
  103484. delTr.forEach(function (deletedT) {
  103485. if (uniqueArray.indexOf(deletedT) === -1) {
  103486. deletedT.deletePending = true;
  103487. uniqueArray.push(deletedT);
  103488. }
  103489. });
  103490. if (uniqueArray.length % 2 !== 0) {
  103491. continue;
  103492. }
  103493. v0.q = v1.q.add(v0.q);
  103494. v0.updatePosition(p);
  103495. var tStart = _this.references.length;
  103496. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  103497. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  103498. var tCount = _this.references.length - tStart;
  103499. if (tCount <= v0.triangleCount) {
  103500. if (tCount) {
  103501. for (var c = 0; c < tCount; c++) {
  103502. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  103503. }
  103504. }
  103505. }
  103506. else {
  103507. v0.triangleStart = tStart;
  103508. }
  103509. v0.triangleCount = tCount;
  103510. break;
  103511. }
  103512. }
  103513. };
  103514. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  103515. }, 0);
  103516. };
  103517. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  103518. if (triangleCount - deletedTriangles <= targetCount)
  103519. loop.breakLoop();
  103520. else {
  103521. iterationFunction(loop.index, function () {
  103522. loop.executeNext();
  103523. });
  103524. }
  103525. }, function () {
  103526. setTimeout(function () {
  103527. //reconstruct this part of the mesh
  103528. _this.reconstructMesh(submeshIndex);
  103529. successCallback();
  103530. }, 0);
  103531. });
  103532. };
  103533. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  103534. var _this = this;
  103535. this.vertices = [];
  103536. this.triangles = [];
  103537. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  103538. var indices = this._mesh.getIndices();
  103539. var submesh = this._mesh.subMeshes[submeshIndex];
  103540. var findInVertices = function (positionToSearch) {
  103541. if (optimizeMesh) {
  103542. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  103543. if (_this.vertices[ii].position.equals(positionToSearch)) {
  103544. return _this.vertices[ii];
  103545. }
  103546. }
  103547. }
  103548. return null;
  103549. };
  103550. var vertexReferences = [];
  103551. var vertexInit = function (i) {
  103552. if (!positionData) {
  103553. return;
  103554. }
  103555. var offset = i + submesh.verticesStart;
  103556. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  103557. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  103558. vertex.originalOffsets.push(offset);
  103559. if (vertex.id === _this.vertices.length) {
  103560. _this.vertices.push(vertex);
  103561. }
  103562. vertexReferences.push(vertex.id);
  103563. };
  103564. //var totalVertices = mesh.getTotalVertices();
  103565. var totalVertices = submesh.verticesCount;
  103566. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  103567. var indicesInit = function (i) {
  103568. if (!indices) {
  103569. return;
  103570. }
  103571. var offset = (submesh.indexStart / 3) + i;
  103572. var pos = (offset * 3);
  103573. var i0 = indices[pos + 0];
  103574. var i1 = indices[pos + 1];
  103575. var i2 = indices[pos + 2];
  103576. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  103577. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  103578. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  103579. var triangle = new DecimationTriangle([v0, v1, v2]);
  103580. triangle.originalOffset = pos;
  103581. _this.triangles.push(triangle);
  103582. };
  103583. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  103584. _this.init(callback);
  103585. });
  103586. });
  103587. };
  103588. QuadraticErrorSimplification.prototype.init = function (callback) {
  103589. var _this = this;
  103590. var triangleInit1 = function (i) {
  103591. var t = _this.triangles[i];
  103592. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  103593. for (var j = 0; j < 3; j++) {
  103594. 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))));
  103595. }
  103596. };
  103597. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  103598. var triangleInit2 = function (i) {
  103599. var t = _this.triangles[i];
  103600. for (var j = 0; j < 3; ++j) {
  103601. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  103602. }
  103603. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  103604. };
  103605. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  103606. callback();
  103607. });
  103608. });
  103609. };
  103610. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  103611. var newTriangles = [];
  103612. var i;
  103613. for (i = 0; i < this.vertices.length; ++i) {
  103614. this.vertices[i].triangleCount = 0;
  103615. }
  103616. var t;
  103617. var j;
  103618. for (i = 0; i < this.triangles.length; ++i) {
  103619. if (!this.triangles[i].deleted) {
  103620. t = this.triangles[i];
  103621. for (j = 0; j < 3; ++j) {
  103622. t.vertices[j].triangleCount = 1;
  103623. }
  103624. newTriangles.push(t);
  103625. }
  103626. }
  103627. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  103628. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  103629. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  103630. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  103631. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  103632. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  103633. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  103634. var vertexCount = 0;
  103635. for (i = 0; i < this.vertices.length; ++i) {
  103636. var vertex = this.vertices[i];
  103637. vertex.id = vertexCount;
  103638. if (vertex.triangleCount) {
  103639. vertex.originalOffsets.forEach(function (originalOffset) {
  103640. if (!normalData) {
  103641. return;
  103642. }
  103643. newPositionData.push(vertex.position.x);
  103644. newPositionData.push(vertex.position.y);
  103645. newPositionData.push(vertex.position.z);
  103646. newNormalData.push(normalData[originalOffset * 3]);
  103647. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  103648. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  103649. if (uvs && uvs.length) {
  103650. newUVsData.push(uvs[(originalOffset * 2)]);
  103651. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  103652. }
  103653. else if (colorsData && colorsData.length) {
  103654. newColorsData.push(colorsData[(originalOffset * 4)]);
  103655. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  103656. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  103657. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  103658. }
  103659. ++vertexCount;
  103660. });
  103661. }
  103662. }
  103663. var startingIndex = this._reconstructedMesh.getTotalIndices();
  103664. var startingVertex = this._reconstructedMesh.getTotalVertices();
  103665. var submeshesArray = this._reconstructedMesh.subMeshes;
  103666. this._reconstructedMesh.subMeshes = [];
  103667. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  103668. var originalIndices = this._mesh.getIndices();
  103669. for (i = 0; i < newTriangles.length; ++i) {
  103670. t = newTriangles[i]; //now get the new referencing point for each vertex
  103671. [0, 1, 2].forEach(function (idx) {
  103672. var id = originalIndices[t.originalOffset + idx];
  103673. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  103674. if (offset < 0)
  103675. offset = 0;
  103676. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  103677. });
  103678. }
  103679. //overwriting the old vertex buffers and indices.
  103680. this._reconstructedMesh.setIndices(newIndicesArray);
  103681. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  103682. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  103683. if (newUVsData.length > 0)
  103684. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  103685. if (newColorsData.length > 0)
  103686. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  103687. //create submesh
  103688. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  103689. if (submeshIndex > 0) {
  103690. this._reconstructedMesh.subMeshes = [];
  103691. submeshesArray.forEach(function (submesh) {
  103692. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  103693. });
  103694. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  103695. }
  103696. };
  103697. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  103698. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  103699. this._reconstructedMesh.material = this._mesh.material;
  103700. this._reconstructedMesh.parent = this._mesh.parent;
  103701. this._reconstructedMesh.isVisible = false;
  103702. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  103703. };
  103704. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  103705. for (var i = 0; i < vertex1.triangleCount; ++i) {
  103706. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  103707. if (t.deleted)
  103708. continue;
  103709. var s = this.references[vertex1.triangleStart + i].vertexId;
  103710. var v1 = t.vertices[(s + 1) % 3];
  103711. var v2 = t.vertices[(s + 2) % 3];
  103712. if ((v1 === vertex2 || v2 === vertex2)) {
  103713. deletedArray[i] = true;
  103714. delTr.push(t);
  103715. continue;
  103716. }
  103717. var d1 = v1.position.subtract(point);
  103718. d1 = d1.normalize();
  103719. var d2 = v2.position.subtract(point);
  103720. d2 = d2.normalize();
  103721. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  103722. return true;
  103723. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  103724. deletedArray[i] = false;
  103725. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  103726. return true;
  103727. }
  103728. return false;
  103729. };
  103730. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  103731. var newDeleted = deletedTriangles;
  103732. for (var i = 0; i < vertex.triangleCount; ++i) {
  103733. var ref = this.references[vertex.triangleStart + i];
  103734. var t = this.triangles[ref.triangleId];
  103735. if (t.deleted)
  103736. continue;
  103737. if (deletedArray[i] && t.deletePending) {
  103738. t.deleted = true;
  103739. newDeleted++;
  103740. continue;
  103741. }
  103742. t.vertices[ref.vertexId] = origVertex;
  103743. t.isDirty = true;
  103744. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  103745. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  103746. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  103747. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  103748. this.references.push(ref);
  103749. }
  103750. return newDeleted;
  103751. };
  103752. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  103753. for (var i = 0; i < this.vertices.length; ++i) {
  103754. var vCount = [];
  103755. var vId = [];
  103756. var v = this.vertices[i];
  103757. var j;
  103758. for (j = 0; j < v.triangleCount; ++j) {
  103759. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  103760. for (var ii = 0; ii < 3; ii++) {
  103761. var ofs = 0;
  103762. var vv = triangle.vertices[ii];
  103763. while (ofs < vCount.length) {
  103764. if (vId[ofs] === vv.id)
  103765. break;
  103766. ++ofs;
  103767. }
  103768. if (ofs === vCount.length) {
  103769. vCount.push(1);
  103770. vId.push(vv.id);
  103771. }
  103772. else {
  103773. vCount[ofs]++;
  103774. }
  103775. }
  103776. }
  103777. for (j = 0; j < vCount.length; ++j) {
  103778. if (vCount[j] === 1) {
  103779. this.vertices[vId[j]].isBorder = true;
  103780. }
  103781. else {
  103782. this.vertices[vId[j]].isBorder = false;
  103783. }
  103784. }
  103785. }
  103786. };
  103787. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  103788. if (identifyBorders === void 0) { identifyBorders = false; }
  103789. var i;
  103790. if (!identifyBorders) {
  103791. var newTrianglesVector = [];
  103792. for (i = 0; i < this.triangles.length; ++i) {
  103793. if (!this.triangles[i].deleted) {
  103794. newTrianglesVector.push(this.triangles[i]);
  103795. }
  103796. }
  103797. this.triangles = newTrianglesVector;
  103798. }
  103799. for (i = 0; i < this.vertices.length; ++i) {
  103800. this.vertices[i].triangleCount = 0;
  103801. this.vertices[i].triangleStart = 0;
  103802. }
  103803. var t;
  103804. var j;
  103805. var v;
  103806. for (i = 0; i < this.triangles.length; ++i) {
  103807. t = this.triangles[i];
  103808. for (j = 0; j < 3; ++j) {
  103809. v = t.vertices[j];
  103810. v.triangleCount++;
  103811. }
  103812. }
  103813. var tStart = 0;
  103814. for (i = 0; i < this.vertices.length; ++i) {
  103815. this.vertices[i].triangleStart = tStart;
  103816. tStart += this.vertices[i].triangleCount;
  103817. this.vertices[i].triangleCount = 0;
  103818. }
  103819. var newReferences = new Array(this.triangles.length * 3);
  103820. for (i = 0; i < this.triangles.length; ++i) {
  103821. t = this.triangles[i];
  103822. for (j = 0; j < 3; ++j) {
  103823. v = t.vertices[j];
  103824. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  103825. v.triangleCount++;
  103826. }
  103827. }
  103828. this.references = newReferences;
  103829. if (identifyBorders) {
  103830. this.identifyBorder();
  103831. }
  103832. };
  103833. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  103834. var x = point.x;
  103835. var y = point.y;
  103836. var z = point.z;
  103837. 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
  103838. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  103839. };
  103840. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  103841. var q = vertex1.q.add(vertex2.q);
  103842. var border = vertex1.isBorder && vertex2.isBorder;
  103843. var error = 0;
  103844. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  103845. if (qDet !== 0 && !border) {
  103846. if (!pointResult) {
  103847. pointResult = BABYLON.Vector3.Zero();
  103848. }
  103849. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  103850. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  103851. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  103852. error = this.vertexError(q, pointResult);
  103853. }
  103854. else {
  103855. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  103856. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  103857. var error1 = this.vertexError(q, vertex1.position);
  103858. var error2 = this.vertexError(q, vertex2.position);
  103859. var error3 = this.vertexError(q, p3);
  103860. error = Math.min(error1, error2, error3);
  103861. if (error === error1) {
  103862. if (pointResult) {
  103863. pointResult.copyFrom(vertex1.position);
  103864. }
  103865. }
  103866. else if (error === error2) {
  103867. if (pointResult) {
  103868. pointResult.copyFrom(vertex2.position);
  103869. }
  103870. }
  103871. else {
  103872. if (pointResult) {
  103873. pointResult.copyFrom(p3);
  103874. }
  103875. }
  103876. }
  103877. return error;
  103878. };
  103879. return QuadraticErrorSimplification;
  103880. }());
  103881. })(BABYLON || (BABYLON = {}));
  103882. //# sourceMappingURL=babylon.meshSimplification.js.map
  103883. var BABYLON;
  103884. (function (BABYLON) {
  103885. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  103886. get: function () {
  103887. if (!this._simplificationQueue) {
  103888. this._simplificationQueue = new BABYLON.SimplificationQueue();
  103889. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  103890. if (!component) {
  103891. component = new SimplicationQueueSceneComponent(this);
  103892. this._addComponent(component);
  103893. }
  103894. }
  103895. return this._simplificationQueue;
  103896. },
  103897. set: function (value) {
  103898. this._simplificationQueue = value;
  103899. },
  103900. enumerable: true,
  103901. configurable: true
  103902. });
  103903. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  103904. if (parallelProcessing === void 0) { parallelProcessing = true; }
  103905. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  103906. this.getScene().simplificationQueue.addTask({
  103907. settings: settings,
  103908. parallelProcessing: parallelProcessing,
  103909. mesh: this,
  103910. simplificationType: simplificationType,
  103911. successCallback: successCallback
  103912. });
  103913. return this;
  103914. };
  103915. /**
  103916. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  103917. * created in a scene
  103918. */
  103919. var SimplicationQueueSceneComponent = /** @class */ (function () {
  103920. /**
  103921. * Creates a new instance of the component for the given scene
  103922. * @param scene Defines the scene to register the component in
  103923. */
  103924. function SimplicationQueueSceneComponent(scene) {
  103925. /**
  103926. * The component name helpfull to identify the component in the list of scene components.
  103927. */
  103928. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  103929. this.scene = scene;
  103930. }
  103931. /**
  103932. * Registers the component in a given scene
  103933. */
  103934. SimplicationQueueSceneComponent.prototype.register = function () {
  103935. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  103936. };
  103937. /**
  103938. * Rebuilds the elements related to this component in case of
  103939. * context lost for instance.
  103940. */
  103941. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  103942. // Nothing to do for this component
  103943. };
  103944. /**
  103945. * Disposes the component and the associated ressources
  103946. */
  103947. SimplicationQueueSceneComponent.prototype.dispose = function () {
  103948. // Nothing to do for this component
  103949. };
  103950. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  103951. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  103952. this.scene._simplificationQueue.executeNext();
  103953. }
  103954. };
  103955. return SimplicationQueueSceneComponent;
  103956. }());
  103957. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  103958. })(BABYLON || (BABYLON = {}));
  103959. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  103960. var BABYLON;
  103961. (function (BABYLON) {
  103962. /**
  103963. * Class used to represent a specific level of detail of a mesh
  103964. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  103965. */
  103966. var MeshLODLevel = /** @class */ (function () {
  103967. /**
  103968. * Creates a new LOD level
  103969. * @param distance defines the distance where this level should star being displayed
  103970. * @param mesh defines the mesh to use to render this level
  103971. */
  103972. function MeshLODLevel(
  103973. /** Defines the distance where this level should star being displayed */
  103974. distance,
  103975. /** Defines the mesh to use to render this level */
  103976. mesh) {
  103977. this.distance = distance;
  103978. this.mesh = mesh;
  103979. }
  103980. return MeshLODLevel;
  103981. }());
  103982. BABYLON.MeshLODLevel = MeshLODLevel;
  103983. })(BABYLON || (BABYLON = {}));
  103984. //# sourceMappingURL=babylon.meshLODLevel.js.map
  103985. var BABYLON;
  103986. (function (BABYLON) {
  103987. /**
  103988. * Defines the root class used to create scene optimization to use with SceneOptimizer
  103989. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103990. */
  103991. var SceneOptimization = /** @class */ (function () {
  103992. /**
  103993. * Creates the SceneOptimization object
  103994. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103995. * @param desc defines the description associated with the optimization
  103996. */
  103997. function SceneOptimization(
  103998. /**
  103999. * Defines the priority of this optimization (0 by default which means first in the list)
  104000. */
  104001. priority) {
  104002. if (priority === void 0) { priority = 0; }
  104003. this.priority = priority;
  104004. }
  104005. /**
  104006. * Gets a string describing the action executed by the current optimization
  104007. * @returns description string
  104008. */
  104009. SceneOptimization.prototype.getDescription = function () {
  104010. return "";
  104011. };
  104012. /**
  104013. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104014. * @param scene defines the current scene where to apply this optimization
  104015. * @param optimizer defines the current optimizer
  104016. * @returns true if everything that can be done was applied
  104017. */
  104018. SceneOptimization.prototype.apply = function (scene, optimizer) {
  104019. return true;
  104020. };
  104021. ;
  104022. return SceneOptimization;
  104023. }());
  104024. BABYLON.SceneOptimization = SceneOptimization;
  104025. /**
  104026. * Defines an optimization used to reduce the size of render target textures
  104027. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104028. */
  104029. var TextureOptimization = /** @class */ (function (_super) {
  104030. __extends(TextureOptimization, _super);
  104031. /**
  104032. * Creates the TextureOptimization object
  104033. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104034. * @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
  104035. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  104036. */
  104037. function TextureOptimization(
  104038. /**
  104039. * Defines the priority of this optimization (0 by default which means first in the list)
  104040. */
  104041. priority,
  104042. /**
  104043. * 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
  104044. */
  104045. maximumSize,
  104046. /**
  104047. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  104048. */
  104049. step) {
  104050. if (priority === void 0) { priority = 0; }
  104051. if (maximumSize === void 0) { maximumSize = 1024; }
  104052. if (step === void 0) { step = 0.5; }
  104053. var _this = _super.call(this, priority) || this;
  104054. _this.priority = priority;
  104055. _this.maximumSize = maximumSize;
  104056. _this.step = step;
  104057. return _this;
  104058. }
  104059. /**
  104060. * Gets a string describing the action executed by the current optimization
  104061. * @returns description string
  104062. */
  104063. TextureOptimization.prototype.getDescription = function () {
  104064. return "Reducing render target texture size to " + this.maximumSize;
  104065. };
  104066. /**
  104067. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104068. * @param scene defines the current scene where to apply this optimization
  104069. * @param optimizer defines the current optimizer
  104070. * @returns true if everything that can be done was applied
  104071. */
  104072. TextureOptimization.prototype.apply = function (scene, optimizer) {
  104073. var allDone = true;
  104074. for (var index = 0; index < scene.textures.length; index++) {
  104075. var texture = scene.textures[index];
  104076. if (!texture.canRescale || texture.getContext) {
  104077. continue;
  104078. }
  104079. var currentSize = texture.getSize();
  104080. var maxDimension = Math.max(currentSize.width, currentSize.height);
  104081. if (maxDimension > this.maximumSize) {
  104082. texture.scale(this.step);
  104083. allDone = false;
  104084. }
  104085. }
  104086. return allDone;
  104087. };
  104088. return TextureOptimization;
  104089. }(SceneOptimization));
  104090. BABYLON.TextureOptimization = TextureOptimization;
  104091. /**
  104092. * Defines an optimization used to increase or decrease the rendering resolution
  104093. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104094. */
  104095. var HardwareScalingOptimization = /** @class */ (function (_super) {
  104096. __extends(HardwareScalingOptimization, _super);
  104097. /**
  104098. * Creates the HardwareScalingOptimization object
  104099. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104100. * @param maximumScale defines the maximum scale to use (2 by default)
  104101. * @param step defines the step to use between two passes (0.5 by default)
  104102. */
  104103. function HardwareScalingOptimization(
  104104. /**
  104105. * Defines the priority of this optimization (0 by default which means first in the list)
  104106. */
  104107. priority,
  104108. /**
  104109. * Defines the maximum scale to use (2 by default)
  104110. */
  104111. maximumScale,
  104112. /**
  104113. * Defines the step to use between two passes (0.5 by default)
  104114. */
  104115. step) {
  104116. if (priority === void 0) { priority = 0; }
  104117. if (maximumScale === void 0) { maximumScale = 2; }
  104118. if (step === void 0) { step = 0.25; }
  104119. var _this = _super.call(this, priority) || this;
  104120. _this.priority = priority;
  104121. _this.maximumScale = maximumScale;
  104122. _this.step = step;
  104123. _this._currentScale = -1;
  104124. _this._directionOffset = 1;
  104125. return _this;
  104126. }
  104127. /**
  104128. * Gets a string describing the action executed by the current optimization
  104129. * @return description string
  104130. */
  104131. HardwareScalingOptimization.prototype.getDescription = function () {
  104132. return "Setting hardware scaling level to " + this._currentScale;
  104133. };
  104134. /**
  104135. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104136. * @param scene defines the current scene where to apply this optimization
  104137. * @param optimizer defines the current optimizer
  104138. * @returns true if everything that can be done was applied
  104139. */
  104140. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  104141. if (this._currentScale === -1) {
  104142. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  104143. if (this._currentScale > this.maximumScale) {
  104144. this._directionOffset = -1;
  104145. }
  104146. }
  104147. this._currentScale += this._directionOffset * this.step;
  104148. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  104149. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  104150. };
  104151. ;
  104152. return HardwareScalingOptimization;
  104153. }(SceneOptimization));
  104154. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  104155. /**
  104156. * Defines an optimization used to remove shadows
  104157. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104158. */
  104159. var ShadowsOptimization = /** @class */ (function (_super) {
  104160. __extends(ShadowsOptimization, _super);
  104161. function ShadowsOptimization() {
  104162. return _super !== null && _super.apply(this, arguments) || this;
  104163. }
  104164. /**
  104165. * Gets a string describing the action executed by the current optimization
  104166. * @return description string
  104167. */
  104168. ShadowsOptimization.prototype.getDescription = function () {
  104169. return "Turning shadows on/off";
  104170. };
  104171. /**
  104172. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104173. * @param scene defines the current scene where to apply this optimization
  104174. * @param optimizer defines the current optimizer
  104175. * @returns true if everything that can be done was applied
  104176. */
  104177. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  104178. scene.shadowsEnabled = optimizer.isInImprovementMode;
  104179. return true;
  104180. };
  104181. ;
  104182. return ShadowsOptimization;
  104183. }(SceneOptimization));
  104184. BABYLON.ShadowsOptimization = ShadowsOptimization;
  104185. /**
  104186. * Defines an optimization used to turn post-processes off
  104187. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104188. */
  104189. var PostProcessesOptimization = /** @class */ (function (_super) {
  104190. __extends(PostProcessesOptimization, _super);
  104191. function PostProcessesOptimization() {
  104192. return _super !== null && _super.apply(this, arguments) || this;
  104193. }
  104194. /**
  104195. * Gets a string describing the action executed by the current optimization
  104196. * @return description string
  104197. */
  104198. PostProcessesOptimization.prototype.getDescription = function () {
  104199. return "Turning post-processes on/off";
  104200. };
  104201. /**
  104202. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104203. * @param scene defines the current scene where to apply this optimization
  104204. * @param optimizer defines the current optimizer
  104205. * @returns true if everything that can be done was applied
  104206. */
  104207. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  104208. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  104209. return true;
  104210. };
  104211. ;
  104212. return PostProcessesOptimization;
  104213. }(SceneOptimization));
  104214. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  104215. /**
  104216. * Defines an optimization used to turn lens flares off
  104217. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104218. */
  104219. var LensFlaresOptimization = /** @class */ (function (_super) {
  104220. __extends(LensFlaresOptimization, _super);
  104221. function LensFlaresOptimization() {
  104222. return _super !== null && _super.apply(this, arguments) || this;
  104223. }
  104224. /**
  104225. * Gets a string describing the action executed by the current optimization
  104226. * @return description string
  104227. */
  104228. LensFlaresOptimization.prototype.getDescription = function () {
  104229. return "Turning lens flares on/off";
  104230. };
  104231. /**
  104232. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104233. * @param scene defines the current scene where to apply this optimization
  104234. * @param optimizer defines the current optimizer
  104235. * @returns true if everything that can be done was applied
  104236. */
  104237. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  104238. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  104239. return true;
  104240. };
  104241. ;
  104242. return LensFlaresOptimization;
  104243. }(SceneOptimization));
  104244. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  104245. /**
  104246. * Defines an optimization based on user defined callback.
  104247. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104248. */
  104249. var CustomOptimization = /** @class */ (function (_super) {
  104250. __extends(CustomOptimization, _super);
  104251. function CustomOptimization() {
  104252. return _super !== null && _super.apply(this, arguments) || this;
  104253. }
  104254. /**
  104255. * Gets a string describing the action executed by the current optimization
  104256. * @returns description string
  104257. */
  104258. CustomOptimization.prototype.getDescription = function () {
  104259. if (this.onGetDescription) {
  104260. return this.onGetDescription();
  104261. }
  104262. return "Running user defined callback";
  104263. };
  104264. /**
  104265. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104266. * @param scene defines the current scene where to apply this optimization
  104267. * @param optimizer defines the current optimizer
  104268. * @returns true if everything that can be done was applied
  104269. */
  104270. CustomOptimization.prototype.apply = function (scene, optimizer) {
  104271. if (this.onApply) {
  104272. return this.onApply(scene, optimizer);
  104273. }
  104274. return true;
  104275. };
  104276. ;
  104277. return CustomOptimization;
  104278. }(SceneOptimization));
  104279. BABYLON.CustomOptimization = CustomOptimization;
  104280. /**
  104281. * Defines an optimization used to turn particles off
  104282. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104283. */
  104284. var ParticlesOptimization = /** @class */ (function (_super) {
  104285. __extends(ParticlesOptimization, _super);
  104286. function ParticlesOptimization() {
  104287. return _super !== null && _super.apply(this, arguments) || this;
  104288. }
  104289. /**
  104290. * Gets a string describing the action executed by the current optimization
  104291. * @return description string
  104292. */
  104293. ParticlesOptimization.prototype.getDescription = function () {
  104294. return "Turning particles on/off";
  104295. };
  104296. /**
  104297. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104298. * @param scene defines the current scene where to apply this optimization
  104299. * @param optimizer defines the current optimizer
  104300. * @returns true if everything that can be done was applied
  104301. */
  104302. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  104303. scene.particlesEnabled = optimizer.isInImprovementMode;
  104304. return true;
  104305. };
  104306. ;
  104307. return ParticlesOptimization;
  104308. }(SceneOptimization));
  104309. BABYLON.ParticlesOptimization = ParticlesOptimization;
  104310. /**
  104311. * Defines an optimization used to turn render targets off
  104312. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104313. */
  104314. var RenderTargetsOptimization = /** @class */ (function (_super) {
  104315. __extends(RenderTargetsOptimization, _super);
  104316. function RenderTargetsOptimization() {
  104317. return _super !== null && _super.apply(this, arguments) || this;
  104318. }
  104319. /**
  104320. * Gets a string describing the action executed by the current optimization
  104321. * @return description string
  104322. */
  104323. RenderTargetsOptimization.prototype.getDescription = function () {
  104324. return "Turning render targets off";
  104325. };
  104326. /**
  104327. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104328. * @param scene defines the current scene where to apply this optimization
  104329. * @param optimizer defines the current optimizer
  104330. * @returns true if everything that can be done was applied
  104331. */
  104332. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  104333. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  104334. return true;
  104335. };
  104336. ;
  104337. return RenderTargetsOptimization;
  104338. }(SceneOptimization));
  104339. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  104340. /**
  104341. * Defines an optimization used to merge meshes with compatible materials
  104342. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104343. */
  104344. var MergeMeshesOptimization = /** @class */ (function (_super) {
  104345. __extends(MergeMeshesOptimization, _super);
  104346. function MergeMeshesOptimization() {
  104347. var _this = _super !== null && _super.apply(this, arguments) || this;
  104348. _this._canBeMerged = function (abstractMesh) {
  104349. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  104350. return false;
  104351. }
  104352. var mesh = abstractMesh;
  104353. if (mesh.isDisposed()) {
  104354. return false;
  104355. }
  104356. if (!mesh.isVisible || !mesh.isEnabled()) {
  104357. return false;
  104358. }
  104359. if (mesh.instances.length > 0) {
  104360. return false;
  104361. }
  104362. if (mesh.skeleton || mesh.hasLODLevels) {
  104363. return false;
  104364. }
  104365. return true;
  104366. };
  104367. return _this;
  104368. }
  104369. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  104370. /**
  104371. * Gets or sets a boolean which defines if optimization octree has to be updated
  104372. */
  104373. get: function () {
  104374. return MergeMeshesOptimization._UpdateSelectionTree;
  104375. },
  104376. /**
  104377. * Gets or sets a boolean which defines if optimization octree has to be updated
  104378. */
  104379. set: function (value) {
  104380. MergeMeshesOptimization._UpdateSelectionTree = value;
  104381. },
  104382. enumerable: true,
  104383. configurable: true
  104384. });
  104385. /**
  104386. * Gets a string describing the action executed by the current optimization
  104387. * @return description string
  104388. */
  104389. MergeMeshesOptimization.prototype.getDescription = function () {
  104390. return "Merging similar meshes together";
  104391. };
  104392. /**
  104393. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104394. * @param scene defines the current scene where to apply this optimization
  104395. * @param optimizer defines the current optimizer
  104396. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  104397. * @returns true if everything that can be done was applied
  104398. */
  104399. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  104400. var globalPool = scene.meshes.slice(0);
  104401. var globalLength = globalPool.length;
  104402. for (var index = 0; index < globalLength; index++) {
  104403. var currentPool = new Array();
  104404. var current = globalPool[index];
  104405. // Checks
  104406. if (!this._canBeMerged(current)) {
  104407. continue;
  104408. }
  104409. currentPool.push(current);
  104410. // Find compatible meshes
  104411. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  104412. var otherMesh = globalPool[subIndex];
  104413. if (!this._canBeMerged(otherMesh)) {
  104414. continue;
  104415. }
  104416. if (otherMesh.material !== current.material) {
  104417. continue;
  104418. }
  104419. if (otherMesh.checkCollisions !== current.checkCollisions) {
  104420. continue;
  104421. }
  104422. currentPool.push(otherMesh);
  104423. globalLength--;
  104424. globalPool.splice(subIndex, 1);
  104425. subIndex--;
  104426. }
  104427. if (currentPool.length < 2) {
  104428. continue;
  104429. }
  104430. // Merge meshes
  104431. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  104432. }
  104433. // Call the octree system optimization if it is defined.
  104434. var sceneAsAny = scene;
  104435. if (sceneAsAny.createOrUpdateSelectionOctree) {
  104436. if (updateSelectionTree != undefined) {
  104437. if (updateSelectionTree) {
  104438. sceneAsAny.createOrUpdateSelectionOctree();
  104439. }
  104440. }
  104441. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  104442. sceneAsAny.createOrUpdateSelectionOctree();
  104443. }
  104444. }
  104445. return true;
  104446. };
  104447. ;
  104448. MergeMeshesOptimization._UpdateSelectionTree = false;
  104449. return MergeMeshesOptimization;
  104450. }(SceneOptimization));
  104451. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  104452. /**
  104453. * Defines a list of options used by SceneOptimizer
  104454. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104455. */
  104456. var SceneOptimizerOptions = /** @class */ (function () {
  104457. /**
  104458. * Creates a new list of options used by SceneOptimizer
  104459. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  104460. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  104461. */
  104462. function SceneOptimizerOptions(
  104463. /**
  104464. * Defines the target frame rate to reach (60 by default)
  104465. */
  104466. targetFrameRate,
  104467. /**
  104468. * Defines the interval between two checkes (2000ms by default)
  104469. */
  104470. trackerDuration) {
  104471. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  104472. if (trackerDuration === void 0) { trackerDuration = 2000; }
  104473. this.targetFrameRate = targetFrameRate;
  104474. this.trackerDuration = trackerDuration;
  104475. /**
  104476. * Gets the list of optimizations to apply
  104477. */
  104478. this.optimizations = new Array();
  104479. }
  104480. /**
  104481. * Add a new optimization
  104482. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  104483. * @returns the current SceneOptimizerOptions
  104484. */
  104485. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  104486. this.optimizations.push(optimization);
  104487. return this;
  104488. };
  104489. /**
  104490. * Add a new custom optimization
  104491. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  104492. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  104493. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104494. * @returns the current SceneOptimizerOptions
  104495. */
  104496. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  104497. if (priority === void 0) { priority = 0; }
  104498. var optimization = new CustomOptimization(priority);
  104499. optimization.onApply = onApply;
  104500. optimization.onGetDescription = onGetDescription;
  104501. this.optimizations.push(optimization);
  104502. return this;
  104503. };
  104504. /**
  104505. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  104506. * @param targetFrameRate defines the target frame rate (60 by default)
  104507. * @returns a SceneOptimizerOptions object
  104508. */
  104509. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  104510. var result = new SceneOptimizerOptions(targetFrameRate);
  104511. var priority = 0;
  104512. result.addOptimization(new MergeMeshesOptimization(priority));
  104513. result.addOptimization(new ShadowsOptimization(priority));
  104514. result.addOptimization(new LensFlaresOptimization(priority));
  104515. // Next priority
  104516. priority++;
  104517. result.addOptimization(new PostProcessesOptimization(priority));
  104518. result.addOptimization(new ParticlesOptimization(priority));
  104519. // Next priority
  104520. priority++;
  104521. result.addOptimization(new TextureOptimization(priority, 1024));
  104522. return result;
  104523. };
  104524. /**
  104525. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  104526. * @param targetFrameRate defines the target frame rate (60 by default)
  104527. * @returns a SceneOptimizerOptions object
  104528. */
  104529. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  104530. var result = new SceneOptimizerOptions(targetFrameRate);
  104531. var priority = 0;
  104532. result.addOptimization(new MergeMeshesOptimization(priority));
  104533. result.addOptimization(new ShadowsOptimization(priority));
  104534. result.addOptimization(new LensFlaresOptimization(priority));
  104535. // Next priority
  104536. priority++;
  104537. result.addOptimization(new PostProcessesOptimization(priority));
  104538. result.addOptimization(new ParticlesOptimization(priority));
  104539. // Next priority
  104540. priority++;
  104541. result.addOptimization(new TextureOptimization(priority, 512));
  104542. // Next priority
  104543. priority++;
  104544. result.addOptimization(new RenderTargetsOptimization(priority));
  104545. // Next priority
  104546. priority++;
  104547. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  104548. return result;
  104549. };
  104550. /**
  104551. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  104552. * @param targetFrameRate defines the target frame rate (60 by default)
  104553. * @returns a SceneOptimizerOptions object
  104554. */
  104555. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  104556. var result = new SceneOptimizerOptions(targetFrameRate);
  104557. var priority = 0;
  104558. result.addOptimization(new MergeMeshesOptimization(priority));
  104559. result.addOptimization(new ShadowsOptimization(priority));
  104560. result.addOptimization(new LensFlaresOptimization(priority));
  104561. // Next priority
  104562. priority++;
  104563. result.addOptimization(new PostProcessesOptimization(priority));
  104564. result.addOptimization(new ParticlesOptimization(priority));
  104565. // Next priority
  104566. priority++;
  104567. result.addOptimization(new TextureOptimization(priority, 256));
  104568. // Next priority
  104569. priority++;
  104570. result.addOptimization(new RenderTargetsOptimization(priority));
  104571. // Next priority
  104572. priority++;
  104573. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  104574. return result;
  104575. };
  104576. return SceneOptimizerOptions;
  104577. }());
  104578. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  104579. /**
  104580. * Class used to run optimizations in order to reach a target frame rate
  104581. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104582. */
  104583. var SceneOptimizer = /** @class */ (function () {
  104584. /**
  104585. * Creates a new SceneOptimizer
  104586. * @param scene defines the scene to work on
  104587. * @param options defines the options to use with the SceneOptimizer
  104588. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  104589. * @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)
  104590. */
  104591. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  104592. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  104593. if (improvementMode === void 0) { improvementMode = false; }
  104594. var _this = this;
  104595. this._isRunning = false;
  104596. this._currentPriorityLevel = 0;
  104597. this._targetFrameRate = 60;
  104598. this._trackerDuration = 2000;
  104599. this._currentFrameRate = 0;
  104600. this._improvementMode = false;
  104601. /**
  104602. * Defines an observable called when the optimizer reaches the target frame rate
  104603. */
  104604. this.onSuccessObservable = new BABYLON.Observable();
  104605. /**
  104606. * Defines an observable called when the optimizer enables an optimization
  104607. */
  104608. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  104609. /**
  104610. * Defines an observable called when the optimizer is not able to reach the target frame rate
  104611. */
  104612. this.onFailureObservable = new BABYLON.Observable();
  104613. if (!options) {
  104614. this._options = new SceneOptimizerOptions();
  104615. }
  104616. else {
  104617. this._options = options;
  104618. }
  104619. if (this._options.targetFrameRate) {
  104620. this._targetFrameRate = this._options.targetFrameRate;
  104621. }
  104622. if (this._options.trackerDuration) {
  104623. this._trackerDuration = this._options.trackerDuration;
  104624. }
  104625. if (autoGeneratePriorities) {
  104626. var priority = 0;
  104627. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  104628. var optim = _a[_i];
  104629. optim.priority = priority++;
  104630. }
  104631. }
  104632. this._improvementMode = improvementMode;
  104633. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  104634. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  104635. _this._sceneDisposeObserver = null;
  104636. _this.dispose();
  104637. });
  104638. }
  104639. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  104640. /**
  104641. * Gets a boolean indicating if the optimizer is in improvement mode
  104642. */
  104643. get: function () {
  104644. return this._improvementMode;
  104645. },
  104646. enumerable: true,
  104647. configurable: true
  104648. });
  104649. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  104650. /**
  104651. * Gets the current priority level (0 at start)
  104652. */
  104653. get: function () {
  104654. return this._currentPriorityLevel;
  104655. },
  104656. enumerable: true,
  104657. configurable: true
  104658. });
  104659. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  104660. /**
  104661. * Gets the current frame rate checked by the SceneOptimizer
  104662. */
  104663. get: function () {
  104664. return this._currentFrameRate;
  104665. },
  104666. enumerable: true,
  104667. configurable: true
  104668. });
  104669. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  104670. /**
  104671. * Gets or sets the current target frame rate (60 by default)
  104672. */
  104673. get: function () {
  104674. return this._targetFrameRate;
  104675. },
  104676. /**
  104677. * Gets or sets the current target frame rate (60 by default)
  104678. */
  104679. set: function (value) {
  104680. this._targetFrameRate = value;
  104681. },
  104682. enumerable: true,
  104683. configurable: true
  104684. });
  104685. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  104686. /**
  104687. * Gets or sets the current interval between two checks (every 2000ms by default)
  104688. */
  104689. get: function () {
  104690. return this._trackerDuration;
  104691. },
  104692. /**
  104693. * Gets or sets the current interval between two checks (every 2000ms by default)
  104694. */
  104695. set: function (value) {
  104696. this._trackerDuration = value;
  104697. },
  104698. enumerable: true,
  104699. configurable: true
  104700. });
  104701. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  104702. /**
  104703. * Gets the list of active optimizations
  104704. */
  104705. get: function () {
  104706. return this._options.optimizations;
  104707. },
  104708. enumerable: true,
  104709. configurable: true
  104710. });
  104711. /**
  104712. * Stops the current optimizer
  104713. */
  104714. SceneOptimizer.prototype.stop = function () {
  104715. this._isRunning = false;
  104716. };
  104717. /**
  104718. * Reset the optimizer to initial step (current priority level = 0)
  104719. */
  104720. SceneOptimizer.prototype.reset = function () {
  104721. this._currentPriorityLevel = 0;
  104722. };
  104723. /**
  104724. * Start the optimizer. By default it will try to reach a specific framerate
  104725. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  104726. */
  104727. SceneOptimizer.prototype.start = function () {
  104728. var _this = this;
  104729. if (this._isRunning) {
  104730. return;
  104731. }
  104732. this._isRunning = true;
  104733. // Let's wait for the scene to be ready before running our check
  104734. this._scene.executeWhenReady(function () {
  104735. setTimeout(function () {
  104736. _this._checkCurrentState();
  104737. }, _this._trackerDuration);
  104738. });
  104739. };
  104740. SceneOptimizer.prototype._checkCurrentState = function () {
  104741. var _this = this;
  104742. if (!this._isRunning) {
  104743. return;
  104744. }
  104745. var scene = this._scene;
  104746. var options = this._options;
  104747. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  104748. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  104749. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  104750. this._isRunning = false;
  104751. this.onSuccessObservable.notifyObservers(this);
  104752. return;
  104753. }
  104754. // Apply current level of optimizations
  104755. var allDone = true;
  104756. var noOptimizationApplied = true;
  104757. for (var index = 0; index < options.optimizations.length; index++) {
  104758. var optimization = options.optimizations[index];
  104759. if (optimization.priority === this._currentPriorityLevel) {
  104760. noOptimizationApplied = false;
  104761. allDone = allDone && optimization.apply(scene, this);
  104762. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  104763. }
  104764. }
  104765. // If no optimization was applied, this is a failure :(
  104766. if (noOptimizationApplied) {
  104767. this._isRunning = false;
  104768. this.onFailureObservable.notifyObservers(this);
  104769. return;
  104770. }
  104771. // If all optimizations were done, move to next level
  104772. if (allDone) {
  104773. this._currentPriorityLevel++;
  104774. }
  104775. // Let's the system running for a specific amount of time before checking FPS
  104776. scene.executeWhenReady(function () {
  104777. setTimeout(function () {
  104778. _this._checkCurrentState();
  104779. }, _this._trackerDuration);
  104780. });
  104781. };
  104782. /**
  104783. * Release all resources
  104784. */
  104785. SceneOptimizer.prototype.dispose = function () {
  104786. this.stop();
  104787. this.onSuccessObservable.clear();
  104788. this.onFailureObservable.clear();
  104789. this.onNewOptimizationAppliedObservable.clear();
  104790. if (this._sceneDisposeObserver) {
  104791. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  104792. }
  104793. };
  104794. /**
  104795. * Helper function to create a SceneOptimizer with one single line of code
  104796. * @param scene defines the scene to work on
  104797. * @param options defines the options to use with the SceneOptimizer
  104798. * @param onSuccess defines a callback to call on success
  104799. * @param onFailure defines a callback to call on failure
  104800. * @returns the new SceneOptimizer object
  104801. */
  104802. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  104803. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  104804. if (onSuccess) {
  104805. optimizer.onSuccessObservable.add(function () {
  104806. onSuccess();
  104807. });
  104808. }
  104809. if (onFailure) {
  104810. optimizer.onFailureObservable.add(function () {
  104811. onFailure();
  104812. });
  104813. }
  104814. optimizer.start();
  104815. return optimizer;
  104816. };
  104817. return SceneOptimizer;
  104818. }());
  104819. BABYLON.SceneOptimizer = SceneOptimizer;
  104820. })(BABYLON || (BABYLON = {}));
  104821. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  104822. var BABYLON;
  104823. (function (BABYLON) {
  104824. /**
  104825. * Gets the outline renderer associated with the scene
  104826. * @returns a OutlineRenderer
  104827. */
  104828. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  104829. if (!this._outlineRenderer) {
  104830. this._outlineRenderer = new OutlineRenderer(this);
  104831. }
  104832. return this._outlineRenderer;
  104833. };
  104834. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  104835. get: function () {
  104836. return this._renderOutline;
  104837. },
  104838. set: function (value) {
  104839. if (value) {
  104840. // Lazy Load the component.
  104841. this.getScene().getOutlineRenderer();
  104842. }
  104843. this._renderOutline = value;
  104844. },
  104845. enumerable: true,
  104846. configurable: true
  104847. });
  104848. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  104849. get: function () {
  104850. return this._renderOverlay;
  104851. },
  104852. set: function (value) {
  104853. if (value) {
  104854. // Lazy Load the component.
  104855. this.getScene().getOutlineRenderer();
  104856. }
  104857. this._renderOverlay = value;
  104858. },
  104859. enumerable: true,
  104860. configurable: true
  104861. });
  104862. /**
  104863. * This class is responsible to draw bothe outline/overlay of meshes.
  104864. * It should not be used directly but through the available method on mesh.
  104865. */
  104866. var OutlineRenderer = /** @class */ (function () {
  104867. /**
  104868. * Instantiates a new outline renderer. (There could be only one per scene).
  104869. * @param scene Defines the scene it belongs to
  104870. */
  104871. function OutlineRenderer(scene) {
  104872. /**
  104873. * The name of the component. Each component must have a unique name.
  104874. */
  104875. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  104876. /**
  104877. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  104878. */
  104879. this.zOffset = 1;
  104880. this.scene = scene;
  104881. this._engine = scene.getEngine();
  104882. this.scene._addComponent(this);
  104883. }
  104884. /**
  104885. * Register the component to one instance of a scene.
  104886. */
  104887. OutlineRenderer.prototype.register = function () {
  104888. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  104889. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  104890. };
  104891. /**
  104892. * Rebuilds the elements related to this component in case of
  104893. * context lost for instance.
  104894. */
  104895. OutlineRenderer.prototype.rebuild = function () {
  104896. // Nothing to do here.
  104897. };
  104898. /**
  104899. * Disposes the component and the associated ressources.
  104900. */
  104901. OutlineRenderer.prototype.dispose = function () {
  104902. // Nothing to do here.
  104903. };
  104904. /**
  104905. * Renders the outline in the canvas.
  104906. * @param subMesh Defines the sumesh to render
  104907. * @param batch Defines the batch of meshes in case of instances
  104908. * @param useOverlay Defines if the rendering is for the overlay or the outline
  104909. */
  104910. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  104911. var _this = this;
  104912. if (useOverlay === void 0) { useOverlay = false; }
  104913. var scene = this.scene;
  104914. var engine = scene.getEngine();
  104915. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  104916. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  104917. return;
  104918. }
  104919. var mesh = subMesh.getRenderingMesh();
  104920. var material = subMesh.getMaterial();
  104921. if (!material || !scene.activeCamera) {
  104922. return;
  104923. }
  104924. engine.enableEffect(this._effect);
  104925. // Logarithmic depth
  104926. if (material.useLogarithmicDepth) {
  104927. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  104928. }
  104929. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  104930. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  104931. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  104932. // Bones
  104933. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  104934. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  104935. }
  104936. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  104937. // Alpha test
  104938. if (material && material.needAlphaTesting()) {
  104939. var alphaTexture = material.getAlphaTestTexture();
  104940. if (alphaTexture) {
  104941. this._effect.setTexture("diffuseSampler", alphaTexture);
  104942. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  104943. }
  104944. }
  104945. engine.setZOffset(-this.zOffset);
  104946. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  104947. engine.setZOffset(0);
  104948. };
  104949. /**
  104950. * Returns whether or not the outline renderer is ready for a given submesh.
  104951. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  104952. * @param subMesh Defines the submesh to check readyness for
  104953. * @param useInstances Defines wheter wee are trying to render instances or not
  104954. * @returns true if ready otherwise false
  104955. */
  104956. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  104957. var defines = [];
  104958. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  104959. var mesh = subMesh.getMesh();
  104960. var material = subMesh.getMaterial();
  104961. if (material) {
  104962. // Alpha test
  104963. if (material.needAlphaTesting()) {
  104964. defines.push("#define ALPHATEST");
  104965. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104966. attribs.push(BABYLON.VertexBuffer.UVKind);
  104967. defines.push("#define UV1");
  104968. }
  104969. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  104970. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104971. defines.push("#define UV2");
  104972. }
  104973. }
  104974. //Logarithmic depth
  104975. if (material.useLogarithmicDepth) {
  104976. defines.push("#define LOGARITHMICDEPTH");
  104977. }
  104978. }
  104979. // Bones
  104980. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  104981. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  104982. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  104983. if (mesh.numBoneInfluencers > 4) {
  104984. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  104985. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  104986. }
  104987. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  104988. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  104989. }
  104990. else {
  104991. defines.push("#define NUM_BONE_INFLUENCERS 0");
  104992. }
  104993. // Instances
  104994. if (useInstances) {
  104995. defines.push("#define INSTANCES");
  104996. attribs.push("world0");
  104997. attribs.push("world1");
  104998. attribs.push("world2");
  104999. attribs.push("world3");
  105000. }
  105001. // Get correct effect
  105002. var join = defines.join("\n");
  105003. if (this._cachedDefines !== join) {
  105004. this._cachedDefines = join;
  105005. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  105006. }
  105007. return this._effect.isReady();
  105008. };
  105009. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  105010. // Outline - step 1
  105011. this._savedDepthWrite = this._engine.getDepthWrite();
  105012. if (mesh.renderOutline) {
  105013. this._engine.setDepthWrite(false);
  105014. this.render(subMesh, batch);
  105015. this._engine.setDepthWrite(this._savedDepthWrite);
  105016. }
  105017. };
  105018. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  105019. // Outline - step 2
  105020. if (mesh.renderOutline && this._savedDepthWrite) {
  105021. this._engine.setDepthWrite(true);
  105022. this._engine.setColorWrite(false);
  105023. this.render(subMesh, batch);
  105024. this._engine.setColorWrite(true);
  105025. }
  105026. // Overlay
  105027. if (mesh.renderOverlay) {
  105028. var currentMode = this._engine.getAlphaMode();
  105029. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  105030. this.render(subMesh, batch, true);
  105031. this._engine.setAlphaMode(currentMode);
  105032. }
  105033. };
  105034. return OutlineRenderer;
  105035. }());
  105036. BABYLON.OutlineRenderer = OutlineRenderer;
  105037. })(BABYLON || (BABYLON = {}));
  105038. //# sourceMappingURL=babylon.outlineRenderer.js.map
  105039. var BABYLON;
  105040. (function (BABYLON) {
  105041. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  105042. if (this._edgesRenderer) {
  105043. this._edgesRenderer.dispose();
  105044. this._edgesRenderer = null;
  105045. }
  105046. return this;
  105047. };
  105048. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  105049. if (epsilon === void 0) { epsilon = 0.95; }
  105050. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105051. this.disableEdgesRendering();
  105052. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  105053. return this;
  105054. };
  105055. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  105056. get: function () {
  105057. return this._edgesRenderer;
  105058. },
  105059. enumerable: true,
  105060. configurable: true
  105061. });
  105062. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  105063. if (epsilon === void 0) { epsilon = 0.95; }
  105064. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105065. this.disableEdgesRendering();
  105066. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  105067. return this;
  105068. };
  105069. /**
  105070. * FaceAdjacencies Helper class to generate edges
  105071. */
  105072. var FaceAdjacencies = /** @class */ (function () {
  105073. function FaceAdjacencies() {
  105074. this.edges = new Array();
  105075. this.edgesConnectedCount = 0;
  105076. }
  105077. return FaceAdjacencies;
  105078. }());
  105079. /**
  105080. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  105081. */
  105082. var EdgesRenderer = /** @class */ (function () {
  105083. /**
  105084. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  105085. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  105086. * @param source Mesh used to create edges
  105087. * @param epsilon sum of angles in adjacency to check for edge
  105088. * @param checkVerticesInsteadOfIndices
  105089. * @param generateEdgesLines - should generate Lines or only prepare resources.
  105090. */
  105091. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  105092. if (epsilon === void 0) { epsilon = 0.95; }
  105093. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105094. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  105095. var _this = this;
  105096. /**
  105097. * Define the size of the edges with an orthographic camera
  105098. */
  105099. this.edgesWidthScalerForOrthographic = 1000.0;
  105100. /**
  105101. * Define the size of the edges with a perspective camera
  105102. */
  105103. this.edgesWidthScalerForPerspective = 50.0;
  105104. this._linesPositions = new Array();
  105105. this._linesNormals = new Array();
  105106. this._linesIndices = new Array();
  105107. this._buffers = {};
  105108. this._checkVerticesInsteadOfIndices = false;
  105109. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  105110. this.isEnabled = true;
  105111. this._source = source;
  105112. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  105113. this._epsilon = epsilon;
  105114. this._prepareRessources();
  105115. if (generateEdgesLines) {
  105116. this._generateEdgesLines();
  105117. }
  105118. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  105119. _this._rebuild();
  105120. });
  105121. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  105122. _this.dispose();
  105123. });
  105124. }
  105125. EdgesRenderer.prototype._prepareRessources = function () {
  105126. if (this._lineShader) {
  105127. return;
  105128. }
  105129. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  105130. attributes: ["position", "normal"],
  105131. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  105132. });
  105133. this._lineShader.disableDepthWrite = true;
  105134. this._lineShader.backFaceCulling = false;
  105135. };
  105136. /** @hidden */
  105137. EdgesRenderer.prototype._rebuild = function () {
  105138. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  105139. if (buffer) {
  105140. buffer._rebuild();
  105141. }
  105142. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  105143. if (buffer) {
  105144. buffer._rebuild();
  105145. }
  105146. var scene = this._source.getScene();
  105147. var engine = scene.getEngine();
  105148. this._ib = engine.createIndexBuffer(this._linesIndices);
  105149. };
  105150. /**
  105151. * Releases the required resources for the edges renderer
  105152. */
  105153. EdgesRenderer.prototype.dispose = function () {
  105154. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  105155. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  105156. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  105157. if (buffer) {
  105158. buffer.dispose();
  105159. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  105160. }
  105161. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  105162. if (buffer) {
  105163. buffer.dispose();
  105164. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  105165. }
  105166. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  105167. this._lineShader.dispose();
  105168. };
  105169. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  105170. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  105171. return 0;
  105172. }
  105173. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  105174. return 1;
  105175. }
  105176. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  105177. return 2;
  105178. }
  105179. return -1;
  105180. };
  105181. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  105182. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  105183. return 0;
  105184. }
  105185. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  105186. return 1;
  105187. }
  105188. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  105189. return 2;
  105190. }
  105191. return -1;
  105192. };
  105193. /**
  105194. * Checks if the pair of p0 and p1 is en edge
  105195. * @param faceIndex
  105196. * @param edge
  105197. * @param faceNormals
  105198. * @param p0
  105199. * @param p1
  105200. * @private
  105201. */
  105202. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  105203. var needToCreateLine;
  105204. if (edge === undefined) {
  105205. needToCreateLine = true;
  105206. }
  105207. else {
  105208. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  105209. needToCreateLine = dotProduct < this._epsilon;
  105210. }
  105211. if (needToCreateLine) {
  105212. var offset = this._linesPositions.length / 3;
  105213. var normal = p0.subtract(p1);
  105214. normal.normalize();
  105215. // Positions
  105216. this._linesPositions.push(p0.x);
  105217. this._linesPositions.push(p0.y);
  105218. this._linesPositions.push(p0.z);
  105219. this._linesPositions.push(p0.x);
  105220. this._linesPositions.push(p0.y);
  105221. this._linesPositions.push(p0.z);
  105222. this._linesPositions.push(p1.x);
  105223. this._linesPositions.push(p1.y);
  105224. this._linesPositions.push(p1.z);
  105225. this._linesPositions.push(p1.x);
  105226. this._linesPositions.push(p1.y);
  105227. this._linesPositions.push(p1.z);
  105228. // Normals
  105229. this._linesNormals.push(p1.x);
  105230. this._linesNormals.push(p1.y);
  105231. this._linesNormals.push(p1.z);
  105232. this._linesNormals.push(-1);
  105233. this._linesNormals.push(p1.x);
  105234. this._linesNormals.push(p1.y);
  105235. this._linesNormals.push(p1.z);
  105236. this._linesNormals.push(1);
  105237. this._linesNormals.push(p0.x);
  105238. this._linesNormals.push(p0.y);
  105239. this._linesNormals.push(p0.z);
  105240. this._linesNormals.push(-1);
  105241. this._linesNormals.push(p0.x);
  105242. this._linesNormals.push(p0.y);
  105243. this._linesNormals.push(p0.z);
  105244. this._linesNormals.push(1);
  105245. // Indices
  105246. this._linesIndices.push(offset);
  105247. this._linesIndices.push(offset + 1);
  105248. this._linesIndices.push(offset + 2);
  105249. this._linesIndices.push(offset);
  105250. this._linesIndices.push(offset + 2);
  105251. this._linesIndices.push(offset + 3);
  105252. }
  105253. };
  105254. /**
  105255. * Generates lines edges from adjacencjes
  105256. * @private
  105257. */
  105258. EdgesRenderer.prototype._generateEdgesLines = function () {
  105259. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  105260. var indices = this._source.getIndices();
  105261. if (!indices || !positions) {
  105262. return;
  105263. }
  105264. // First let's find adjacencies
  105265. var adjacencies = new Array();
  105266. var faceNormals = new Array();
  105267. var index;
  105268. var faceAdjacencies;
  105269. // Prepare faces
  105270. for (index = 0; index < indices.length; index += 3) {
  105271. faceAdjacencies = new FaceAdjacencies();
  105272. var p0Index = indices[index];
  105273. var p1Index = indices[index + 1];
  105274. var p2Index = indices[index + 2];
  105275. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  105276. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  105277. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  105278. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  105279. faceNormal.normalize();
  105280. faceNormals.push(faceNormal);
  105281. adjacencies.push(faceAdjacencies);
  105282. }
  105283. // Scan
  105284. for (index = 0; index < adjacencies.length; index++) {
  105285. faceAdjacencies = adjacencies[index];
  105286. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  105287. var otherFaceAdjacencies = adjacencies[otherIndex];
  105288. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  105289. break;
  105290. }
  105291. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  105292. continue;
  105293. }
  105294. var otherP0 = indices[otherIndex * 3];
  105295. var otherP1 = indices[otherIndex * 3 + 1];
  105296. var otherP2 = indices[otherIndex * 3 + 2];
  105297. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  105298. var otherEdgeIndex = 0;
  105299. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  105300. continue;
  105301. }
  105302. switch (edgeIndex) {
  105303. case 0:
  105304. if (this._checkVerticesInsteadOfIndices) {
  105305. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  105306. }
  105307. else {
  105308. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  105309. }
  105310. break;
  105311. case 1:
  105312. if (this._checkVerticesInsteadOfIndices) {
  105313. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  105314. }
  105315. else {
  105316. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  105317. }
  105318. break;
  105319. case 2:
  105320. if (this._checkVerticesInsteadOfIndices) {
  105321. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  105322. }
  105323. else {
  105324. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  105325. }
  105326. break;
  105327. }
  105328. if (otherEdgeIndex === -1) {
  105329. continue;
  105330. }
  105331. faceAdjacencies.edges[edgeIndex] = otherIndex;
  105332. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  105333. faceAdjacencies.edgesConnectedCount++;
  105334. otherFaceAdjacencies.edgesConnectedCount++;
  105335. if (faceAdjacencies.edgesConnectedCount === 3) {
  105336. break;
  105337. }
  105338. }
  105339. }
  105340. }
  105341. // Create lines
  105342. for (index = 0; index < adjacencies.length; index++) {
  105343. // 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
  105344. var current = adjacencies[index];
  105345. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  105346. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  105347. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  105348. }
  105349. // Merge into a single mesh
  105350. var engine = this._source.getScene().getEngine();
  105351. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  105352. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  105353. this._ib = engine.createIndexBuffer(this._linesIndices);
  105354. this._indicesCount = this._linesIndices.length;
  105355. };
  105356. /**
  105357. * Checks wether or not the edges renderer is ready to render.
  105358. * @return true if ready, otherwise false.
  105359. */
  105360. EdgesRenderer.prototype.isReady = function () {
  105361. return this._lineShader.isReady();
  105362. };
  105363. /**
  105364. * Renders the edges of the attached mesh,
  105365. */
  105366. EdgesRenderer.prototype.render = function () {
  105367. var scene = this._source.getScene();
  105368. if (!this.isReady() || !scene.activeCamera) {
  105369. return;
  105370. }
  105371. var engine = scene.getEngine();
  105372. this._lineShader._preBind();
  105373. if (this._source.edgesColor.a !== 1) {
  105374. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  105375. }
  105376. else {
  105377. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  105378. }
  105379. // VBOs
  105380. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  105381. scene.resetCachedMaterial();
  105382. this._lineShader.setColor4("color", this._source.edgesColor);
  105383. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  105384. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  105385. }
  105386. else {
  105387. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  105388. }
  105389. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  105390. this._lineShader.bind(this._source.getWorldMatrix());
  105391. // Draw order
  105392. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  105393. this._lineShader.unbind();
  105394. };
  105395. return EdgesRenderer;
  105396. }());
  105397. BABYLON.EdgesRenderer = EdgesRenderer;
  105398. })(BABYLON || (BABYLON = {}));
  105399. //# sourceMappingURL=babylon.edgesRenderer.js.map
  105400. var BABYLON;
  105401. (function (BABYLON) {
  105402. /**
  105403. * FaceAdjacencies Helper class to generate edges
  105404. */
  105405. var FaceAdjacencies = /** @class */ (function () {
  105406. function FaceAdjacencies() {
  105407. this.edges = new Array();
  105408. this.edgesConnectedCount = 0;
  105409. }
  105410. return FaceAdjacencies;
  105411. }());
  105412. /**
  105413. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  105414. */
  105415. var LineEdgesRenderer = /** @class */ (function (_super) {
  105416. __extends(LineEdgesRenderer, _super);
  105417. /**
  105418. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  105419. * @param source LineMesh used to generate edges
  105420. * @param epsilon not important (specified angle for edge detection)
  105421. * @param checkVerticesInsteadOfIndices not important for LineMesh
  105422. */
  105423. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  105424. if (epsilon === void 0) { epsilon = 0.95; }
  105425. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105426. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  105427. _this._generateEdgesLines();
  105428. return _this;
  105429. }
  105430. /**
  105431. * Always create the edge since its a line so only important things are p0 and p1
  105432. * @param faceIndex not important for LineMesh
  105433. * @param edge not important for LineMesh
  105434. * @param faceNormals not important for LineMesh
  105435. * @param p0 beginnig of line
  105436. * @param p1 end of line
  105437. */
  105438. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  105439. var offset = this._linesPositions.length / 3;
  105440. var normal = p0.subtract(p1);
  105441. normal.normalize();
  105442. // Positions
  105443. this._linesPositions.push(p0.x);
  105444. this._linesPositions.push(p0.y);
  105445. this._linesPositions.push(p0.z);
  105446. this._linesPositions.push(p0.x);
  105447. this._linesPositions.push(p0.y);
  105448. this._linesPositions.push(p0.z);
  105449. this._linesPositions.push(p1.x);
  105450. this._linesPositions.push(p1.y);
  105451. this._linesPositions.push(p1.z);
  105452. this._linesPositions.push(p1.x);
  105453. this._linesPositions.push(p1.y);
  105454. this._linesPositions.push(p1.z);
  105455. // Normals
  105456. this._linesNormals.push(p1.x);
  105457. this._linesNormals.push(p1.y);
  105458. this._linesNormals.push(p1.z);
  105459. this._linesNormals.push(-1);
  105460. this._linesNormals.push(p1.x);
  105461. this._linesNormals.push(p1.y);
  105462. this._linesNormals.push(p1.z);
  105463. this._linesNormals.push(1);
  105464. this._linesNormals.push(p0.x);
  105465. this._linesNormals.push(p0.y);
  105466. this._linesNormals.push(p0.z);
  105467. this._linesNormals.push(-1);
  105468. this._linesNormals.push(p0.x);
  105469. this._linesNormals.push(p0.y);
  105470. this._linesNormals.push(p0.z);
  105471. this._linesNormals.push(1);
  105472. // Indices
  105473. this._linesIndices.push(offset);
  105474. this._linesIndices.push(offset + 1);
  105475. this._linesIndices.push(offset + 2);
  105476. this._linesIndices.push(offset);
  105477. this._linesIndices.push(offset + 2);
  105478. this._linesIndices.push(offset + 3);
  105479. };
  105480. /**
  105481. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  105482. */
  105483. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  105484. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  105485. var indices = this._source.getIndices();
  105486. if (!indices || !positions) {
  105487. return;
  105488. }
  105489. // First let's find adjacencies
  105490. var adjacencies = new Array();
  105491. var faceNormals = new Array();
  105492. var index;
  105493. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  105494. var currentAdjecancy = new FaceAdjacencies();
  105495. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  105496. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  105497. adjacencies.push(currentAdjecancy);
  105498. }
  105499. // Create lines
  105500. for (index = 0; index < adjacencies.length; index++) {
  105501. // 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
  105502. var current = adjacencies[index];
  105503. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  105504. }
  105505. // Merge into a single mesh
  105506. var engine = this._source.getScene().getEngine();
  105507. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  105508. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  105509. this._ib = engine.createIndexBuffer(this._linesIndices);
  105510. this._indicesCount = this._linesIndices.length;
  105511. };
  105512. return LineEdgesRenderer;
  105513. }(BABYLON.EdgesRenderer));
  105514. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  105515. })(BABYLON || (BABYLON = {}));
  105516. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  105517. var BABYLON;
  105518. (function (BABYLON) {
  105519. // Adds the parser to the scene parsers.
  105520. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  105521. if (parsedData.effectLayers) {
  105522. if (!container.effectLayers) {
  105523. container.effectLayers = new Array();
  105524. }
  105525. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  105526. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  105527. container.effectLayers.push(effectLayer);
  105528. }
  105529. }
  105530. });
  105531. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  105532. var index = this.effectLayers.indexOf(toRemove);
  105533. if (index !== -1) {
  105534. this.effectLayers.splice(index, 1);
  105535. }
  105536. return index;
  105537. };
  105538. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  105539. this.effectLayers.push(newEffectLayer);
  105540. };
  105541. /**
  105542. * Defines the layer scene component responsible to manage any effect layers
  105543. * in a given scene.
  105544. */
  105545. var EffectLayerSceneComponent = /** @class */ (function () {
  105546. /**
  105547. * Creates a new instance of the component for the given scene
  105548. * @param scene Defines the scene to register the component in
  105549. */
  105550. function EffectLayerSceneComponent(scene) {
  105551. /**
  105552. * The component name helpfull to identify the component in the list of scene components.
  105553. */
  105554. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  105555. this._renderEffects = false;
  105556. this._needStencil = false;
  105557. this._previousStencilState = false;
  105558. this.scene = scene;
  105559. this._engine = scene.getEngine();
  105560. scene.effectLayers = new Array();
  105561. }
  105562. /**
  105563. * Registers the component in a given scene
  105564. */
  105565. EffectLayerSceneComponent.prototype.register = function () {
  105566. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  105567. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  105568. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  105569. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  105570. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  105571. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  105572. };
  105573. /**
  105574. * Rebuilds the elements related to this component in case of
  105575. * context lost for instance.
  105576. */
  105577. EffectLayerSceneComponent.prototype.rebuild = function () {
  105578. var layers = this.scene.effectLayers;
  105579. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  105580. var effectLayer = layers_1[_i];
  105581. effectLayer._rebuild();
  105582. }
  105583. };
  105584. /**
  105585. * Serializes the component data to the specified json object
  105586. * @param serializationObject The object to serialize to
  105587. */
  105588. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  105589. // Effect layers
  105590. serializationObject.effectLayers = [];
  105591. var layers = this.scene.effectLayers;
  105592. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  105593. var effectLayer = layers_2[_i];
  105594. if (effectLayer.serialize) {
  105595. serializationObject.effectLayers.push(effectLayer.serialize());
  105596. }
  105597. }
  105598. };
  105599. /**
  105600. * Adds all the element from the container to the scene
  105601. * @param container the container holding the elements
  105602. */
  105603. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  105604. var _this = this;
  105605. if (!container.effectLayers) {
  105606. return;
  105607. }
  105608. container.effectLayers.forEach(function (o) {
  105609. _this.scene.addEffectLayer(o);
  105610. });
  105611. };
  105612. /**
  105613. * Removes all the elements in the container from the scene
  105614. * @param container contains the elements to remove
  105615. */
  105616. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  105617. var _this = this;
  105618. if (!container.effectLayers) {
  105619. return;
  105620. }
  105621. container.effectLayers.forEach(function (o) {
  105622. _this.scene.removeEffectLayer(o);
  105623. });
  105624. };
  105625. /**
  105626. * Disposes the component and the associated ressources.
  105627. */
  105628. EffectLayerSceneComponent.prototype.dispose = function () {
  105629. var layers = this.scene.effectLayers;
  105630. while (layers.length) {
  105631. layers[0].dispose();
  105632. }
  105633. };
  105634. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  105635. var layers = this.scene.effectLayers;
  105636. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  105637. var layer = layers_3[_i];
  105638. if (!layer.hasMesh(mesh)) {
  105639. continue;
  105640. }
  105641. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  105642. var subMesh = _b[_a];
  105643. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  105644. return false;
  105645. }
  105646. }
  105647. }
  105648. return true;
  105649. };
  105650. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  105651. this._renderEffects = false;
  105652. this._needStencil = false;
  105653. var layers = this.scene.effectLayers;
  105654. if (layers && layers.length > 0) {
  105655. this._previousStencilState = this._engine.getStencilBuffer();
  105656. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  105657. var effectLayer = layers_4[_i];
  105658. if (effectLayer.shouldRender() &&
  105659. (!effectLayer.camera ||
  105660. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  105661. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  105662. this._renderEffects = true;
  105663. this._needStencil = this._needStencil || effectLayer.needStencil();
  105664. var renderTarget = effectLayer._mainTexture;
  105665. if (renderTarget._shouldRender()) {
  105666. this.scene.incrementRenderId();
  105667. renderTarget.render(false, false);
  105668. }
  105669. }
  105670. }
  105671. this.scene.incrementRenderId();
  105672. }
  105673. };
  105674. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  105675. // Activate effect Layer stencil
  105676. if (this._needStencil) {
  105677. this._engine.setStencilBuffer(true);
  105678. }
  105679. };
  105680. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  105681. // Restore effect Layer stencil
  105682. if (this._needStencil) {
  105683. this._engine.setStencilBuffer(this._previousStencilState);
  105684. }
  105685. };
  105686. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  105687. if (this._renderEffects) {
  105688. this._engine.setDepthBuffer(false);
  105689. var layers = this.scene.effectLayers;
  105690. for (var i = 0; i < layers.length; i++) {
  105691. var effectLayer = layers[i];
  105692. if (effectLayer.renderingGroupId === renderingGroupId) {
  105693. if (effectLayer.shouldRender()) {
  105694. effectLayer.render();
  105695. }
  105696. }
  105697. }
  105698. this._engine.setDepthBuffer(true);
  105699. }
  105700. };
  105701. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  105702. if (this._renderEffects) {
  105703. this._draw(-1);
  105704. }
  105705. };
  105706. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  105707. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  105708. this._draw(index);
  105709. }
  105710. };
  105711. return EffectLayerSceneComponent;
  105712. }());
  105713. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  105714. })(BABYLON || (BABYLON = {}));
  105715. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  105716. var __assign = (this && this.__assign) || function () {
  105717. __assign = Object.assign || function(t) {
  105718. for (var s, i = 1, n = arguments.length; i < n; i++) {
  105719. s = arguments[i];
  105720. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  105721. t[p] = s[p];
  105722. }
  105723. return t;
  105724. };
  105725. return __assign.apply(this, arguments);
  105726. };
  105727. var BABYLON;
  105728. (function (BABYLON) {
  105729. /**
  105730. * The effect layer Helps adding post process effect blended with the main pass.
  105731. *
  105732. * This can be for instance use to generate glow or higlight effects on the scene.
  105733. *
  105734. * The effect layer class can not be used directly and is intented to inherited from to be
  105735. * customized per effects.
  105736. */
  105737. var EffectLayer = /** @class */ (function () {
  105738. /**
  105739. * Instantiates a new effect Layer and references it in the scene.
  105740. * @param name The name of the layer
  105741. * @param scene The scene to use the layer in
  105742. */
  105743. function EffectLayer(
  105744. /** The Friendly of the effect in the scene */
  105745. name, scene) {
  105746. this._vertexBuffers = {};
  105747. this._maxSize = 0;
  105748. this._mainTextureDesiredSize = { width: 0, height: 0 };
  105749. this._shouldRender = true;
  105750. this._postProcesses = [];
  105751. this._textures = [];
  105752. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  105753. /**
  105754. * The clear color of the texture used to generate the glow map.
  105755. */
  105756. this.neutralColor = new BABYLON.Color4();
  105757. /**
  105758. * Specifies wether the highlight layer is enabled or not.
  105759. */
  105760. this.isEnabled = true;
  105761. /**
  105762. * An event triggered when the effect layer has been disposed.
  105763. */
  105764. this.onDisposeObservable = new BABYLON.Observable();
  105765. /**
  105766. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  105767. */
  105768. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  105769. /**
  105770. * An event triggered when the generated texture is being merged in the scene.
  105771. */
  105772. this.onBeforeComposeObservable = new BABYLON.Observable();
  105773. /**
  105774. * An event triggered when the generated texture has been merged in the scene.
  105775. */
  105776. this.onAfterComposeObservable = new BABYLON.Observable();
  105777. /**
  105778. * An event triggered when the efffect layer changes its size.
  105779. */
  105780. this.onSizeChangedObservable = new BABYLON.Observable();
  105781. this.name = name;
  105782. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  105783. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  105784. if (!component) {
  105785. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  105786. this._scene._addComponent(component);
  105787. }
  105788. this._engine = this._scene.getEngine();
  105789. this._maxSize = this._engine.getCaps().maxTextureSize;
  105790. this._scene.effectLayers.push(this);
  105791. // Generate Buffers
  105792. this._generateIndexBuffer();
  105793. this._genrateVertexBuffer();
  105794. }
  105795. Object.defineProperty(EffectLayer.prototype, "camera", {
  105796. /**
  105797. * Gets the camera attached to the layer.
  105798. */
  105799. get: function () {
  105800. return this._effectLayerOptions.camera;
  105801. },
  105802. enumerable: true,
  105803. configurable: true
  105804. });
  105805. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  105806. /**
  105807. * Gets the rendering group id the layer should render in.
  105808. */
  105809. get: function () {
  105810. return this._effectLayerOptions.renderingGroupId;
  105811. },
  105812. enumerable: true,
  105813. configurable: true
  105814. });
  105815. /**
  105816. * Initializes the effect layer with the required options.
  105817. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  105818. */
  105819. EffectLayer.prototype._init = function (options) {
  105820. // Adapt options
  105821. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  105822. this._setMainTextureSize();
  105823. this._createMainTexture();
  105824. this._createTextureAndPostProcesses();
  105825. this._mergeEffect = this._createMergeEffect();
  105826. };
  105827. /**
  105828. * Generates the index buffer of the full screen quad blending to the main canvas.
  105829. */
  105830. EffectLayer.prototype._generateIndexBuffer = function () {
  105831. // Indices
  105832. var indices = [];
  105833. indices.push(0);
  105834. indices.push(1);
  105835. indices.push(2);
  105836. indices.push(0);
  105837. indices.push(2);
  105838. indices.push(3);
  105839. this._indexBuffer = this._engine.createIndexBuffer(indices);
  105840. };
  105841. /**
  105842. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  105843. */
  105844. EffectLayer.prototype._genrateVertexBuffer = function () {
  105845. // VBO
  105846. var vertices = [];
  105847. vertices.push(1, 1);
  105848. vertices.push(-1, 1);
  105849. vertices.push(-1, -1);
  105850. vertices.push(1, -1);
  105851. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105852. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105853. };
  105854. /**
  105855. * Sets the main texture desired size which is the closest power of two
  105856. * of the engine canvas size.
  105857. */
  105858. EffectLayer.prototype._setMainTextureSize = function () {
  105859. if (this._effectLayerOptions.mainTextureFixedSize) {
  105860. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  105861. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  105862. }
  105863. else {
  105864. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  105865. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  105866. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  105867. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  105868. }
  105869. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  105870. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  105871. };
  105872. /**
  105873. * Creates the main texture for the effect layer.
  105874. */
  105875. EffectLayer.prototype._createMainTexture = function () {
  105876. var _this = this;
  105877. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  105878. width: this._mainTextureDesiredSize.width,
  105879. height: this._mainTextureDesiredSize.height
  105880. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105881. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  105882. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105883. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105884. this._mainTexture.anisotropicFilteringLevel = 1;
  105885. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105886. this._mainTexture.renderParticles = false;
  105887. this._mainTexture.renderList = null;
  105888. this._mainTexture.ignoreCameraViewport = true;
  105889. // Custom render function
  105890. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  105891. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  105892. var index;
  105893. var engine = _this._scene.getEngine();
  105894. if (depthOnlySubMeshes.length) {
  105895. engine.setColorWrite(false);
  105896. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  105897. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  105898. }
  105899. engine.setColorWrite(true);
  105900. }
  105901. for (index = 0; index < opaqueSubMeshes.length; index++) {
  105902. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  105903. }
  105904. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  105905. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  105906. }
  105907. for (index = 0; index < transparentSubMeshes.length; index++) {
  105908. _this._renderSubMesh(transparentSubMeshes.data[index]);
  105909. }
  105910. };
  105911. this._mainTexture.onClearObservable.add(function (engine) {
  105912. engine.clear(_this.neutralColor, true, true, true);
  105913. });
  105914. };
  105915. /**
  105916. * Checks for the readiness of the element composing the layer.
  105917. * @param subMesh the mesh to check for
  105918. * @param useInstances specify wether or not to use instances to render the mesh
  105919. * @param emissiveTexture the associated emissive texture used to generate the glow
  105920. * @return true if ready otherwise, false
  105921. */
  105922. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  105923. var material = subMesh.getMaterial();
  105924. if (!material) {
  105925. return false;
  105926. }
  105927. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  105928. return false;
  105929. }
  105930. var defines = [];
  105931. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105932. var mesh = subMesh.getMesh();
  105933. var uv1 = false;
  105934. var uv2 = false;
  105935. // Alpha test
  105936. if (material && material.needAlphaTesting()) {
  105937. var alphaTexture = material.getAlphaTestTexture();
  105938. if (alphaTexture) {
  105939. defines.push("#define ALPHATEST");
  105940. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105941. alphaTexture.coordinatesIndex === 1) {
  105942. defines.push("#define DIFFUSEUV2");
  105943. uv2 = true;
  105944. }
  105945. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105946. defines.push("#define DIFFUSEUV1");
  105947. uv1 = true;
  105948. }
  105949. }
  105950. }
  105951. // Emissive
  105952. if (emissiveTexture) {
  105953. defines.push("#define EMISSIVE");
  105954. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105955. emissiveTexture.coordinatesIndex === 1) {
  105956. defines.push("#define EMISSIVEUV2");
  105957. uv2 = true;
  105958. }
  105959. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105960. defines.push("#define EMISSIVEUV1");
  105961. uv1 = true;
  105962. }
  105963. }
  105964. if (uv1) {
  105965. attribs.push(BABYLON.VertexBuffer.UVKind);
  105966. defines.push("#define UV1");
  105967. }
  105968. if (uv2) {
  105969. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105970. defines.push("#define UV2");
  105971. }
  105972. // Bones
  105973. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  105974. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  105975. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  105976. if (mesh.numBoneInfluencers > 4) {
  105977. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  105978. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  105979. }
  105980. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  105981. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  105982. }
  105983. else {
  105984. defines.push("#define NUM_BONE_INFLUENCERS 0");
  105985. }
  105986. // Morph targets
  105987. var manager = mesh.morphTargetManager;
  105988. var morphInfluencers = 0;
  105989. if (manager) {
  105990. if (manager.numInfluencers > 0) {
  105991. defines.push("#define MORPHTARGETS");
  105992. morphInfluencers = manager.numInfluencers;
  105993. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  105994. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  105995. }
  105996. }
  105997. // Instances
  105998. if (useInstances) {
  105999. defines.push("#define INSTANCES");
  106000. attribs.push("world0");
  106001. attribs.push("world1");
  106002. attribs.push("world2");
  106003. attribs.push("world3");
  106004. }
  106005. // Get correct effect
  106006. var join = defines.join("\n");
  106007. if (this._cachedDefines !== join) {
  106008. this._cachedDefines = join;
  106009. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  106010. }
  106011. return this._effectLayerMapGenerationEffect.isReady();
  106012. };
  106013. /**
  106014. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  106015. */
  106016. EffectLayer.prototype.render = function () {
  106017. var currentEffect = this._mergeEffect;
  106018. // Check
  106019. if (!currentEffect.isReady())
  106020. return;
  106021. for (var i = 0; i < this._postProcesses.length; i++) {
  106022. if (!this._postProcesses[i].isReady()) {
  106023. return;
  106024. }
  106025. }
  106026. var engine = this._scene.getEngine();
  106027. this.onBeforeComposeObservable.notifyObservers(this);
  106028. // Render
  106029. engine.enableEffect(currentEffect);
  106030. engine.setState(false);
  106031. // VBOs
  106032. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  106033. // Cache
  106034. var previousAlphaMode = engine.getAlphaMode();
  106035. // Go Blend.
  106036. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  106037. // Blends the map on the main canvas.
  106038. this._internalRender(currentEffect);
  106039. // Restore Alpha
  106040. engine.setAlphaMode(previousAlphaMode);
  106041. this.onAfterComposeObservable.notifyObservers(this);
  106042. // Handle size changes.
  106043. var size = this._mainTexture.getSize();
  106044. this._setMainTextureSize();
  106045. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  106046. // Recreate RTT and post processes on size change.
  106047. this.onSizeChangedObservable.notifyObservers(this);
  106048. this._disposeTextureAndPostProcesses();
  106049. this._createMainTexture();
  106050. this._createTextureAndPostProcesses();
  106051. }
  106052. };
  106053. /**
  106054. * Determine if a given mesh will be used in the current effect.
  106055. * @param mesh mesh to test
  106056. * @returns true if the mesh will be used
  106057. */
  106058. EffectLayer.prototype.hasMesh = function (mesh) {
  106059. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  106060. return true;
  106061. }
  106062. return false;
  106063. };
  106064. /**
  106065. * Returns true if the layer contains information to display, otherwise false.
  106066. * @returns true if the glow layer should be rendered
  106067. */
  106068. EffectLayer.prototype.shouldRender = function () {
  106069. return this.isEnabled && this._shouldRender;
  106070. };
  106071. /**
  106072. * Returns true if the mesh should render, otherwise false.
  106073. * @param mesh The mesh to render
  106074. * @returns true if it should render otherwise false
  106075. */
  106076. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  106077. return true;
  106078. };
  106079. /**
  106080. * Returns true if the mesh should render, otherwise false.
  106081. * @param mesh The mesh to render
  106082. * @returns true if it should render otherwise false
  106083. */
  106084. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  106085. return true;
  106086. };
  106087. /**
  106088. * Renders the submesh passed in parameter to the generation map.
  106089. */
  106090. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  106091. var _this = this;
  106092. if (!this.shouldRender()) {
  106093. return;
  106094. }
  106095. var material = subMesh.getMaterial();
  106096. var mesh = subMesh.getRenderingMesh();
  106097. var scene = this._scene;
  106098. var engine = scene.getEngine();
  106099. if (!material) {
  106100. return;
  106101. }
  106102. // Do not block in blend mode.
  106103. if (material.needAlphaBlendingForMesh(mesh)) {
  106104. return;
  106105. }
  106106. // Culling
  106107. engine.setState(material.backFaceCulling);
  106108. // Managing instances
  106109. var batch = mesh._getInstancesRenderList(subMesh._id);
  106110. if (batch.mustReturn) {
  106111. return;
  106112. }
  106113. // Early Exit per mesh
  106114. if (!this._shouldRenderMesh(mesh)) {
  106115. return;
  106116. }
  106117. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  106118. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  106119. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  106120. engine.enableEffect(this._effectLayerMapGenerationEffect);
  106121. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  106122. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  106123. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  106124. // Alpha test
  106125. if (material && material.needAlphaTesting()) {
  106126. var alphaTexture = material.getAlphaTestTexture();
  106127. if (alphaTexture) {
  106128. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  106129. var textureMatrix = alphaTexture.getTextureMatrix();
  106130. if (textureMatrix) {
  106131. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  106132. }
  106133. }
  106134. }
  106135. // Glow emissive only
  106136. if (this._emissiveTextureAndColor.texture) {
  106137. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  106138. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  106139. }
  106140. // Bones
  106141. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  106142. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  106143. }
  106144. // Morph targets
  106145. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  106146. // Draw
  106147. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  106148. }
  106149. else {
  106150. // Need to reset refresh rate of the main map
  106151. this._mainTexture.resetRefreshCounter();
  106152. }
  106153. };
  106154. /**
  106155. * Rebuild the required buffers.
  106156. * @hidden Internal use only.
  106157. */
  106158. EffectLayer.prototype._rebuild = function () {
  106159. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106160. if (vb) {
  106161. vb._rebuild();
  106162. }
  106163. this._generateIndexBuffer();
  106164. };
  106165. /**
  106166. * Dispose only the render target textures and post process.
  106167. */
  106168. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  106169. this._mainTexture.dispose();
  106170. for (var i = 0; i < this._postProcesses.length; i++) {
  106171. if (this._postProcesses[i]) {
  106172. this._postProcesses[i].dispose();
  106173. }
  106174. }
  106175. this._postProcesses = [];
  106176. for (var i = 0; i < this._textures.length; i++) {
  106177. if (this._textures[i]) {
  106178. this._textures[i].dispose();
  106179. }
  106180. }
  106181. this._textures = [];
  106182. };
  106183. /**
  106184. * Dispose the highlight layer and free resources.
  106185. */
  106186. EffectLayer.prototype.dispose = function () {
  106187. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106188. if (vertexBuffer) {
  106189. vertexBuffer.dispose();
  106190. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  106191. }
  106192. if (this._indexBuffer) {
  106193. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  106194. this._indexBuffer = null;
  106195. }
  106196. // Clean textures and post processes
  106197. this._disposeTextureAndPostProcesses();
  106198. // Remove from scene
  106199. var index = this._scene.effectLayers.indexOf(this, 0);
  106200. if (index > -1) {
  106201. this._scene.effectLayers.splice(index, 1);
  106202. }
  106203. // Callback
  106204. this.onDisposeObservable.notifyObservers(this);
  106205. this.onDisposeObservable.clear();
  106206. this.onBeforeRenderMainTextureObservable.clear();
  106207. this.onBeforeComposeObservable.clear();
  106208. this.onAfterComposeObservable.clear();
  106209. this.onSizeChangedObservable.clear();
  106210. };
  106211. /**
  106212. * Gets the class name of the effect layer
  106213. * @returns the string with the class name of the effect layer
  106214. */
  106215. EffectLayer.prototype.getClassName = function () {
  106216. return "EffectLayer";
  106217. };
  106218. /**
  106219. * Creates an effect layer from parsed effect layer data
  106220. * @param parsedEffectLayer defines effect layer data
  106221. * @param scene defines the current scene
  106222. * @param rootUrl defines the root URL containing the effect layer information
  106223. * @returns a parsed effect Layer
  106224. */
  106225. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  106226. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  106227. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  106228. };
  106229. __decorate([
  106230. BABYLON.serialize()
  106231. ], EffectLayer.prototype, "name", void 0);
  106232. __decorate([
  106233. BABYLON.serializeAsColor4()
  106234. ], EffectLayer.prototype, "neutralColor", void 0);
  106235. __decorate([
  106236. BABYLON.serialize()
  106237. ], EffectLayer.prototype, "isEnabled", void 0);
  106238. __decorate([
  106239. BABYLON.serializeAsCameraReference()
  106240. ], EffectLayer.prototype, "camera", null);
  106241. __decorate([
  106242. BABYLON.serialize()
  106243. ], EffectLayer.prototype, "renderingGroupId", null);
  106244. return EffectLayer;
  106245. }());
  106246. BABYLON.EffectLayer = EffectLayer;
  106247. })(BABYLON || (BABYLON = {}));
  106248. //# sourceMappingURL=babylon.effectLayer.js.map
  106249. var BABYLON;
  106250. (function (BABYLON) {
  106251. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  106252. for (var index = 0; index < this.effectLayers.length; index++) {
  106253. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  106254. return this.effectLayers[index];
  106255. }
  106256. }
  106257. return null;
  106258. };
  106259. /**
  106260. * Special Glow Blur post process only blurring the alpha channel
  106261. * It enforces keeping the most luminous color in the color channel.
  106262. */
  106263. var GlowBlurPostProcess = /** @class */ (function (_super) {
  106264. __extends(GlowBlurPostProcess, _super);
  106265. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  106266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  106267. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  106268. _this.direction = direction;
  106269. _this.kernel = kernel;
  106270. _this.onApplyObservable.add(function (effect) {
  106271. effect.setFloat2("screenSize", _this.width, _this.height);
  106272. effect.setVector2("direction", _this.direction);
  106273. effect.setFloat("blurWidth", _this.kernel);
  106274. });
  106275. return _this;
  106276. }
  106277. return GlowBlurPostProcess;
  106278. }(BABYLON.PostProcess));
  106279. /**
  106280. * The highlight layer Helps adding a glow effect around a mesh.
  106281. *
  106282. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  106283. * glowy meshes to your scene.
  106284. *
  106285. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  106286. */
  106287. var HighlightLayer = /** @class */ (function (_super) {
  106288. __extends(HighlightLayer, _super);
  106289. /**
  106290. * Instantiates a new highlight Layer and references it to the scene..
  106291. * @param name The name of the layer
  106292. * @param scene The scene to use the layer in
  106293. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  106294. */
  106295. function HighlightLayer(name, scene, options) {
  106296. var _this = _super.call(this, name, scene) || this;
  106297. _this.name = name;
  106298. /**
  106299. * Specifies whether or not the inner glow is ACTIVE in the layer.
  106300. */
  106301. _this.innerGlow = true;
  106302. /**
  106303. * Specifies whether or not the outer glow is ACTIVE in the layer.
  106304. */
  106305. _this.outerGlow = true;
  106306. /**
  106307. * An event triggered when the highlight layer is being blurred.
  106308. */
  106309. _this.onBeforeBlurObservable = new BABYLON.Observable();
  106310. /**
  106311. * An event triggered when the highlight layer has been blurred.
  106312. */
  106313. _this.onAfterBlurObservable = new BABYLON.Observable();
  106314. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  106315. _this._meshes = {};
  106316. _this._excludedMeshes = {};
  106317. _this.neutralColor = HighlightLayer.NeutralColor;
  106318. // Warn on stencil
  106319. if (!_this._engine.isStencilEnable) {
  106320. 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 }");
  106321. }
  106322. // Adapt options
  106323. _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);
  106324. // Initialize the layer
  106325. _this._init({
  106326. alphaBlendingMode: _this._options.alphaBlendingMode,
  106327. camera: _this._options.camera,
  106328. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  106329. mainTextureRatio: _this._options.mainTextureRatio,
  106330. renderingGroupId: _this._options.renderingGroupId
  106331. });
  106332. // Do not render as long as no meshes have been added
  106333. _this._shouldRender = false;
  106334. return _this;
  106335. }
  106336. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  106337. /**
  106338. * Gets the horizontal size of the blur.
  106339. */
  106340. get: function () {
  106341. return this._horizontalBlurPostprocess.kernel;
  106342. },
  106343. /**
  106344. * Specifies the horizontal size of the blur.
  106345. */
  106346. set: function (value) {
  106347. this._horizontalBlurPostprocess.kernel = value;
  106348. },
  106349. enumerable: true,
  106350. configurable: true
  106351. });
  106352. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  106353. /**
  106354. * Gets the vertical size of the blur.
  106355. */
  106356. get: function () {
  106357. return this._verticalBlurPostprocess.kernel;
  106358. },
  106359. /**
  106360. * Specifies the vertical size of the blur.
  106361. */
  106362. set: function (value) {
  106363. this._verticalBlurPostprocess.kernel = value;
  106364. },
  106365. enumerable: true,
  106366. configurable: true
  106367. });
  106368. /**
  106369. * Get the effect name of the layer.
  106370. * @return The effect name
  106371. */
  106372. HighlightLayer.prototype.getEffectName = function () {
  106373. return HighlightLayer.EffectName;
  106374. };
  106375. /**
  106376. * Create the merge effect. This is the shader use to blit the information back
  106377. * to the main canvas at the end of the scene rendering.
  106378. */
  106379. HighlightLayer.prototype._createMergeEffect = function () {
  106380. // Effect
  106381. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  106382. };
  106383. /**
  106384. * Creates the render target textures and post processes used in the highlight layer.
  106385. */
  106386. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  106387. var _this = this;
  106388. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  106389. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  106390. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  106391. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  106392. var textureType = 0;
  106393. if (this._engine.getCaps().textureHalfFloatRender) {
  106394. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  106395. }
  106396. else {
  106397. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106398. }
  106399. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  106400. width: blurTextureWidth,
  106401. height: blurTextureHeight
  106402. }, this._scene, false, true, textureType);
  106403. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106404. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106405. this._blurTexture.anisotropicFilteringLevel = 16;
  106406. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  106407. this._blurTexture.renderParticles = false;
  106408. this._blurTexture.ignoreCameraViewport = true;
  106409. this._textures = [this._blurTexture];
  106410. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  106411. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  106412. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  106413. effect.setTexture("textureSampler", _this._mainTexture);
  106414. });
  106415. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  106416. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  106417. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  106418. });
  106419. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  106420. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  106421. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  106422. });
  106423. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  106424. }
  106425. else {
  106426. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  106427. width: blurTextureWidth,
  106428. height: blurTextureHeight
  106429. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106430. this._horizontalBlurPostprocess.width = blurTextureWidth;
  106431. this._horizontalBlurPostprocess.height = blurTextureHeight;
  106432. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  106433. effect.setTexture("textureSampler", _this._mainTexture);
  106434. });
  106435. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  106436. width: blurTextureWidth,
  106437. height: blurTextureHeight
  106438. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106439. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  106440. }
  106441. this._mainTexture.onAfterUnbindObservable.add(function () {
  106442. _this.onBeforeBlurObservable.notifyObservers(_this);
  106443. var internalTexture = _this._blurTexture.getInternalTexture();
  106444. if (internalTexture) {
  106445. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  106446. }
  106447. _this.onAfterBlurObservable.notifyObservers(_this);
  106448. });
  106449. // Prevent autoClear.
  106450. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  106451. };
  106452. /**
  106453. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  106454. */
  106455. HighlightLayer.prototype.needStencil = function () {
  106456. return true;
  106457. };
  106458. /**
  106459. * Checks for the readiness of the element composing the layer.
  106460. * @param subMesh the mesh to check for
  106461. * @param useInstances specify wether or not to use instances to render the mesh
  106462. * @param emissiveTexture the associated emissive texture used to generate the glow
  106463. * @return true if ready otherwise, false
  106464. */
  106465. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  106466. var material = subMesh.getMaterial();
  106467. var mesh = subMesh.getRenderingMesh();
  106468. if (!material || !mesh || !this._meshes) {
  106469. return false;
  106470. }
  106471. var emissiveTexture = null;
  106472. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  106473. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  106474. emissiveTexture = material.emissiveTexture;
  106475. }
  106476. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  106477. };
  106478. /**
  106479. * Implementation specific of rendering the generating effect on the main canvas.
  106480. * @param effect The effect used to render through
  106481. */
  106482. HighlightLayer.prototype._internalRender = function (effect) {
  106483. // Texture
  106484. effect.setTexture("textureSampler", this._blurTexture);
  106485. // Cache
  106486. var engine = this._engine;
  106487. var previousStencilBuffer = engine.getStencilBuffer();
  106488. var previousStencilFunction = engine.getStencilFunction();
  106489. var previousStencilMask = engine.getStencilMask();
  106490. var previousStencilOperationPass = engine.getStencilOperationPass();
  106491. var previousStencilOperationFail = engine.getStencilOperationFail();
  106492. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  106493. var previousStencilReference = engine.getStencilFunctionReference();
  106494. // Stencil operations
  106495. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  106496. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  106497. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  106498. // Draw order
  106499. engine.setStencilMask(0x00);
  106500. engine.setStencilBuffer(true);
  106501. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  106502. // 2 passes inner outer
  106503. if (this.outerGlow) {
  106504. effect.setFloat("offset", 0);
  106505. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  106506. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106507. }
  106508. if (this.innerGlow) {
  106509. effect.setFloat("offset", 1);
  106510. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  106511. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106512. }
  106513. // Restore Cache
  106514. engine.setStencilFunction(previousStencilFunction);
  106515. engine.setStencilMask(previousStencilMask);
  106516. engine.setStencilBuffer(previousStencilBuffer);
  106517. engine.setStencilOperationPass(previousStencilOperationPass);
  106518. engine.setStencilOperationFail(previousStencilOperationFail);
  106519. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  106520. engine.setStencilFunctionReference(previousStencilReference);
  106521. };
  106522. /**
  106523. * Returns true if the layer contains information to display, otherwise false.
  106524. */
  106525. HighlightLayer.prototype.shouldRender = function () {
  106526. if (_super.prototype.shouldRender.call(this)) {
  106527. return this._meshes ? true : false;
  106528. }
  106529. return false;
  106530. };
  106531. /**
  106532. * Returns true if the mesh should render, otherwise false.
  106533. * @param mesh The mesh to render
  106534. * @returns true if it should render otherwise false
  106535. */
  106536. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  106537. // Excluded Mesh
  106538. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  106539. return false;
  106540. }
  106541. ;
  106542. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106543. return false;
  106544. }
  106545. return true;
  106546. };
  106547. /**
  106548. * Sets the required values for both the emissive texture and and the main color.
  106549. */
  106550. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  106551. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  106552. if (highlightLayerMesh) {
  106553. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  106554. }
  106555. else {
  106556. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  106557. }
  106558. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  106559. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  106560. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  106561. }
  106562. else {
  106563. this._emissiveTextureAndColor.texture = null;
  106564. }
  106565. };
  106566. /**
  106567. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  106568. * @param mesh The mesh to exclude from the highlight layer
  106569. */
  106570. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  106571. if (!this._excludedMeshes) {
  106572. return;
  106573. }
  106574. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  106575. if (!meshExcluded) {
  106576. this._excludedMeshes[mesh.uniqueId] = {
  106577. mesh: mesh,
  106578. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  106579. mesh.getEngine().setStencilBuffer(false);
  106580. }),
  106581. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  106582. mesh.getEngine().setStencilBuffer(true);
  106583. }),
  106584. };
  106585. }
  106586. };
  106587. /**
  106588. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  106589. * @param mesh The mesh to highlight
  106590. */
  106591. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  106592. if (!this._excludedMeshes) {
  106593. return;
  106594. }
  106595. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  106596. if (meshExcluded) {
  106597. if (meshExcluded.beforeRender) {
  106598. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  106599. }
  106600. if (meshExcluded.afterRender) {
  106601. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  106602. }
  106603. }
  106604. this._excludedMeshes[mesh.uniqueId] = null;
  106605. };
  106606. /**
  106607. * Determine if a given mesh will be highlighted by the current HighlightLayer
  106608. * @param mesh mesh to test
  106609. * @returns true if the mesh will be highlighted by the current HighlightLayer
  106610. */
  106611. HighlightLayer.prototype.hasMesh = function (mesh) {
  106612. if (!this._meshes) {
  106613. return false;
  106614. }
  106615. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106616. return false;
  106617. }
  106618. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  106619. };
  106620. /**
  106621. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  106622. * @param mesh The mesh to highlight
  106623. * @param color The color of the highlight
  106624. * @param glowEmissiveOnly Extract the glow from the emissive texture
  106625. */
  106626. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  106627. var _this = this;
  106628. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  106629. if (!this._meshes) {
  106630. return;
  106631. }
  106632. var meshHighlight = this._meshes[mesh.uniqueId];
  106633. if (meshHighlight) {
  106634. meshHighlight.color = color;
  106635. }
  106636. else {
  106637. this._meshes[mesh.uniqueId] = {
  106638. mesh: mesh,
  106639. color: color,
  106640. // Lambda required for capture due to Observable this context
  106641. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  106642. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  106643. _this._defaultStencilReference(mesh);
  106644. }
  106645. else {
  106646. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  106647. }
  106648. }),
  106649. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  106650. glowEmissiveOnly: glowEmissiveOnly
  106651. };
  106652. mesh.onDisposeObservable.add(function () {
  106653. _this._disposeMesh(mesh);
  106654. });
  106655. }
  106656. this._shouldRender = true;
  106657. };
  106658. /**
  106659. * Remove a mesh from the highlight layer in order to make it stop glowing.
  106660. * @param mesh The mesh to highlight
  106661. */
  106662. HighlightLayer.prototype.removeMesh = function (mesh) {
  106663. if (!this._meshes) {
  106664. return;
  106665. }
  106666. var meshHighlight = this._meshes[mesh.uniqueId];
  106667. if (meshHighlight) {
  106668. if (meshHighlight.observerHighlight) {
  106669. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106670. }
  106671. if (meshHighlight.observerDefault) {
  106672. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106673. }
  106674. delete this._meshes[mesh.uniqueId];
  106675. }
  106676. this._shouldRender = false;
  106677. for (var meshHighlightToCheck in this._meshes) {
  106678. if (this._meshes[meshHighlightToCheck]) {
  106679. this._shouldRender = true;
  106680. break;
  106681. }
  106682. }
  106683. };
  106684. /**
  106685. * Force the stencil to the normal expected value for none glowing parts
  106686. */
  106687. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  106688. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  106689. };
  106690. /**
  106691. * Free any resources and references associated to a mesh.
  106692. * Internal use
  106693. * @param mesh The mesh to free.
  106694. * @hidden
  106695. */
  106696. HighlightLayer.prototype._disposeMesh = function (mesh) {
  106697. this.removeMesh(mesh);
  106698. this.removeExcludedMesh(mesh);
  106699. };
  106700. /**
  106701. * Dispose the highlight layer and free resources.
  106702. */
  106703. HighlightLayer.prototype.dispose = function () {
  106704. if (this._meshes) {
  106705. // Clean mesh references
  106706. for (var id in this._meshes) {
  106707. var meshHighlight = this._meshes[id];
  106708. if (meshHighlight && meshHighlight.mesh) {
  106709. if (meshHighlight.observerHighlight) {
  106710. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106711. }
  106712. if (meshHighlight.observerDefault) {
  106713. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106714. }
  106715. }
  106716. }
  106717. this._meshes = null;
  106718. }
  106719. if (this._excludedMeshes) {
  106720. for (var id in this._excludedMeshes) {
  106721. var meshHighlight = this._excludedMeshes[id];
  106722. if (meshHighlight) {
  106723. if (meshHighlight.beforeRender) {
  106724. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  106725. }
  106726. if (meshHighlight.afterRender) {
  106727. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  106728. }
  106729. }
  106730. }
  106731. this._excludedMeshes = null;
  106732. }
  106733. _super.prototype.dispose.call(this);
  106734. };
  106735. /**
  106736. * Gets the class name of the effect layer
  106737. * @returns the string with the class name of the effect layer
  106738. */
  106739. HighlightLayer.prototype.getClassName = function () {
  106740. return "HighlightLayer";
  106741. };
  106742. /**
  106743. * Serializes this Highlight layer
  106744. * @returns a serialized Highlight layer object
  106745. */
  106746. HighlightLayer.prototype.serialize = function () {
  106747. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106748. serializationObject.customType = "BABYLON.HighlightLayer";
  106749. // Highlighted meshes
  106750. serializationObject.meshes = [];
  106751. if (this._meshes) {
  106752. for (var m in this._meshes) {
  106753. var mesh = this._meshes[m];
  106754. if (mesh) {
  106755. serializationObject.meshes.push({
  106756. glowEmissiveOnly: mesh.glowEmissiveOnly,
  106757. color: mesh.color.asArray(),
  106758. meshId: mesh.mesh.id
  106759. });
  106760. }
  106761. }
  106762. }
  106763. // Excluded meshes
  106764. serializationObject.excludedMeshes = [];
  106765. if (this._excludedMeshes) {
  106766. for (var e in this._excludedMeshes) {
  106767. var excludedMesh = this._excludedMeshes[e];
  106768. if (excludedMesh) {
  106769. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  106770. }
  106771. }
  106772. }
  106773. return serializationObject;
  106774. };
  106775. /**
  106776. * Creates a Highlight layer from parsed Highlight layer data
  106777. * @param parsedHightlightLayer defines the Highlight layer data
  106778. * @param scene defines the current scene
  106779. * @param rootUrl defines the root URL containing the Highlight layer information
  106780. * @returns a parsed Highlight layer
  106781. */
  106782. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  106783. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  106784. var index;
  106785. // Excluded meshes
  106786. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  106787. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  106788. if (mesh) {
  106789. hl.addExcludedMesh(mesh);
  106790. }
  106791. }
  106792. // Included meshes
  106793. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  106794. var highlightedMesh = parsedHightlightLayer.meshes[index];
  106795. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  106796. if (mesh) {
  106797. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  106798. }
  106799. }
  106800. return hl;
  106801. };
  106802. /**
  106803. * Effect Name of the highlight layer.
  106804. */
  106805. HighlightLayer.EffectName = "HighlightLayer";
  106806. /**
  106807. * The neutral color used during the preparation of the glow effect.
  106808. * This is black by default as the blend operation is a blend operation.
  106809. */
  106810. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  106811. /**
  106812. * Stencil value used for glowing meshes.
  106813. */
  106814. HighlightLayer.GlowingMeshStencilReference = 0x02;
  106815. /**
  106816. * Stencil value used for the other meshes in the scene.
  106817. */
  106818. HighlightLayer.NormalMeshStencilReference = 0x01;
  106819. __decorate([
  106820. BABYLON.serialize()
  106821. ], HighlightLayer.prototype, "innerGlow", void 0);
  106822. __decorate([
  106823. BABYLON.serialize()
  106824. ], HighlightLayer.prototype, "outerGlow", void 0);
  106825. __decorate([
  106826. BABYLON.serialize()
  106827. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  106828. __decorate([
  106829. BABYLON.serialize()
  106830. ], HighlightLayer.prototype, "blurVerticalSize", null);
  106831. __decorate([
  106832. BABYLON.serialize("options")
  106833. ], HighlightLayer.prototype, "_options", void 0);
  106834. return HighlightLayer;
  106835. }(BABYLON.EffectLayer));
  106836. BABYLON.HighlightLayer = HighlightLayer;
  106837. })(BABYLON || (BABYLON = {}));
  106838. //# sourceMappingURL=babylon.highlightLayer.js.map
  106839. var BABYLON;
  106840. (function (BABYLON) {
  106841. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  106842. for (var index = 0; index < this.effectLayers.length; index++) {
  106843. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  106844. return this.effectLayers[index];
  106845. }
  106846. }
  106847. return null;
  106848. };
  106849. /**
  106850. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  106851. *
  106852. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  106853. * glowy meshes to your scene.
  106854. *
  106855. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  106856. */
  106857. var GlowLayer = /** @class */ (function (_super) {
  106858. __extends(GlowLayer, _super);
  106859. /**
  106860. * Instantiates a new glow Layer and references it to the scene.
  106861. * @param name The name of the layer
  106862. * @param scene The scene to use the layer in
  106863. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  106864. */
  106865. function GlowLayer(name, scene, options) {
  106866. var _this = _super.call(this, name, scene) || this;
  106867. _this._intensity = 1.0;
  106868. _this._includedOnlyMeshes = [];
  106869. _this._excludedMeshes = [];
  106870. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  106871. // Adapt options
  106872. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  106873. // Initialize the layer
  106874. _this._init({
  106875. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  106876. camera: _this._options.camera,
  106877. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  106878. mainTextureRatio: _this._options.mainTextureRatio,
  106879. renderingGroupId: _this._options.renderingGroupId
  106880. });
  106881. return _this;
  106882. }
  106883. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  106884. /**
  106885. * Gets the kernel size of the blur.
  106886. */
  106887. get: function () {
  106888. return this._horizontalBlurPostprocess1.kernel;
  106889. },
  106890. /**
  106891. * Sets the kernel size of the blur.
  106892. */
  106893. set: function (value) {
  106894. this._horizontalBlurPostprocess1.kernel = value;
  106895. this._verticalBlurPostprocess1.kernel = value;
  106896. this._horizontalBlurPostprocess2.kernel = value;
  106897. this._verticalBlurPostprocess2.kernel = value;
  106898. },
  106899. enumerable: true,
  106900. configurable: true
  106901. });
  106902. Object.defineProperty(GlowLayer.prototype, "intensity", {
  106903. /**
  106904. * Gets the glow intensity.
  106905. */
  106906. get: function () {
  106907. return this._intensity;
  106908. },
  106909. /**
  106910. * Sets the glow intensity.
  106911. */
  106912. set: function (value) {
  106913. this._intensity = value;
  106914. },
  106915. enumerable: true,
  106916. configurable: true
  106917. });
  106918. /**
  106919. * Get the effect name of the layer.
  106920. * @return The effect name
  106921. */
  106922. GlowLayer.prototype.getEffectName = function () {
  106923. return GlowLayer.EffectName;
  106924. };
  106925. /**
  106926. * Create the merge effect. This is the shader use to blit the information back
  106927. * to the main canvas at the end of the scene rendering.
  106928. */
  106929. GlowLayer.prototype._createMergeEffect = function () {
  106930. // Effect
  106931. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  106932. };
  106933. /**
  106934. * Creates the render target textures and post processes used in the glow layer.
  106935. */
  106936. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  106937. var _this = this;
  106938. var blurTextureWidth = this._mainTextureDesiredSize.width;
  106939. var blurTextureHeight = this._mainTextureDesiredSize.height;
  106940. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  106941. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  106942. var textureType = 0;
  106943. if (this._engine.getCaps().textureHalfFloatRender) {
  106944. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  106945. }
  106946. else {
  106947. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106948. }
  106949. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  106950. width: blurTextureWidth,
  106951. height: blurTextureHeight
  106952. }, this._scene, false, true, textureType);
  106953. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106954. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106955. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106956. this._blurTexture1.renderParticles = false;
  106957. this._blurTexture1.ignoreCameraViewport = true;
  106958. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  106959. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  106960. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  106961. width: blurTextureWidth2,
  106962. height: blurTextureHeight2
  106963. }, this._scene, false, true, textureType);
  106964. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106965. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106966. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106967. this._blurTexture2.renderParticles = false;
  106968. this._blurTexture2.ignoreCameraViewport = true;
  106969. this._textures = [this._blurTexture1, this._blurTexture2];
  106970. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106971. width: blurTextureWidth,
  106972. height: blurTextureHeight
  106973. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106974. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  106975. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  106976. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  106977. effect.setTexture("textureSampler", _this._mainTexture);
  106978. });
  106979. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106980. width: blurTextureWidth,
  106981. height: blurTextureHeight
  106982. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106983. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106984. width: blurTextureWidth2,
  106985. height: blurTextureHeight2
  106986. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106987. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  106988. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  106989. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  106990. effect.setTexture("textureSampler", _this._blurTexture1);
  106991. });
  106992. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106993. width: blurTextureWidth2,
  106994. height: blurTextureHeight2
  106995. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106996. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106997. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  106998. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106999. this._mainTexture.samples = this._options.mainTextureSamples;
  107000. this._mainTexture.onAfterUnbindObservable.add(function () {
  107001. var internalTexture = _this._blurTexture1.getInternalTexture();
  107002. if (internalTexture) {
  107003. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  107004. internalTexture = _this._blurTexture2.getInternalTexture();
  107005. if (internalTexture) {
  107006. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  107007. }
  107008. }
  107009. });
  107010. // Prevent autoClear.
  107011. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  107012. };
  107013. /**
  107014. * Checks for the readiness of the element composing the layer.
  107015. * @param subMesh the mesh to check for
  107016. * @param useInstances specify wether or not to use instances to render the mesh
  107017. * @param emissiveTexture the associated emissive texture used to generate the glow
  107018. * @return true if ready otherwise, false
  107019. */
  107020. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  107021. var material = subMesh.getMaterial();
  107022. var mesh = subMesh.getRenderingMesh();
  107023. if (!material || !mesh) {
  107024. return false;
  107025. }
  107026. var emissiveTexture = material.emissiveTexture;
  107027. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  107028. };
  107029. /**
  107030. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  107031. */
  107032. GlowLayer.prototype.needStencil = function () {
  107033. return false;
  107034. };
  107035. /**
  107036. * Implementation specific of rendering the generating effect on the main canvas.
  107037. * @param effect The effect used to render through
  107038. */
  107039. GlowLayer.prototype._internalRender = function (effect) {
  107040. // Texture
  107041. effect.setTexture("textureSampler", this._blurTexture1);
  107042. effect.setTexture("textureSampler2", this._blurTexture2);
  107043. effect.setFloat("offset", this._intensity);
  107044. // Cache
  107045. var engine = this._engine;
  107046. var previousStencilBuffer = engine.getStencilBuffer();
  107047. // Draw order
  107048. engine.setStencilBuffer(false);
  107049. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107050. // Draw order
  107051. engine.setStencilBuffer(previousStencilBuffer);
  107052. };
  107053. /**
  107054. * Sets the required values for both the emissive texture and and the main color.
  107055. */
  107056. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  107057. var textureLevel = 1.0;
  107058. if (this.customEmissiveTextureSelector) {
  107059. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  107060. }
  107061. else {
  107062. if (material) {
  107063. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  107064. if (this._emissiveTextureAndColor.texture) {
  107065. textureLevel = this._emissiveTextureAndColor.texture.level;
  107066. }
  107067. }
  107068. else {
  107069. this._emissiveTextureAndColor.texture = null;
  107070. }
  107071. }
  107072. if (this.customEmissiveColorSelector) {
  107073. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  107074. }
  107075. else {
  107076. if (material.emissiveColor) {
  107077. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  107078. }
  107079. else {
  107080. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  107081. }
  107082. }
  107083. };
  107084. /**
  107085. * Returns true if the mesh should render, otherwise false.
  107086. * @param mesh The mesh to render
  107087. * @returns true if it should render otherwise false
  107088. */
  107089. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  107090. return this.hasMesh(mesh);
  107091. };
  107092. /**
  107093. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  107094. * @param mesh The mesh to exclude from the glow layer
  107095. */
  107096. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  107097. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  107098. this._excludedMeshes.push(mesh.uniqueId);
  107099. }
  107100. };
  107101. /**
  107102. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  107103. * @param mesh The mesh to remove
  107104. */
  107105. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  107106. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  107107. if (index !== -1) {
  107108. this._excludedMeshes.splice(index, 1);
  107109. }
  107110. };
  107111. /**
  107112. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  107113. * @param mesh The mesh to include in the glow layer
  107114. */
  107115. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  107116. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  107117. this._includedOnlyMeshes.push(mesh.uniqueId);
  107118. }
  107119. };
  107120. /**
  107121. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  107122. * @param mesh The mesh to remove
  107123. */
  107124. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  107125. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  107126. if (index !== -1) {
  107127. this._includedOnlyMeshes.splice(index, 1);
  107128. }
  107129. };
  107130. /**
  107131. * Determine if a given mesh will be used in the glow layer
  107132. * @param mesh The mesh to test
  107133. * @returns true if the mesh will be highlighted by the current glow layer
  107134. */
  107135. GlowLayer.prototype.hasMesh = function (mesh) {
  107136. if (!_super.prototype.hasMesh.call(this, mesh)) {
  107137. return false;
  107138. }
  107139. // Included Mesh
  107140. if (this._includedOnlyMeshes.length) {
  107141. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  107142. }
  107143. ;
  107144. // Excluded Mesh
  107145. if (this._excludedMeshes.length) {
  107146. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  107147. }
  107148. ;
  107149. return true;
  107150. };
  107151. /**
  107152. * Free any resources and references associated to a mesh.
  107153. * Internal use
  107154. * @param mesh The mesh to free.
  107155. * @hidden
  107156. */
  107157. GlowLayer.prototype._disposeMesh = function (mesh) {
  107158. this.removeIncludedOnlyMesh(mesh);
  107159. this.removeExcludedMesh(mesh);
  107160. };
  107161. /**
  107162. * Gets the class name of the effect layer
  107163. * @returns the string with the class name of the effect layer
  107164. */
  107165. GlowLayer.prototype.getClassName = function () {
  107166. return "GlowLayer";
  107167. };
  107168. /**
  107169. * Serializes this glow layer
  107170. * @returns a serialized glow layer object
  107171. */
  107172. GlowLayer.prototype.serialize = function () {
  107173. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  107174. serializationObject.customType = "BABYLON.GlowLayer";
  107175. var index;
  107176. // Included meshes
  107177. serializationObject.includedMeshes = [];
  107178. if (this._includedOnlyMeshes.length) {
  107179. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  107180. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  107181. if (mesh) {
  107182. serializationObject.includedMeshes.push(mesh.id);
  107183. }
  107184. }
  107185. }
  107186. // Excluded meshes
  107187. serializationObject.excludedMeshes = [];
  107188. if (this._excludedMeshes.length) {
  107189. for (index = 0; index < this._excludedMeshes.length; index++) {
  107190. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  107191. if (mesh) {
  107192. serializationObject.excludedMeshes.push(mesh.id);
  107193. }
  107194. }
  107195. }
  107196. return serializationObject;
  107197. };
  107198. /**
  107199. * Creates a Glow Layer from parsed glow layer data
  107200. * @param parsedGlowLayer defines glow layer data
  107201. * @param scene defines the current scene
  107202. * @param rootUrl defines the root URL containing the glow layer information
  107203. * @returns a parsed Glow Layer
  107204. */
  107205. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  107206. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  107207. var index;
  107208. // Excluded meshes
  107209. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  107210. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  107211. if (mesh) {
  107212. gl.addExcludedMesh(mesh);
  107213. }
  107214. }
  107215. // Included meshes
  107216. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  107217. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  107218. if (mesh) {
  107219. gl.addIncludedOnlyMesh(mesh);
  107220. }
  107221. }
  107222. return gl;
  107223. };
  107224. /**
  107225. * Effect Name of the layer.
  107226. */
  107227. GlowLayer.EffectName = "GlowLayer";
  107228. /**
  107229. * The default blur kernel size used for the glow.
  107230. */
  107231. GlowLayer.DefaultBlurKernelSize = 32;
  107232. /**
  107233. * The default texture size ratio used for the glow.
  107234. */
  107235. GlowLayer.DefaultTextureRatio = 0.5;
  107236. __decorate([
  107237. BABYLON.serialize()
  107238. ], GlowLayer.prototype, "blurKernelSize", null);
  107239. __decorate([
  107240. BABYLON.serialize()
  107241. ], GlowLayer.prototype, "intensity", null);
  107242. __decorate([
  107243. BABYLON.serialize("options")
  107244. ], GlowLayer.prototype, "_options", void 0);
  107245. return GlowLayer;
  107246. }(BABYLON.EffectLayer));
  107247. BABYLON.GlowLayer = GlowLayer;
  107248. })(BABYLON || (BABYLON = {}));
  107249. //# sourceMappingURL=babylon.glowLayer.js.map
  107250. var BABYLON;
  107251. (function (BABYLON) {
  107252. /**
  107253. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  107254. */
  107255. var AssetTaskState;
  107256. (function (AssetTaskState) {
  107257. /**
  107258. * Initialization
  107259. */
  107260. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  107261. /**
  107262. * Running
  107263. */
  107264. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  107265. /**
  107266. * Done
  107267. */
  107268. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  107269. /**
  107270. * Error
  107271. */
  107272. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  107273. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  107274. /**
  107275. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  107276. */
  107277. var AbstractAssetTask = /** @class */ (function () {
  107278. /**
  107279. * Creates a new {BABYLON.AssetsManager}
  107280. * @param name defines the name of the task
  107281. */
  107282. function AbstractAssetTask(
  107283. /**
  107284. * Task name
  107285. */ name) {
  107286. this.name = name;
  107287. this._isCompleted = false;
  107288. this._taskState = AssetTaskState.INIT;
  107289. }
  107290. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  107291. /**
  107292. * Get if the task is completed
  107293. */
  107294. get: function () {
  107295. return this._isCompleted;
  107296. },
  107297. enumerable: true,
  107298. configurable: true
  107299. });
  107300. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  107301. /**
  107302. * Gets the current state of the task
  107303. */
  107304. get: function () {
  107305. return this._taskState;
  107306. },
  107307. enumerable: true,
  107308. configurable: true
  107309. });
  107310. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  107311. /**
  107312. * Gets the current error object (if task is in error)
  107313. */
  107314. get: function () {
  107315. return this._errorObject;
  107316. },
  107317. enumerable: true,
  107318. configurable: true
  107319. });
  107320. /**
  107321. * Internal only
  107322. * @hidden
  107323. */
  107324. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  107325. if (this._errorObject) {
  107326. return;
  107327. }
  107328. this._errorObject = {
  107329. message: message,
  107330. exception: exception
  107331. };
  107332. };
  107333. /**
  107334. * Execute the current task
  107335. * @param scene defines the scene where you want your assets to be loaded
  107336. * @param onSuccess is a callback called when the task is successfully executed
  107337. * @param onError is a callback called if an error occurs
  107338. */
  107339. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  107340. var _this = this;
  107341. this._taskState = AssetTaskState.RUNNING;
  107342. this.runTask(scene, function () {
  107343. _this.onDoneCallback(onSuccess, onError);
  107344. }, function (msg, exception) {
  107345. _this.onErrorCallback(onError, msg, exception);
  107346. });
  107347. };
  107348. /**
  107349. * Execute the current task
  107350. * @param scene defines the scene where you want your assets to be loaded
  107351. * @param onSuccess is a callback called when the task is successfully executed
  107352. * @param onError is a callback called if an error occurs
  107353. */
  107354. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107355. throw new Error("runTask is not implemented");
  107356. };
  107357. /**
  107358. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  107359. * This can be used with failed tasks that have the reason for failure fixed.
  107360. */
  107361. AbstractAssetTask.prototype.reset = function () {
  107362. this._taskState = AssetTaskState.INIT;
  107363. };
  107364. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  107365. this._taskState = AssetTaskState.ERROR;
  107366. this._errorObject = {
  107367. message: message,
  107368. exception: exception
  107369. };
  107370. if (this.onError) {
  107371. this.onError(this, message, exception);
  107372. }
  107373. onError();
  107374. };
  107375. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  107376. try {
  107377. this._taskState = AssetTaskState.DONE;
  107378. this._isCompleted = true;
  107379. if (this.onSuccess) {
  107380. this.onSuccess(this);
  107381. }
  107382. onSuccess();
  107383. }
  107384. catch (e) {
  107385. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  107386. }
  107387. };
  107388. return AbstractAssetTask;
  107389. }());
  107390. BABYLON.AbstractAssetTask = AbstractAssetTask;
  107391. /**
  107392. * Class used to share progress information about assets loading
  107393. */
  107394. var AssetsProgressEvent = /** @class */ (function () {
  107395. /**
  107396. * Creates a {BABYLON.AssetsProgressEvent}
  107397. * @param remainingCount defines the number of remaining tasks to process
  107398. * @param totalCount defines the total number of tasks
  107399. * @param task defines the task that was just processed
  107400. */
  107401. function AssetsProgressEvent(remainingCount, totalCount, task) {
  107402. this.remainingCount = remainingCount;
  107403. this.totalCount = totalCount;
  107404. this.task = task;
  107405. }
  107406. return AssetsProgressEvent;
  107407. }());
  107408. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  107409. /**
  107410. * Define a task used by {BABYLON.AssetsManager} to load meshes
  107411. */
  107412. var MeshAssetTask = /** @class */ (function (_super) {
  107413. __extends(MeshAssetTask, _super);
  107414. /**
  107415. * Creates a new {BABYLON.MeshAssetTask}
  107416. * @param name defines the name of the task
  107417. * @param meshesNames defines the list of mesh's names you want to load
  107418. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  107419. * @param sceneFilename defines the filename of the scene to load from
  107420. */
  107421. function MeshAssetTask(
  107422. /**
  107423. * Defines the name of the task
  107424. */
  107425. name,
  107426. /**
  107427. * Defines the list of mesh's names you want to load
  107428. */
  107429. meshesNames,
  107430. /**
  107431. * Defines the root url to use as a base to load your meshes and associated resources
  107432. */
  107433. rootUrl,
  107434. /**
  107435. * Defines the filename of the scene to load from
  107436. */
  107437. sceneFilename) {
  107438. var _this = _super.call(this, name) || this;
  107439. _this.name = name;
  107440. _this.meshesNames = meshesNames;
  107441. _this.rootUrl = rootUrl;
  107442. _this.sceneFilename = sceneFilename;
  107443. return _this;
  107444. }
  107445. /**
  107446. * Execute the current task
  107447. * @param scene defines the scene where you want your assets to be loaded
  107448. * @param onSuccess is a callback called when the task is successfully executed
  107449. * @param onError is a callback called if an error occurs
  107450. */
  107451. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107452. var _this = this;
  107453. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  107454. _this.loadedMeshes = meshes;
  107455. _this.loadedParticleSystems = particleSystems;
  107456. _this.loadedSkeletons = skeletons;
  107457. onSuccess();
  107458. }, null, function (scene, message, exception) {
  107459. onError(message, exception);
  107460. });
  107461. };
  107462. return MeshAssetTask;
  107463. }(AbstractAssetTask));
  107464. BABYLON.MeshAssetTask = MeshAssetTask;
  107465. /**
  107466. * Define a task used by {BABYLON.AssetsManager} to load text content
  107467. */
  107468. var TextFileAssetTask = /** @class */ (function (_super) {
  107469. __extends(TextFileAssetTask, _super);
  107470. /**
  107471. * Creates a new TextFileAssetTask object
  107472. * @param name defines the name of the task
  107473. * @param url defines the location of the file to load
  107474. */
  107475. function TextFileAssetTask(
  107476. /**
  107477. * Defines the name of the task
  107478. */
  107479. name,
  107480. /**
  107481. * Defines the location of the file to load
  107482. */
  107483. url) {
  107484. var _this = _super.call(this, name) || this;
  107485. _this.name = name;
  107486. _this.url = url;
  107487. return _this;
  107488. }
  107489. /**
  107490. * Execute the current task
  107491. * @param scene defines the scene where you want your assets to be loaded
  107492. * @param onSuccess is a callback called when the task is successfully executed
  107493. * @param onError is a callback called if an error occurs
  107494. */
  107495. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107496. var _this = this;
  107497. scene._loadFile(this.url, function (data) {
  107498. _this.text = data;
  107499. onSuccess();
  107500. }, undefined, false, false, function (request, exception) {
  107501. if (request) {
  107502. onError(request.status + " " + request.statusText, exception);
  107503. }
  107504. });
  107505. };
  107506. return TextFileAssetTask;
  107507. }(AbstractAssetTask));
  107508. BABYLON.TextFileAssetTask = TextFileAssetTask;
  107509. /**
  107510. * Define a task used by {BABYLON.AssetsManager} to load binary data
  107511. */
  107512. var BinaryFileAssetTask = /** @class */ (function (_super) {
  107513. __extends(BinaryFileAssetTask, _super);
  107514. /**
  107515. * Creates a new BinaryFileAssetTask object
  107516. * @param name defines the name of the new task
  107517. * @param url defines the location of the file to load
  107518. */
  107519. function BinaryFileAssetTask(
  107520. /**
  107521. * Defines the name of the task
  107522. */
  107523. name,
  107524. /**
  107525. * Defines the location of the file to load
  107526. */
  107527. url) {
  107528. var _this = _super.call(this, name) || this;
  107529. _this.name = name;
  107530. _this.url = url;
  107531. return _this;
  107532. }
  107533. /**
  107534. * Execute the current task
  107535. * @param scene defines the scene where you want your assets to be loaded
  107536. * @param onSuccess is a callback called when the task is successfully executed
  107537. * @param onError is a callback called if an error occurs
  107538. */
  107539. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107540. var _this = this;
  107541. scene._loadFile(this.url, function (data) {
  107542. _this.data = data;
  107543. onSuccess();
  107544. }, undefined, true, true, function (request, exception) {
  107545. if (request) {
  107546. onError(request.status + " " + request.statusText, exception);
  107547. }
  107548. });
  107549. };
  107550. return BinaryFileAssetTask;
  107551. }(AbstractAssetTask));
  107552. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  107553. /**
  107554. * Define a task used by {BABYLON.AssetsManager} to load images
  107555. */
  107556. var ImageAssetTask = /** @class */ (function (_super) {
  107557. __extends(ImageAssetTask, _super);
  107558. /**
  107559. * Creates a new ImageAssetTask
  107560. * @param name defines the name of the task
  107561. * @param url defines the location of the image to load
  107562. */
  107563. function ImageAssetTask(
  107564. /**
  107565. * Defines the name of the task
  107566. */
  107567. name,
  107568. /**
  107569. * Defines the location of the image to load
  107570. */
  107571. url) {
  107572. var _this = _super.call(this, name) || this;
  107573. _this.name = name;
  107574. _this.url = url;
  107575. return _this;
  107576. }
  107577. /**
  107578. * Execute the current task
  107579. * @param scene defines the scene where you want your assets to be loaded
  107580. * @param onSuccess is a callback called when the task is successfully executed
  107581. * @param onError is a callback called if an error occurs
  107582. */
  107583. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107584. var _this = this;
  107585. var img = new Image();
  107586. BABYLON.Tools.SetCorsBehavior(this.url, img);
  107587. img.onload = function () {
  107588. _this.image = img;
  107589. onSuccess();
  107590. };
  107591. img.onerror = function (err) {
  107592. onError("Error loading image", err);
  107593. };
  107594. img.src = this.url;
  107595. };
  107596. return ImageAssetTask;
  107597. }(AbstractAssetTask));
  107598. BABYLON.ImageAssetTask = ImageAssetTask;
  107599. /**
  107600. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  107601. */
  107602. var TextureAssetTask = /** @class */ (function (_super) {
  107603. __extends(TextureAssetTask, _super);
  107604. /**
  107605. * Creates a new TextureAssetTask object
  107606. * @param name defines the name of the task
  107607. * @param url defines the location of the file to load
  107608. * @param noMipmap defines if mipmap should not be generated (default is false)
  107609. * @param invertY defines if texture must be inverted on Y axis (default is false)
  107610. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107611. */
  107612. function TextureAssetTask(
  107613. /**
  107614. * Defines the name of the task
  107615. */
  107616. name,
  107617. /**
  107618. * Defines the location of the file to load
  107619. */
  107620. url,
  107621. /**
  107622. * Defines if mipmap should not be generated (default is false)
  107623. */
  107624. noMipmap,
  107625. /**
  107626. * Defines if texture must be inverted on Y axis (default is false)
  107627. */
  107628. invertY,
  107629. /**
  107630. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107631. */
  107632. samplingMode) {
  107633. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107634. var _this = _super.call(this, name) || this;
  107635. _this.name = name;
  107636. _this.url = url;
  107637. _this.noMipmap = noMipmap;
  107638. _this.invertY = invertY;
  107639. _this.samplingMode = samplingMode;
  107640. return _this;
  107641. }
  107642. /**
  107643. * Execute the current task
  107644. * @param scene defines the scene where you want your assets to be loaded
  107645. * @param onSuccess is a callback called when the task is successfully executed
  107646. * @param onError is a callback called if an error occurs
  107647. */
  107648. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107649. var onload = function () {
  107650. onSuccess();
  107651. };
  107652. var onerror = function (message, exception) {
  107653. onError(message, exception);
  107654. };
  107655. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  107656. };
  107657. return TextureAssetTask;
  107658. }(AbstractAssetTask));
  107659. BABYLON.TextureAssetTask = TextureAssetTask;
  107660. /**
  107661. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  107662. */
  107663. var CubeTextureAssetTask = /** @class */ (function (_super) {
  107664. __extends(CubeTextureAssetTask, _super);
  107665. /**
  107666. * Creates a new CubeTextureAssetTask
  107667. * @param name defines the name of the task
  107668. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107669. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107670. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107671. * @param files defines the explicit list of files (undefined by default)
  107672. */
  107673. function CubeTextureAssetTask(
  107674. /**
  107675. * Defines the name of the task
  107676. */
  107677. name,
  107678. /**
  107679. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107680. */
  107681. url,
  107682. /**
  107683. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107684. */
  107685. extensions,
  107686. /**
  107687. * Defines if mipmaps should not be generated (default is false)
  107688. */
  107689. noMipmap,
  107690. /**
  107691. * Defines the explicit list of files (undefined by default)
  107692. */
  107693. files) {
  107694. var _this = _super.call(this, name) || this;
  107695. _this.name = name;
  107696. _this.url = url;
  107697. _this.extensions = extensions;
  107698. _this.noMipmap = noMipmap;
  107699. _this.files = files;
  107700. return _this;
  107701. }
  107702. /**
  107703. * Execute the current task
  107704. * @param scene defines the scene where you want your assets to be loaded
  107705. * @param onSuccess is a callback called when the task is successfully executed
  107706. * @param onError is a callback called if an error occurs
  107707. */
  107708. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107709. var onload = function () {
  107710. onSuccess();
  107711. };
  107712. var onerror = function (message, exception) {
  107713. onError(message, exception);
  107714. };
  107715. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  107716. };
  107717. return CubeTextureAssetTask;
  107718. }(AbstractAssetTask));
  107719. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  107720. /**
  107721. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  107722. */
  107723. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  107724. __extends(HDRCubeTextureAssetTask, _super);
  107725. /**
  107726. * Creates a new HDRCubeTextureAssetTask object
  107727. * @param name defines the name of the task
  107728. * @param url defines the location of the file to load
  107729. * @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.
  107730. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107731. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107732. * @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)
  107733. * @param reserved Internal use only
  107734. */
  107735. function HDRCubeTextureAssetTask(
  107736. /**
  107737. * Defines the name of the task
  107738. */
  107739. name,
  107740. /**
  107741. * Defines the location of the file to load
  107742. */
  107743. url,
  107744. /**
  107745. * Defines the desired size (the more it increases the longer the generation will be)
  107746. */
  107747. size,
  107748. /**
  107749. * Defines if mipmaps should not be generated (default is false)
  107750. */
  107751. noMipmap,
  107752. /**
  107753. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107754. */
  107755. generateHarmonics,
  107756. /**
  107757. * 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)
  107758. */
  107759. gammaSpace,
  107760. /**
  107761. * Internal Use Only
  107762. */
  107763. reserved) {
  107764. if (noMipmap === void 0) { noMipmap = false; }
  107765. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107766. if (gammaSpace === void 0) { gammaSpace = false; }
  107767. if (reserved === void 0) { reserved = false; }
  107768. var _this = _super.call(this, name) || this;
  107769. _this.name = name;
  107770. _this.url = url;
  107771. _this.size = size;
  107772. _this.noMipmap = noMipmap;
  107773. _this.generateHarmonics = generateHarmonics;
  107774. _this.gammaSpace = gammaSpace;
  107775. _this.reserved = reserved;
  107776. return _this;
  107777. }
  107778. /**
  107779. * Execute the current task
  107780. * @param scene defines the scene where you want your assets to be loaded
  107781. * @param onSuccess is a callback called when the task is successfully executed
  107782. * @param onError is a callback called if an error occurs
  107783. */
  107784. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  107785. var onload = function () {
  107786. onSuccess();
  107787. };
  107788. var onerror = function (message, exception) {
  107789. onError(message, exception);
  107790. };
  107791. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  107792. };
  107793. return HDRCubeTextureAssetTask;
  107794. }(AbstractAssetTask));
  107795. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  107796. /**
  107797. * This class can be used to easily import assets into a scene
  107798. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  107799. */
  107800. var AssetsManager = /** @class */ (function () {
  107801. /**
  107802. * Creates a new AssetsManager
  107803. * @param scene defines the scene to work on
  107804. */
  107805. function AssetsManager(scene) {
  107806. this._isLoading = false;
  107807. this._tasks = new Array();
  107808. this._waitingTasksCount = 0;
  107809. this._totalTasksCount = 0;
  107810. /**
  107811. * Observable called when all tasks are processed
  107812. */
  107813. this.onTaskSuccessObservable = new BABYLON.Observable();
  107814. /**
  107815. * Observable called when a task had an error
  107816. */
  107817. this.onTaskErrorObservable = new BABYLON.Observable();
  107818. /**
  107819. * Observable called when a task is successful
  107820. */
  107821. this.onTasksDoneObservable = new BABYLON.Observable();
  107822. /**
  107823. * Observable called when a task is done (whatever the result is)
  107824. */
  107825. this.onProgressObservable = new BABYLON.Observable();
  107826. /**
  107827. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  107828. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  107829. */
  107830. this.useDefaultLoadingScreen = true;
  107831. this._scene = scene;
  107832. }
  107833. /**
  107834. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  107835. * @param taskName defines the name of the new task
  107836. * @param meshesNames defines the name of meshes to load
  107837. * @param rootUrl defines the root url to use to locate files
  107838. * @param sceneFilename defines the filename of the scene file
  107839. * @returns a new {BABYLON.MeshAssetTask} object
  107840. */
  107841. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  107842. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  107843. this._tasks.push(task);
  107844. return task;
  107845. };
  107846. /**
  107847. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  107848. * @param taskName defines the name of the new task
  107849. * @param url defines the url of the file to load
  107850. * @returns a new {BABYLON.TextFileAssetTask} object
  107851. */
  107852. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  107853. var task = new TextFileAssetTask(taskName, url);
  107854. this._tasks.push(task);
  107855. return task;
  107856. };
  107857. /**
  107858. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  107859. * @param taskName defines the name of the new task
  107860. * @param url defines the url of the file to load
  107861. * @returns a new {BABYLON.BinaryFileAssetTask} object
  107862. */
  107863. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  107864. var task = new BinaryFileAssetTask(taskName, url);
  107865. this._tasks.push(task);
  107866. return task;
  107867. };
  107868. /**
  107869. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  107870. * @param taskName defines the name of the new task
  107871. * @param url defines the url of the file to load
  107872. * @returns a new {BABYLON.ImageAssetTask} object
  107873. */
  107874. AssetsManager.prototype.addImageTask = function (taskName, url) {
  107875. var task = new ImageAssetTask(taskName, url);
  107876. this._tasks.push(task);
  107877. return task;
  107878. };
  107879. /**
  107880. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  107881. * @param taskName defines the name of the new task
  107882. * @param url defines the url of the file to load
  107883. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107884. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  107885. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  107886. * @returns a new {BABYLON.TextureAssetTask} object
  107887. */
  107888. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  107889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107890. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  107891. this._tasks.push(task);
  107892. return task;
  107893. };
  107894. /**
  107895. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  107896. * @param taskName defines the name of the new task
  107897. * @param url defines the url of the file to load
  107898. * @param extensions defines the extension to use to load the cube map (can be null)
  107899. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107900. * @param files defines the list of files to load (can be null)
  107901. * @returns a new {BABYLON.CubeTextureAssetTask} object
  107902. */
  107903. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  107904. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  107905. this._tasks.push(task);
  107906. return task;
  107907. };
  107908. /**
  107909. *
  107910. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  107911. * @param taskName defines the name of the new task
  107912. * @param url defines the url of the file to load
  107913. * @param size defines the size you want for the cubemap (can be null)
  107914. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107915. * @param generateHarmonics defines if you want to automatically generate (true by default)
  107916. * @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)
  107917. * @param reserved Internal use only
  107918. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  107919. */
  107920. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  107921. if (noMipmap === void 0) { noMipmap = false; }
  107922. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107923. if (gammaSpace === void 0) { gammaSpace = false; }
  107924. if (reserved === void 0) { reserved = false; }
  107925. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  107926. this._tasks.push(task);
  107927. return task;
  107928. };
  107929. /**
  107930. * Remove a task from the assets manager.
  107931. * @param task the task to remove
  107932. */
  107933. AssetsManager.prototype.removeTask = function (task) {
  107934. var index = this._tasks.indexOf(task);
  107935. if (index > -1) {
  107936. this._tasks.splice(index, 1);
  107937. }
  107938. };
  107939. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  107940. this._waitingTasksCount--;
  107941. try {
  107942. if (this.onProgress) {
  107943. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  107944. }
  107945. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  107946. }
  107947. catch (e) {
  107948. BABYLON.Tools.Error("Error running progress callbacks.");
  107949. console.log(e);
  107950. }
  107951. if (this._waitingTasksCount === 0) {
  107952. try {
  107953. if (this.onFinish) {
  107954. this.onFinish(this._tasks);
  107955. }
  107956. // Let's remove successfull tasks
  107957. var currentTasks = this._tasks.slice();
  107958. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  107959. var task = currentTasks_1[_i];
  107960. if (task.taskState === AssetTaskState.DONE) {
  107961. var index = this._tasks.indexOf(task);
  107962. if (index > -1) {
  107963. this._tasks.splice(index, 1);
  107964. }
  107965. }
  107966. }
  107967. this.onTasksDoneObservable.notifyObservers(this._tasks);
  107968. }
  107969. catch (e) {
  107970. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  107971. console.log(e);
  107972. }
  107973. this._isLoading = false;
  107974. this._scene.getEngine().hideLoadingUI();
  107975. }
  107976. };
  107977. AssetsManager.prototype._runTask = function (task) {
  107978. var _this = this;
  107979. var done = function () {
  107980. try {
  107981. if (_this.onTaskSuccess) {
  107982. _this.onTaskSuccess(task);
  107983. }
  107984. _this.onTaskSuccessObservable.notifyObservers(task);
  107985. _this._decreaseWaitingTasksCount(task);
  107986. }
  107987. catch (e) {
  107988. error("Error executing task success callbacks", e);
  107989. }
  107990. };
  107991. var error = function (message, exception) {
  107992. task._setErrorObject(message, exception);
  107993. if (_this.onTaskError) {
  107994. _this.onTaskError(task);
  107995. }
  107996. _this.onTaskErrorObservable.notifyObservers(task);
  107997. _this._decreaseWaitingTasksCount(task);
  107998. };
  107999. task.run(this._scene, done, error);
  108000. };
  108001. /**
  108002. * Reset the {BABYLON.AssetsManager} and remove all tasks
  108003. * @return the current instance of the {BABYLON.AssetsManager}
  108004. */
  108005. AssetsManager.prototype.reset = function () {
  108006. this._isLoading = false;
  108007. this._tasks = new Array();
  108008. return this;
  108009. };
  108010. /**
  108011. * Start the loading process
  108012. * @return the current instance of the {BABYLON.AssetsManager}
  108013. */
  108014. AssetsManager.prototype.load = function () {
  108015. if (this._isLoading) {
  108016. return this;
  108017. }
  108018. this._isLoading = true;
  108019. this._waitingTasksCount = this._tasks.length;
  108020. this._totalTasksCount = this._tasks.length;
  108021. if (this._waitingTasksCount === 0) {
  108022. this._isLoading = false;
  108023. if (this.onFinish) {
  108024. this.onFinish(this._tasks);
  108025. }
  108026. this.onTasksDoneObservable.notifyObservers(this._tasks);
  108027. return this;
  108028. }
  108029. if (this.useDefaultLoadingScreen) {
  108030. this._scene.getEngine().displayLoadingUI();
  108031. }
  108032. for (var index = 0; index < this._tasks.length; index++) {
  108033. var task = this._tasks[index];
  108034. if (task.taskState === AssetTaskState.INIT) {
  108035. this._runTask(task);
  108036. }
  108037. }
  108038. return this;
  108039. };
  108040. return AssetsManager;
  108041. }());
  108042. BABYLON.AssetsManager = AssetsManager;
  108043. })(BABYLON || (BABYLON = {}));
  108044. //# sourceMappingURL=babylon.assetsManager.js.map
  108045. var BABYLON;
  108046. (function (BABYLON) {
  108047. var serializedGeometries = [];
  108048. var serializeGeometry = function (geometry, serializationGeometries) {
  108049. if (serializedGeometries[geometry.id]) {
  108050. return;
  108051. }
  108052. if (geometry.doNotSerialize) {
  108053. return;
  108054. }
  108055. if (geometry instanceof BABYLON.BoxGeometry) {
  108056. serializationGeometries.boxes.push(geometry.serialize());
  108057. }
  108058. else if (geometry instanceof BABYLON.SphereGeometry) {
  108059. serializationGeometries.spheres.push(geometry.serialize());
  108060. }
  108061. else if (geometry instanceof BABYLON.CylinderGeometry) {
  108062. serializationGeometries.cylinders.push(geometry.serialize());
  108063. }
  108064. else if (geometry instanceof BABYLON.TorusGeometry) {
  108065. serializationGeometries.toruses.push(geometry.serialize());
  108066. }
  108067. else if (geometry instanceof BABYLON.GroundGeometry) {
  108068. serializationGeometries.grounds.push(geometry.serialize());
  108069. }
  108070. else if (geometry instanceof BABYLON.Plane) {
  108071. serializationGeometries.planes.push(geometry.serialize());
  108072. }
  108073. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  108074. serializationGeometries.torusKnots.push(geometry.serialize());
  108075. }
  108076. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  108077. throw new Error("Unknown primitive type");
  108078. }
  108079. else {
  108080. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  108081. }
  108082. serializedGeometries[geometry.id] = true;
  108083. };
  108084. var serializeMesh = function (mesh, serializationScene) {
  108085. var serializationObject = {};
  108086. // Geometry
  108087. var geometry = mesh._geometry;
  108088. if (geometry) {
  108089. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  108090. // 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
  108091. serializeGeometry(geometry, serializationScene.geometries);
  108092. }
  108093. }
  108094. // Custom
  108095. if (mesh.serialize) {
  108096. mesh.serialize(serializationObject);
  108097. }
  108098. return serializationObject;
  108099. };
  108100. var finalizeSingleMesh = function (mesh, serializationObject) {
  108101. //only works if the mesh is already loaded
  108102. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  108103. //serialize material
  108104. if (mesh.material) {
  108105. if (mesh.material instanceof BABYLON.MultiMaterial) {
  108106. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  108107. serializationObject.materials = serializationObject.materials || [];
  108108. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  108109. serializationObject.multiMaterials.push(mesh.material.serialize());
  108110. var _loop_1 = function (submaterial) {
  108111. if (submaterial) {
  108112. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  108113. serializationObject.materials.push(submaterial.serialize());
  108114. }
  108115. }
  108116. };
  108117. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  108118. var submaterial = _a[_i];
  108119. _loop_1(submaterial);
  108120. }
  108121. }
  108122. }
  108123. else {
  108124. serializationObject.materials = serializationObject.materials || [];
  108125. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  108126. serializationObject.materials.push(mesh.material.serialize());
  108127. }
  108128. }
  108129. }
  108130. //serialize geometry
  108131. var geometry = mesh._geometry;
  108132. if (geometry) {
  108133. if (!serializationObject.geometries) {
  108134. serializationObject.geometries = {};
  108135. serializationObject.geometries.boxes = [];
  108136. serializationObject.geometries.spheres = [];
  108137. serializationObject.geometries.cylinders = [];
  108138. serializationObject.geometries.toruses = [];
  108139. serializationObject.geometries.grounds = [];
  108140. serializationObject.geometries.planes = [];
  108141. serializationObject.geometries.torusKnots = [];
  108142. serializationObject.geometries.vertexData = [];
  108143. }
  108144. serializeGeometry(geometry, serializationObject.geometries);
  108145. }
  108146. // Skeletons
  108147. if (mesh.skeleton) {
  108148. serializationObject.skeletons = serializationObject.skeletons || [];
  108149. serializationObject.skeletons.push(mesh.skeleton.serialize());
  108150. }
  108151. //serialize the actual mesh
  108152. serializationObject.meshes = serializationObject.meshes || [];
  108153. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  108154. }
  108155. };
  108156. /**
  108157. * Class used to serialize a scene into a string
  108158. */
  108159. var SceneSerializer = /** @class */ (function () {
  108160. function SceneSerializer() {
  108161. }
  108162. /**
  108163. * Clear cache used by a previous serialization
  108164. */
  108165. SceneSerializer.ClearCache = function () {
  108166. serializedGeometries = [];
  108167. };
  108168. /**
  108169. * Serialize a scene into a JSON compatible object
  108170. * @param scene defines the scene to serialize
  108171. * @returns a JSON compatible object
  108172. */
  108173. SceneSerializer.Serialize = function (scene) {
  108174. var serializationObject = {};
  108175. SceneSerializer.ClearCache();
  108176. // Scene
  108177. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  108178. serializationObject.autoClear = scene.autoClear;
  108179. serializationObject.clearColor = scene.clearColor.asArray();
  108180. serializationObject.ambientColor = scene.ambientColor.asArray();
  108181. serializationObject.gravity = scene.gravity.asArray();
  108182. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  108183. serializationObject.workerCollisions = scene.workerCollisions;
  108184. // Fog
  108185. if (scene.fogMode && scene.fogMode !== 0) {
  108186. serializationObject.fogMode = scene.fogMode;
  108187. serializationObject.fogColor = scene.fogColor.asArray();
  108188. serializationObject.fogStart = scene.fogStart;
  108189. serializationObject.fogEnd = scene.fogEnd;
  108190. serializationObject.fogDensity = scene.fogDensity;
  108191. }
  108192. //Physics
  108193. if (scene.isPhysicsEnabled()) {
  108194. var physicEngine = scene.getPhysicsEngine();
  108195. if (physicEngine) {
  108196. serializationObject.physicsEnabled = true;
  108197. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  108198. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  108199. }
  108200. }
  108201. // Metadata
  108202. if (scene.metadata) {
  108203. serializationObject.metadata = scene.metadata;
  108204. }
  108205. // Morph targets
  108206. serializationObject.morphTargetManagers = [];
  108207. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  108208. var abstractMesh = _a[_i];
  108209. var manager = abstractMesh.morphTargetManager;
  108210. if (manager) {
  108211. serializationObject.morphTargetManagers.push(manager.serialize());
  108212. }
  108213. }
  108214. // Lights
  108215. serializationObject.lights = [];
  108216. var index;
  108217. var light;
  108218. for (index = 0; index < scene.lights.length; index++) {
  108219. light = scene.lights[index];
  108220. if (!light.doNotSerialize) {
  108221. serializationObject.lights.push(light.serialize());
  108222. }
  108223. }
  108224. // Cameras
  108225. serializationObject.cameras = [];
  108226. for (index = 0; index < scene.cameras.length; index++) {
  108227. var camera = scene.cameras[index];
  108228. if (!camera.doNotSerialize) {
  108229. serializationObject.cameras.push(camera.serialize());
  108230. }
  108231. }
  108232. if (scene.activeCamera) {
  108233. serializationObject.activeCameraID = scene.activeCamera.id;
  108234. }
  108235. // Animations
  108236. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  108237. // Materials
  108238. serializationObject.materials = [];
  108239. serializationObject.multiMaterials = [];
  108240. var material;
  108241. for (index = 0; index < scene.materials.length; index++) {
  108242. material = scene.materials[index];
  108243. if (!material.doNotSerialize) {
  108244. serializationObject.materials.push(material.serialize());
  108245. }
  108246. }
  108247. // MultiMaterials
  108248. serializationObject.multiMaterials = [];
  108249. for (index = 0; index < scene.multiMaterials.length; index++) {
  108250. var multiMaterial = scene.multiMaterials[index];
  108251. serializationObject.multiMaterials.push(multiMaterial.serialize());
  108252. }
  108253. // Environment texture
  108254. if (scene.environmentTexture) {
  108255. serializationObject.environmentTexture = scene.environmentTexture.name;
  108256. }
  108257. // Skeletons
  108258. serializationObject.skeletons = [];
  108259. for (index = 0; index < scene.skeletons.length; index++) {
  108260. var skeleton = scene.skeletons[index];
  108261. if (!skeleton.doNotSerialize) {
  108262. serializationObject.skeletons.push(skeleton.serialize());
  108263. }
  108264. }
  108265. // Transform nodes
  108266. serializationObject.transformNodes = [];
  108267. for (index = 0; index < scene.transformNodes.length; index++) {
  108268. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  108269. }
  108270. // Geometries
  108271. serializationObject.geometries = {};
  108272. serializationObject.geometries.boxes = [];
  108273. serializationObject.geometries.spheres = [];
  108274. serializationObject.geometries.cylinders = [];
  108275. serializationObject.geometries.toruses = [];
  108276. serializationObject.geometries.grounds = [];
  108277. serializationObject.geometries.planes = [];
  108278. serializationObject.geometries.torusKnots = [];
  108279. serializationObject.geometries.vertexData = [];
  108280. serializedGeometries = [];
  108281. var geometries = scene.getGeometries();
  108282. for (index = 0; index < geometries.length; index++) {
  108283. var geometry = geometries[index];
  108284. if (geometry.isReady()) {
  108285. serializeGeometry(geometry, serializationObject.geometries);
  108286. }
  108287. }
  108288. // Meshes
  108289. serializationObject.meshes = [];
  108290. for (index = 0; index < scene.meshes.length; index++) {
  108291. var abstractMesh = scene.meshes[index];
  108292. if (abstractMesh instanceof BABYLON.Mesh) {
  108293. var mesh = abstractMesh;
  108294. if (!mesh.doNotSerialize) {
  108295. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  108296. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  108297. }
  108298. }
  108299. }
  108300. }
  108301. // Particles Systems
  108302. serializationObject.particleSystems = [];
  108303. for (index = 0; index < scene.particleSystems.length; index++) {
  108304. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  108305. }
  108306. // Action Manager
  108307. if (scene.actionManager) {
  108308. serializationObject.actions = scene.actionManager.serialize("scene");
  108309. }
  108310. // Components
  108311. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  108312. var component = _c[_b];
  108313. component.serialize(serializationObject);
  108314. }
  108315. return serializationObject;
  108316. };
  108317. /**
  108318. * Serialize a mesh into a JSON compatible object
  108319. * @param toSerialize defines the mesh to serialize
  108320. * @param withParents defines if parents must be serialized as well
  108321. * @param withChildren defines if children must be serialized as well
  108322. * @returns a JSON compatible object
  108323. */
  108324. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  108325. if (withParents === void 0) { withParents = false; }
  108326. if (withChildren === void 0) { withChildren = false; }
  108327. var serializationObject = {};
  108328. SceneSerializer.ClearCache();
  108329. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  108330. if (withParents || withChildren) {
  108331. //deliberate for loop! not for each, appended should be processed as well.
  108332. for (var i = 0; i < toSerialize.length; ++i) {
  108333. if (withChildren) {
  108334. toSerialize[i].getDescendants().forEach(function (node) {
  108335. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  108336. toSerialize.push(node);
  108337. }
  108338. });
  108339. }
  108340. //make sure the array doesn't contain the object already
  108341. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  108342. toSerialize.push(toSerialize[i].parent);
  108343. }
  108344. }
  108345. }
  108346. toSerialize.forEach(function (mesh) {
  108347. finalizeSingleMesh(mesh, serializationObject);
  108348. });
  108349. return serializationObject;
  108350. };
  108351. return SceneSerializer;
  108352. }());
  108353. BABYLON.SceneSerializer = SceneSerializer;
  108354. })(BABYLON || (BABYLON = {}));
  108355. //# sourceMappingURL=babylon.sceneSerializer.js.map
  108356. var BABYLON;
  108357. (function (BABYLON) {
  108358. /**
  108359. * Class used to generate realtime reflection / refraction cube textures
  108360. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  108361. */
  108362. var ReflectionProbe = /** @class */ (function () {
  108363. /**
  108364. * Creates a new reflection probe
  108365. * @param name defines the name of the probe
  108366. * @param size defines the texture resolution (for each face)
  108367. * @param scene defines the hosting scene
  108368. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  108369. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  108370. */
  108371. function ReflectionProbe(
  108372. /** defines the name of the probe */
  108373. name, size, scene, generateMipMaps, useFloat) {
  108374. if (generateMipMaps === void 0) { generateMipMaps = true; }
  108375. if (useFloat === void 0) { useFloat = false; }
  108376. var _this = this;
  108377. this.name = name;
  108378. this._viewMatrix = BABYLON.Matrix.Identity();
  108379. this._target = BABYLON.Vector3.Zero();
  108380. this._add = BABYLON.Vector3.Zero();
  108381. this._invertYAxis = false;
  108382. /** Gets or sets probe position (center of the cube map) */
  108383. this.position = BABYLON.Vector3.Zero();
  108384. this._scene = scene;
  108385. // Create the scene field if not exist.
  108386. if (!this._scene.reflectionProbes) {
  108387. this._scene.reflectionProbes = new Array();
  108388. }
  108389. this._scene.reflectionProbes.push(this);
  108390. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  108391. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  108392. switch (faceIndex) {
  108393. case 0:
  108394. _this._add.copyFromFloats(1, 0, 0);
  108395. break;
  108396. case 1:
  108397. _this._add.copyFromFloats(-1, 0, 0);
  108398. break;
  108399. case 2:
  108400. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  108401. break;
  108402. case 3:
  108403. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  108404. break;
  108405. case 4:
  108406. _this._add.copyFromFloats(0, 0, 1);
  108407. break;
  108408. case 5:
  108409. _this._add.copyFromFloats(0, 0, -1);
  108410. break;
  108411. }
  108412. if (_this._attachedMesh) {
  108413. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  108414. }
  108415. _this.position.addToRef(_this._add, _this._target);
  108416. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  108417. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  108418. scene._forcedViewPosition = _this.position;
  108419. });
  108420. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  108421. scene._forcedViewPosition = null;
  108422. scene.updateTransformMatrix(true);
  108423. });
  108424. if (scene.activeCamera) {
  108425. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  108426. }
  108427. }
  108428. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  108429. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  108430. get: function () {
  108431. return this._renderTargetTexture.samples;
  108432. },
  108433. set: function (value) {
  108434. this._renderTargetTexture.samples = value;
  108435. },
  108436. enumerable: true,
  108437. configurable: true
  108438. });
  108439. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  108440. /** Gets or sets the refresh rate to use (on every frame by default) */
  108441. get: function () {
  108442. return this._renderTargetTexture.refreshRate;
  108443. },
  108444. set: function (value) {
  108445. this._renderTargetTexture.refreshRate = value;
  108446. },
  108447. enumerable: true,
  108448. configurable: true
  108449. });
  108450. /**
  108451. * Gets the hosting scene
  108452. * @returns a Scene
  108453. */
  108454. ReflectionProbe.prototype.getScene = function () {
  108455. return this._scene;
  108456. };
  108457. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  108458. /** Gets the internal CubeTexture used to render to */
  108459. get: function () {
  108460. return this._renderTargetTexture;
  108461. },
  108462. enumerable: true,
  108463. configurable: true
  108464. });
  108465. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  108466. /** Gets the list of meshes to render */
  108467. get: function () {
  108468. return this._renderTargetTexture.renderList;
  108469. },
  108470. enumerable: true,
  108471. configurable: true
  108472. });
  108473. /**
  108474. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  108475. * @param mesh defines the mesh to attach to
  108476. */
  108477. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  108478. this._attachedMesh = mesh;
  108479. };
  108480. /**
  108481. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  108482. * @param renderingGroupId The rendering group id corresponding to its index
  108483. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  108484. */
  108485. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  108486. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  108487. };
  108488. /**
  108489. * Clean all associated resources
  108490. */
  108491. ReflectionProbe.prototype.dispose = function () {
  108492. var index = this._scene.reflectionProbes.indexOf(this);
  108493. if (index !== -1) {
  108494. // Remove from the scene if found
  108495. this._scene.reflectionProbes.splice(index, 1);
  108496. }
  108497. if (this._renderTargetTexture) {
  108498. this._renderTargetTexture.dispose();
  108499. this._renderTargetTexture = null;
  108500. }
  108501. };
  108502. return ReflectionProbe;
  108503. }());
  108504. BABYLON.ReflectionProbe = ReflectionProbe;
  108505. })(BABYLON || (BABYLON = {}));
  108506. //# sourceMappingURL=babylon.reflectionProbe.js.map
  108507. var BABYLON;
  108508. (function (BABYLON) {
  108509. /**
  108510. * Defines the layer scene component responsible to manage any layers
  108511. * in a given scene.
  108512. */
  108513. var LayerSceneComponent = /** @class */ (function () {
  108514. /**
  108515. * Creates a new instance of the component for the given scene
  108516. * @param scene Defines the scene to register the component in
  108517. */
  108518. function LayerSceneComponent(scene) {
  108519. /**
  108520. * The component name helpfull to identify the component in the list of scene components.
  108521. */
  108522. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  108523. this.scene = scene;
  108524. this._engine = scene.getEngine();
  108525. scene.layers = new Array();
  108526. }
  108527. /**
  108528. * Registers the component in a given scene
  108529. */
  108530. LayerSceneComponent.prototype.register = function () {
  108531. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  108532. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  108533. };
  108534. /**
  108535. * Rebuilds the elements related to this component in case of
  108536. * context lost for instance.
  108537. */
  108538. LayerSceneComponent.prototype.rebuild = function () {
  108539. var layers = this.scene.layers;
  108540. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  108541. var layer = layers_1[_i];
  108542. layer._rebuild();
  108543. }
  108544. };
  108545. /**
  108546. * Disposes the component and the associated ressources.
  108547. */
  108548. LayerSceneComponent.prototype.dispose = function () {
  108549. var layers = this.scene.layers;
  108550. while (layers.length) {
  108551. layers[0].dispose();
  108552. }
  108553. };
  108554. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  108555. var layers = this.scene.layers;
  108556. if (layers.length) {
  108557. this._engine.setDepthBuffer(false);
  108558. var cameraLayerMask = camera.layerMask;
  108559. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  108560. var layer = layers_2[_i];
  108561. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  108562. layer.render();
  108563. }
  108564. }
  108565. this._engine.setDepthBuffer(true);
  108566. }
  108567. };
  108568. LayerSceneComponent.prototype._drawBackground = function (camera) {
  108569. this._draw(camera, true);
  108570. };
  108571. LayerSceneComponent.prototype._drawForeground = function (camera) {
  108572. this._draw(camera, false);
  108573. };
  108574. return LayerSceneComponent;
  108575. }());
  108576. BABYLON.LayerSceneComponent = LayerSceneComponent;
  108577. })(BABYLON || (BABYLON = {}));
  108578. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  108579. var BABYLON;
  108580. (function (BABYLON) {
  108581. /**
  108582. * This represents a full screen 2d layer.
  108583. * This can be usefull to display a picture in the background of your scene for instance.
  108584. * @see https://www.babylonjs-playground.com/#08A2BS#1
  108585. */
  108586. var Layer = /** @class */ (function () {
  108587. /**
  108588. * Instantiates a new layer.
  108589. * This represents a full screen 2d layer.
  108590. * This can be usefull to display a picture in the background of your scene for instance.
  108591. * @see https://www.babylonjs-playground.com/#08A2BS#1
  108592. * @param name Define the name of the layer in the scene
  108593. * @param imgUrl Define the url of the texture to display in the layer
  108594. * @param scene Define the scene the layer belongs to
  108595. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  108596. * @param color Defines a color for the layer
  108597. */
  108598. function Layer(
  108599. /**
  108600. * Define the name of the layer.
  108601. */
  108602. name, imgUrl, scene, isBackground, color) {
  108603. this.name = name;
  108604. /**
  108605. * Define the scale of the layer in order to zoom in out of the texture.
  108606. */
  108607. this.scale = new BABYLON.Vector2(1, 1);
  108608. /**
  108609. * Define an offset for the layer in order to shift the texture.
  108610. */
  108611. this.offset = new BABYLON.Vector2(0, 0);
  108612. /**
  108613. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  108614. */
  108615. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  108616. /**
  108617. * Define a mask to restrict the layer to only some of the scene cameras.
  108618. */
  108619. this.layerMask = 0x0FFFFFFF;
  108620. this._vertexBuffers = {};
  108621. /**
  108622. * An event triggered when the layer is disposed.
  108623. */
  108624. this.onDisposeObservable = new BABYLON.Observable();
  108625. /**
  108626. * An event triggered before rendering the scene
  108627. */
  108628. this.onBeforeRenderObservable = new BABYLON.Observable();
  108629. /**
  108630. * An event triggered after rendering the scene
  108631. */
  108632. this.onAfterRenderObservable = new BABYLON.Observable();
  108633. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  108634. this.isBackground = isBackground === undefined ? true : isBackground;
  108635. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  108636. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  108637. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  108638. if (!layerComponent) {
  108639. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  108640. this._scene._addComponent(layerComponent);
  108641. }
  108642. this._scene.layers.push(this);
  108643. var engine = this._scene.getEngine();
  108644. // VBO
  108645. var vertices = [];
  108646. vertices.push(1, 1);
  108647. vertices.push(-1, 1);
  108648. vertices.push(-1, -1);
  108649. vertices.push(1, -1);
  108650. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  108651. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  108652. this._createIndexBuffer();
  108653. // Effects
  108654. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  108655. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  108656. }
  108657. Object.defineProperty(Layer.prototype, "onDispose", {
  108658. /**
  108659. * Back compatibility with callback before the onDisposeObservable existed.
  108660. * The set callback will be triggered when the layer has been disposed.
  108661. */
  108662. set: function (callback) {
  108663. if (this._onDisposeObserver) {
  108664. this.onDisposeObservable.remove(this._onDisposeObserver);
  108665. }
  108666. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  108667. },
  108668. enumerable: true,
  108669. configurable: true
  108670. });
  108671. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  108672. /**
  108673. * Back compatibility with callback before the onBeforeRenderObservable existed.
  108674. * The set callback will be triggered just before rendering the layer.
  108675. */
  108676. set: function (callback) {
  108677. if (this._onBeforeRenderObserver) {
  108678. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  108679. }
  108680. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  108681. },
  108682. enumerable: true,
  108683. configurable: true
  108684. });
  108685. Object.defineProperty(Layer.prototype, "onAfterRender", {
  108686. /**
  108687. * Back compatibility with callback before the onAfterRenderObservable existed.
  108688. * The set callback will be triggered just after rendering the layer.
  108689. */
  108690. set: function (callback) {
  108691. if (this._onAfterRenderObserver) {
  108692. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  108693. }
  108694. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  108695. },
  108696. enumerable: true,
  108697. configurable: true
  108698. });
  108699. Layer.prototype._createIndexBuffer = function () {
  108700. var engine = this._scene.getEngine();
  108701. // Indices
  108702. var indices = [];
  108703. indices.push(0);
  108704. indices.push(1);
  108705. indices.push(2);
  108706. indices.push(0);
  108707. indices.push(2);
  108708. indices.push(3);
  108709. this._indexBuffer = engine.createIndexBuffer(indices);
  108710. };
  108711. /** @hidden */
  108712. Layer.prototype._rebuild = function () {
  108713. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108714. if (vb) {
  108715. vb._rebuild();
  108716. }
  108717. this._createIndexBuffer();
  108718. };
  108719. /**
  108720. * Renders the layer in the scene.
  108721. */
  108722. Layer.prototype.render = function () {
  108723. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  108724. // Check
  108725. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  108726. return;
  108727. var engine = this._scene.getEngine();
  108728. this.onBeforeRenderObservable.notifyObservers(this);
  108729. // Render
  108730. engine.enableEffect(currentEffect);
  108731. engine.setState(false);
  108732. // Texture
  108733. currentEffect.setTexture("textureSampler", this.texture);
  108734. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  108735. // Color
  108736. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  108737. // Scale / offset
  108738. currentEffect.setVector2("offset", this.offset);
  108739. currentEffect.setVector2("scale", this.scale);
  108740. // VBOs
  108741. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  108742. // Draw order
  108743. if (!this.alphaTest) {
  108744. engine.setAlphaMode(this.alphaBlendingMode);
  108745. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108746. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108747. }
  108748. else {
  108749. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108750. }
  108751. this.onAfterRenderObservable.notifyObservers(this);
  108752. };
  108753. /**
  108754. * Disposes and releases the associated ressources.
  108755. */
  108756. Layer.prototype.dispose = function () {
  108757. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108758. if (vertexBuffer) {
  108759. vertexBuffer.dispose();
  108760. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  108761. }
  108762. if (this._indexBuffer) {
  108763. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  108764. this._indexBuffer = null;
  108765. }
  108766. if (this.texture) {
  108767. this.texture.dispose();
  108768. this.texture = null;
  108769. }
  108770. // Remove from scene
  108771. var index = this._scene.layers.indexOf(this);
  108772. this._scene.layers.splice(index, 1);
  108773. // Callback
  108774. this.onDisposeObservable.notifyObservers(this);
  108775. this.onDisposeObservable.clear();
  108776. this.onAfterRenderObservable.clear();
  108777. this.onBeforeRenderObservable.clear();
  108778. };
  108779. return Layer;
  108780. }());
  108781. BABYLON.Layer = Layer;
  108782. })(BABYLON || (BABYLON = {}));
  108783. //# sourceMappingURL=babylon.layer.js.map
  108784. var BABYLON;
  108785. (function (BABYLON) {
  108786. /**
  108787. * Class used to host texture specific utilities
  108788. */
  108789. var TextureTools = /** @class */ (function () {
  108790. function TextureTools() {
  108791. }
  108792. /**
  108793. * Uses the GPU to create a copy texture rescaled at a given size
  108794. * @param texture Texture to copy from
  108795. * @param width defines the desired width
  108796. * @param height defines the desired height
  108797. * @param useBilinearMode defines if bilinear mode has to be used
  108798. * @return the generated texture
  108799. */
  108800. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  108801. if (useBilinearMode === void 0) { useBilinearMode = true; }
  108802. var scene = texture.getScene();
  108803. var engine = scene.getEngine();
  108804. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  108805. rtt.wrapU = texture.wrapU;
  108806. rtt.wrapV = texture.wrapV;
  108807. rtt.uOffset = texture.uOffset;
  108808. rtt.vOffset = texture.vOffset;
  108809. rtt.uScale = texture.uScale;
  108810. rtt.vScale = texture.vScale;
  108811. rtt.uAng = texture.uAng;
  108812. rtt.vAng = texture.vAng;
  108813. rtt.wAng = texture.wAng;
  108814. rtt.coordinatesIndex = texture.coordinatesIndex;
  108815. rtt.level = texture.level;
  108816. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  108817. rtt._texture.isReady = false;
  108818. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108819. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108820. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  108821. passPostProcess.getEffect().executeWhenCompiled(function () {
  108822. passPostProcess.onApply = function (effect) {
  108823. effect.setTexture("textureSampler", texture);
  108824. };
  108825. var internalTexture = rtt.getInternalTexture();
  108826. if (internalTexture) {
  108827. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  108828. engine.unBindFramebuffer(internalTexture);
  108829. rtt.disposeFramebufferObjects();
  108830. passPostProcess.dispose();
  108831. internalTexture.isReady = true;
  108832. }
  108833. });
  108834. return rtt;
  108835. };
  108836. /**
  108837. * Gets an environment BRDF texture for a given scene
  108838. * @param scene defines the hosting scene
  108839. * @returns the environment BRDF texture
  108840. */
  108841. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  108842. if (!scene._environmentBRDFTexture) {
  108843. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108844. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108845. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108846. scene._environmentBRDFTexture = texture;
  108847. }
  108848. return scene._environmentBRDFTexture;
  108849. };
  108850. 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=";
  108851. return TextureTools;
  108852. }());
  108853. BABYLON.TextureTools = TextureTools;
  108854. })(BABYLON || (BABYLON = {}));
  108855. //# sourceMappingURL=babylon.textureTools.js.map
  108856. var BABYLON;
  108857. (function (BABYLON) {
  108858. /**
  108859. * 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.
  108860. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  108861. */
  108862. var FramingBehavior = /** @class */ (function () {
  108863. function FramingBehavior() {
  108864. this._mode = FramingBehavior.FitFrustumSidesMode;
  108865. this._radiusScale = 1.0;
  108866. this._positionScale = 0.5;
  108867. this._defaultElevation = 0.3;
  108868. this._elevationReturnTime = 1500;
  108869. this._elevationReturnWaitTime = 1000;
  108870. this._zoomStopsAnimation = false;
  108871. this._framingTime = 1500;
  108872. /**
  108873. * Define if the behavior should automatically change the configured
  108874. * camera limits and sensibilities.
  108875. */
  108876. this.autoCorrectCameraLimitsAndSensibility = true;
  108877. this._isPointerDown = false;
  108878. this._lastInteractionTime = -Infinity;
  108879. // Framing control
  108880. this._animatables = new Array();
  108881. this._betaIsAnimating = false;
  108882. }
  108883. Object.defineProperty(FramingBehavior.prototype, "name", {
  108884. /**
  108885. * Gets the name of the behavior.
  108886. */
  108887. get: function () {
  108888. return "Framing";
  108889. },
  108890. enumerable: true,
  108891. configurable: true
  108892. });
  108893. Object.defineProperty(FramingBehavior.prototype, "mode", {
  108894. /**
  108895. * Gets current mode used by the behavior.
  108896. */
  108897. get: function () {
  108898. return this._mode;
  108899. },
  108900. /**
  108901. * Sets the current mode used by the behavior
  108902. */
  108903. set: function (mode) {
  108904. this._mode = mode;
  108905. },
  108906. enumerable: true,
  108907. configurable: true
  108908. });
  108909. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  108910. /**
  108911. * Gets the scale applied to the radius
  108912. */
  108913. get: function () {
  108914. return this._radiusScale;
  108915. },
  108916. /**
  108917. * Sets the scale applied to the radius (1 by default)
  108918. */
  108919. set: function (radius) {
  108920. this._radiusScale = radius;
  108921. },
  108922. enumerable: true,
  108923. configurable: true
  108924. });
  108925. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  108926. /**
  108927. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108928. */
  108929. get: function () {
  108930. return this._positionScale;
  108931. },
  108932. /**
  108933. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108934. */
  108935. set: function (scale) {
  108936. this._positionScale = scale;
  108937. },
  108938. enumerable: true,
  108939. configurable: true
  108940. });
  108941. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  108942. /**
  108943. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108944. * behaviour is triggered, in radians.
  108945. */
  108946. get: function () {
  108947. return this._defaultElevation;
  108948. },
  108949. /**
  108950. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108951. * behaviour is triggered, in radians.
  108952. */
  108953. set: function (elevation) {
  108954. this._defaultElevation = elevation;
  108955. },
  108956. enumerable: true,
  108957. configurable: true
  108958. });
  108959. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  108960. /**
  108961. * Gets the time (in milliseconds) taken to return to the default beta position.
  108962. * Negative value indicates camera should not return to default.
  108963. */
  108964. get: function () {
  108965. return this._elevationReturnTime;
  108966. },
  108967. /**
  108968. * Sets the time (in milliseconds) taken to return to the default beta position.
  108969. * Negative value indicates camera should not return to default.
  108970. */
  108971. set: function (speed) {
  108972. this._elevationReturnTime = speed;
  108973. },
  108974. enumerable: true,
  108975. configurable: true
  108976. });
  108977. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  108978. /**
  108979. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108980. */
  108981. get: function () {
  108982. return this._elevationReturnWaitTime;
  108983. },
  108984. /**
  108985. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108986. */
  108987. set: function (time) {
  108988. this._elevationReturnWaitTime = time;
  108989. },
  108990. enumerable: true,
  108991. configurable: true
  108992. });
  108993. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  108994. /**
  108995. * Gets the flag that indicates if user zooming should stop animation.
  108996. */
  108997. get: function () {
  108998. return this._zoomStopsAnimation;
  108999. },
  109000. /**
  109001. * Sets the flag that indicates if user zooming should stop animation.
  109002. */
  109003. set: function (flag) {
  109004. this._zoomStopsAnimation = flag;
  109005. },
  109006. enumerable: true,
  109007. configurable: true
  109008. });
  109009. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  109010. /**
  109011. * Gets the transition time when framing the mesh, in milliseconds
  109012. */
  109013. get: function () {
  109014. return this._framingTime;
  109015. },
  109016. /**
  109017. * Sets the transition time when framing the mesh, in milliseconds
  109018. */
  109019. set: function (time) {
  109020. this._framingTime = time;
  109021. },
  109022. enumerable: true,
  109023. configurable: true
  109024. });
  109025. /**
  109026. * Initializes the behavior.
  109027. */
  109028. FramingBehavior.prototype.init = function () {
  109029. // Do notihng
  109030. };
  109031. /**
  109032. * Attaches the behavior to its arc rotate camera.
  109033. * @param camera Defines the camera to attach the behavior to
  109034. */
  109035. FramingBehavior.prototype.attach = function (camera) {
  109036. var _this = this;
  109037. this._attachedCamera = camera;
  109038. var scene = this._attachedCamera.getScene();
  109039. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  109040. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  109041. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  109042. _this._isPointerDown = true;
  109043. return;
  109044. }
  109045. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  109046. _this._isPointerDown = false;
  109047. }
  109048. });
  109049. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  109050. if (mesh) {
  109051. _this.zoomOnMesh(mesh);
  109052. }
  109053. });
  109054. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109055. // Stop the animation if there is user interaction and the animation should stop for this interaction
  109056. _this._applyUserInteraction();
  109057. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  109058. // back to the default position after a given timeout
  109059. _this._maintainCameraAboveGround();
  109060. });
  109061. };
  109062. /**
  109063. * Detaches the behavior from its current arc rotate camera.
  109064. */
  109065. FramingBehavior.prototype.detach = function () {
  109066. if (!this._attachedCamera) {
  109067. return;
  109068. }
  109069. var scene = this._attachedCamera.getScene();
  109070. if (this._onPrePointerObservableObserver) {
  109071. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  109072. }
  109073. if (this._onAfterCheckInputsObserver) {
  109074. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109075. }
  109076. if (this._onMeshTargetChangedObserver) {
  109077. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  109078. }
  109079. this._attachedCamera = null;
  109080. };
  109081. /**
  109082. * Targets the given mesh and updates zoom level accordingly.
  109083. * @param mesh The mesh to target.
  109084. * @param radius Optional. If a cached radius position already exists, overrides default.
  109085. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109086. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109087. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109088. */
  109089. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  109090. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109091. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109092. mesh.computeWorldMatrix(true);
  109093. var boundingBox = mesh.getBoundingInfo().boundingBox;
  109094. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  109095. };
  109096. /**
  109097. * Targets the given mesh with its children and updates zoom level accordingly.
  109098. * @param mesh The mesh to target.
  109099. * @param radius Optional. If a cached radius position already exists, overrides default.
  109100. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109101. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109102. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109103. */
  109104. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  109105. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109106. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109107. mesh.computeWorldMatrix(true);
  109108. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  109109. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  109110. };
  109111. /**
  109112. * Targets the given meshes with their children and updates zoom level accordingly.
  109113. * @param meshes The mesh to target.
  109114. * @param radius Optional. If a cached radius position already exists, overrides default.
  109115. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109116. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109117. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109118. */
  109119. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  109120. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109121. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109122. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  109123. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  109124. for (var i = 0; i < meshes.length; i++) {
  109125. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  109126. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  109127. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  109128. }
  109129. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  109130. };
  109131. /**
  109132. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  109133. * @param minimumWorld Determines the smaller position of the bounding box extend
  109134. * @param maximumWorld Determines the bigger position of the bounding box extend
  109135. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109136. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109137. */
  109138. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  109139. var _this = this;
  109140. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109141. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109142. var zoomTarget;
  109143. if (!this._attachedCamera) {
  109144. return;
  109145. }
  109146. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  109147. var bottom = minimumWorld.y;
  109148. var top = maximumWorld.y;
  109149. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  109150. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  109151. if (focusOnOriginXZ) {
  109152. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  109153. }
  109154. else {
  109155. var centerWorld = minimumWorld.add(radiusWorld);
  109156. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  109157. }
  109158. if (!this._vectorTransition) {
  109159. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  109160. }
  109161. this._betaIsAnimating = true;
  109162. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  109163. if (animatable) {
  109164. this._animatables.push(animatable);
  109165. }
  109166. // sets the radius and lower radius bounds
  109167. // Small delta ensures camera is not always at lower zoom limit.
  109168. var radius = 0;
  109169. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  109170. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  109171. if (this.autoCorrectCameraLimitsAndSensibility) {
  109172. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  109173. }
  109174. radius = position;
  109175. }
  109176. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  109177. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  109178. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  109179. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  109180. }
  109181. }
  109182. // Set sensibilities
  109183. if (this.autoCorrectCameraLimitsAndSensibility) {
  109184. var extend = maximumWorld.subtract(minimumWorld).length();
  109185. this._attachedCamera.panningSensibility = 5000 / extend;
  109186. this._attachedCamera.wheelPrecision = 100 / radius;
  109187. }
  109188. // transition to new radius
  109189. if (!this._radiusTransition) {
  109190. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  109191. }
  109192. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  109193. _this.stopAllAnimations();
  109194. if (onAnimationEnd) {
  109195. onAnimationEnd();
  109196. }
  109197. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  109198. _this._attachedCamera.storeState();
  109199. }
  109200. });
  109201. if (animatable) {
  109202. this._animatables.push(animatable);
  109203. }
  109204. };
  109205. /**
  109206. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  109207. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  109208. * frustum width.
  109209. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  109210. * to fully enclose the mesh in the viewing frustum.
  109211. */
  109212. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  109213. var size = maximumWorld.subtract(minimumWorld);
  109214. var boxVectorGlobalDiagonal = size.length();
  109215. var frustumSlope = this._getFrustumSlope();
  109216. // Formula for setting distance
  109217. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  109218. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  109219. // Horizon distance
  109220. var radius = radiusWithoutFraming * this._radiusScale;
  109221. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  109222. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  109223. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  109224. var camera = this._attachedCamera;
  109225. if (!camera) {
  109226. return 0;
  109227. }
  109228. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  109229. // Don't exceed the requested limit
  109230. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  109231. }
  109232. // Don't exceed the upper radius limit
  109233. if (camera.upperRadiusLimit) {
  109234. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  109235. }
  109236. return distance;
  109237. };
  109238. /**
  109239. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  109240. * is automatically returned to its default position (expected to be above ground plane).
  109241. */
  109242. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  109243. var _this = this;
  109244. if (this._elevationReturnTime < 0) {
  109245. return;
  109246. }
  109247. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  109248. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  109249. var limitBeta = Math.PI * 0.5;
  109250. // Bring the camera back up if below the ground plane
  109251. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  109252. this._betaIsAnimating = true;
  109253. //Transition to new position
  109254. this.stopAllAnimations();
  109255. if (!this._betaTransition) {
  109256. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  109257. }
  109258. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  109259. _this._clearAnimationLocks();
  109260. _this.stopAllAnimations();
  109261. });
  109262. if (animatabe) {
  109263. this._animatables.push(animatabe);
  109264. }
  109265. }
  109266. };
  109267. /**
  109268. * Returns the frustum slope based on the canvas ratio and camera FOV
  109269. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  109270. */
  109271. FramingBehavior.prototype._getFrustumSlope = function () {
  109272. // Calculate the viewport ratio
  109273. // Aspect Ratio is Height/Width.
  109274. var camera = this._attachedCamera;
  109275. if (!camera) {
  109276. return BABYLON.Vector2.Zero();
  109277. }
  109278. var engine = camera.getScene().getEngine();
  109279. var aspectRatio = engine.getAspectRatio(camera);
  109280. // Camera FOV is the vertical field of view (top-bottom) in radians.
  109281. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  109282. var frustumSlopeY = Math.tan(camera.fov / 2);
  109283. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  109284. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  109285. // along the forward vector.
  109286. var frustumSlopeX = frustumSlopeY * aspectRatio;
  109287. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  109288. };
  109289. /**
  109290. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  109291. */
  109292. FramingBehavior.prototype._clearAnimationLocks = function () {
  109293. this._betaIsAnimating = false;
  109294. };
  109295. /**
  109296. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  109297. */
  109298. FramingBehavior.prototype._applyUserInteraction = function () {
  109299. if (this.isUserIsMoving) {
  109300. this._lastInteractionTime = BABYLON.Tools.Now;
  109301. this.stopAllAnimations();
  109302. this._clearAnimationLocks();
  109303. }
  109304. };
  109305. /**
  109306. * Stops and removes all animations that have been applied to the camera
  109307. */
  109308. FramingBehavior.prototype.stopAllAnimations = function () {
  109309. if (this._attachedCamera) {
  109310. this._attachedCamera.animations = [];
  109311. }
  109312. while (this._animatables.length) {
  109313. if (this._animatables[0]) {
  109314. this._animatables[0].onAnimationEnd = null;
  109315. this._animatables[0].stop();
  109316. }
  109317. this._animatables.shift();
  109318. }
  109319. };
  109320. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  109321. /**
  109322. * Gets a value indicating if the user is moving the camera
  109323. */
  109324. get: function () {
  109325. if (!this._attachedCamera) {
  109326. return false;
  109327. }
  109328. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  109329. this._attachedCamera.inertialBetaOffset !== 0 ||
  109330. this._attachedCamera.inertialRadiusOffset !== 0 ||
  109331. this._attachedCamera.inertialPanningX !== 0 ||
  109332. this._attachedCamera.inertialPanningY !== 0 ||
  109333. this._isPointerDown;
  109334. },
  109335. enumerable: true,
  109336. configurable: true
  109337. });
  109338. /**
  109339. * The easing function used by animations
  109340. */
  109341. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  109342. /**
  109343. * The easing mode used by animations
  109344. */
  109345. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  109346. // Statics
  109347. /**
  109348. * The camera can move all the way towards the mesh.
  109349. */
  109350. FramingBehavior.IgnoreBoundsSizeMode = 0;
  109351. /**
  109352. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  109353. */
  109354. FramingBehavior.FitFrustumSidesMode = 1;
  109355. return FramingBehavior;
  109356. }());
  109357. BABYLON.FramingBehavior = FramingBehavior;
  109358. })(BABYLON || (BABYLON = {}));
  109359. //# sourceMappingURL=babylon.framingBehavior.js.map
  109360. var BABYLON;
  109361. (function (BABYLON) {
  109362. /**
  109363. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  109364. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  109365. */
  109366. var BouncingBehavior = /** @class */ (function () {
  109367. function BouncingBehavior() {
  109368. /**
  109369. * The duration of the animation, in milliseconds
  109370. */
  109371. this.transitionDuration = 450;
  109372. /**
  109373. * Length of the distance animated by the transition when lower radius is reached
  109374. */
  109375. this.lowerRadiusTransitionRange = 2;
  109376. /**
  109377. * Length of the distance animated by the transition when upper radius is reached
  109378. */
  109379. this.upperRadiusTransitionRange = -2;
  109380. this._autoTransitionRange = false;
  109381. // Animations
  109382. this._radiusIsAnimating = false;
  109383. this._radiusBounceTransition = null;
  109384. this._animatables = new Array();
  109385. }
  109386. Object.defineProperty(BouncingBehavior.prototype, "name", {
  109387. /**
  109388. * Gets the name of the behavior.
  109389. */
  109390. get: function () {
  109391. return "Bouncing";
  109392. },
  109393. enumerable: true,
  109394. configurable: true
  109395. });
  109396. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  109397. /**
  109398. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  109399. */
  109400. get: function () {
  109401. return this._autoTransitionRange;
  109402. },
  109403. /**
  109404. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  109405. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  109406. */
  109407. set: function (value) {
  109408. var _this = this;
  109409. if (this._autoTransitionRange === value) {
  109410. return;
  109411. }
  109412. this._autoTransitionRange = value;
  109413. var camera = this._attachedCamera;
  109414. if (!camera) {
  109415. return;
  109416. }
  109417. if (value) {
  109418. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  109419. if (!mesh) {
  109420. return;
  109421. }
  109422. mesh.computeWorldMatrix(true);
  109423. var diagonal = mesh.getBoundingInfo().diagonalLength;
  109424. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  109425. _this.upperRadiusTransitionRange = diagonal * 0.05;
  109426. });
  109427. }
  109428. else if (this._onMeshTargetChangedObserver) {
  109429. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  109430. }
  109431. },
  109432. enumerable: true,
  109433. configurable: true
  109434. });
  109435. /**
  109436. * Initializes the behavior.
  109437. */
  109438. BouncingBehavior.prototype.init = function () {
  109439. // Do notihng
  109440. };
  109441. /**
  109442. * Attaches the behavior to its arc rotate camera.
  109443. * @param camera Defines the camera to attach the behavior to
  109444. */
  109445. BouncingBehavior.prototype.attach = function (camera) {
  109446. var _this = this;
  109447. this._attachedCamera = camera;
  109448. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109449. if (!_this._attachedCamera) {
  109450. return;
  109451. }
  109452. // Add the bounce animation to the lower radius limit
  109453. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  109454. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  109455. }
  109456. // Add the bounce animation to the upper radius limit
  109457. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  109458. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  109459. }
  109460. });
  109461. };
  109462. /**
  109463. * Detaches the behavior from its current arc rotate camera.
  109464. */
  109465. BouncingBehavior.prototype.detach = function () {
  109466. if (!this._attachedCamera) {
  109467. return;
  109468. }
  109469. if (this._onAfterCheckInputsObserver) {
  109470. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109471. }
  109472. if (this._onMeshTargetChangedObserver) {
  109473. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  109474. }
  109475. this._attachedCamera = null;
  109476. };
  109477. /**
  109478. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  109479. * @param radiusLimit The limit to check against.
  109480. * @return Bool to indicate if at limit.
  109481. */
  109482. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  109483. if (!this._attachedCamera) {
  109484. return false;
  109485. }
  109486. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  109487. return true;
  109488. }
  109489. return false;
  109490. };
  109491. /**
  109492. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  109493. * @param radiusDelta The delta by which to animate to. Can be negative.
  109494. */
  109495. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  109496. var _this = this;
  109497. if (!this._attachedCamera) {
  109498. return;
  109499. }
  109500. if (!this._radiusBounceTransition) {
  109501. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  109502. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  109503. }
  109504. // Prevent zoom until bounce has completed
  109505. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  109506. this._attachedCamera.wheelPrecision = Infinity;
  109507. this._attachedCamera.inertialRadiusOffset = 0;
  109508. // Animate to the radius limit
  109509. this.stopAllAnimations();
  109510. this._radiusIsAnimating = true;
  109511. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  109512. if (animatable) {
  109513. this._animatables.push(animatable);
  109514. }
  109515. };
  109516. /**
  109517. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  109518. */
  109519. BouncingBehavior.prototype._clearAnimationLocks = function () {
  109520. this._radiusIsAnimating = false;
  109521. if (this._attachedCamera) {
  109522. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  109523. }
  109524. };
  109525. /**
  109526. * Stops and removes all animations that have been applied to the camera
  109527. */
  109528. BouncingBehavior.prototype.stopAllAnimations = function () {
  109529. if (this._attachedCamera) {
  109530. this._attachedCamera.animations = [];
  109531. }
  109532. while (this._animatables.length) {
  109533. this._animatables[0].onAnimationEnd = null;
  109534. this._animatables[0].stop();
  109535. this._animatables.shift();
  109536. }
  109537. };
  109538. /**
  109539. * The easing function used by animations
  109540. */
  109541. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  109542. /**
  109543. * The easing mode used by animations
  109544. */
  109545. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  109546. return BouncingBehavior;
  109547. }());
  109548. BABYLON.BouncingBehavior = BouncingBehavior;
  109549. })(BABYLON || (BABYLON = {}));
  109550. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  109551. var BABYLON;
  109552. (function (BABYLON) {
  109553. /**
  109554. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  109555. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  109556. */
  109557. var AutoRotationBehavior = /** @class */ (function () {
  109558. function AutoRotationBehavior() {
  109559. this._zoomStopsAnimation = false;
  109560. this._idleRotationSpeed = 0.05;
  109561. this._idleRotationWaitTime = 2000;
  109562. this._idleRotationSpinupTime = 2000;
  109563. this._isPointerDown = false;
  109564. this._lastFrameTime = null;
  109565. this._lastInteractionTime = -Infinity;
  109566. this._cameraRotationSpeed = 0;
  109567. this._lastFrameRadius = 0;
  109568. }
  109569. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  109570. /**
  109571. * Gets the name of the behavior.
  109572. */
  109573. get: function () {
  109574. return "AutoRotation";
  109575. },
  109576. enumerable: true,
  109577. configurable: true
  109578. });
  109579. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  109580. /**
  109581. * Gets the flag that indicates if user zooming should stop animation.
  109582. */
  109583. get: function () {
  109584. return this._zoomStopsAnimation;
  109585. },
  109586. /**
  109587. * Sets the flag that indicates if user zooming should stop animation.
  109588. */
  109589. set: function (flag) {
  109590. this._zoomStopsAnimation = flag;
  109591. },
  109592. enumerable: true,
  109593. configurable: true
  109594. });
  109595. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  109596. /**
  109597. * Gets the default speed at which the camera rotates around the model.
  109598. */
  109599. get: function () {
  109600. return this._idleRotationSpeed;
  109601. },
  109602. /**
  109603. * Sets the default speed at which the camera rotates around the model.
  109604. */
  109605. set: function (speed) {
  109606. this._idleRotationSpeed = speed;
  109607. },
  109608. enumerable: true,
  109609. configurable: true
  109610. });
  109611. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  109612. /**
  109613. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  109614. */
  109615. get: function () {
  109616. return this._idleRotationWaitTime;
  109617. },
  109618. /**
  109619. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  109620. */
  109621. set: function (time) {
  109622. this._idleRotationWaitTime = time;
  109623. },
  109624. enumerable: true,
  109625. configurable: true
  109626. });
  109627. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  109628. /**
  109629. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  109630. */
  109631. get: function () {
  109632. return this._idleRotationSpinupTime;
  109633. },
  109634. /**
  109635. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  109636. */
  109637. set: function (time) {
  109638. this._idleRotationSpinupTime = time;
  109639. },
  109640. enumerable: true,
  109641. configurable: true
  109642. });
  109643. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  109644. /**
  109645. * Gets a value indicating if the camera is currently rotating because of this behavior
  109646. */
  109647. get: function () {
  109648. return Math.abs(this._cameraRotationSpeed) > 0;
  109649. },
  109650. enumerable: true,
  109651. configurable: true
  109652. });
  109653. /**
  109654. * Initializes the behavior.
  109655. */
  109656. AutoRotationBehavior.prototype.init = function () {
  109657. // Do notihng
  109658. };
  109659. /**
  109660. * Attaches the behavior to its arc rotate camera.
  109661. * @param camera Defines the camera to attach the behavior to
  109662. */
  109663. AutoRotationBehavior.prototype.attach = function (camera) {
  109664. var _this = this;
  109665. this._attachedCamera = camera;
  109666. var scene = this._attachedCamera.getScene();
  109667. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  109668. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  109669. _this._isPointerDown = true;
  109670. return;
  109671. }
  109672. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  109673. _this._isPointerDown = false;
  109674. }
  109675. });
  109676. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109677. var now = BABYLON.Tools.Now;
  109678. var dt = 0;
  109679. if (_this._lastFrameTime != null) {
  109680. dt = now - _this._lastFrameTime;
  109681. }
  109682. _this._lastFrameTime = now;
  109683. // Stop the animation if there is user interaction and the animation should stop for this interaction
  109684. _this._applyUserInteraction();
  109685. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  109686. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  109687. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  109688. // Step camera rotation by rotation speed
  109689. if (_this._attachedCamera) {
  109690. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  109691. }
  109692. });
  109693. };
  109694. /**
  109695. * Detaches the behavior from its current arc rotate camera.
  109696. */
  109697. AutoRotationBehavior.prototype.detach = function () {
  109698. if (!this._attachedCamera) {
  109699. return;
  109700. }
  109701. var scene = this._attachedCamera.getScene();
  109702. if (this._onPrePointerObservableObserver) {
  109703. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  109704. }
  109705. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109706. this._attachedCamera = null;
  109707. };
  109708. /**
  109709. * Returns true if user is scrolling.
  109710. * @return true if user is scrolling.
  109711. */
  109712. AutoRotationBehavior.prototype._userIsZooming = function () {
  109713. if (!this._attachedCamera) {
  109714. return false;
  109715. }
  109716. return this._attachedCamera.inertialRadiusOffset !== 0;
  109717. };
  109718. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  109719. if (!this._attachedCamera) {
  109720. return false;
  109721. }
  109722. var zoomHasHitLimit = false;
  109723. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  109724. zoomHasHitLimit = true;
  109725. }
  109726. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  109727. this._lastFrameRadius = this._attachedCamera.radius;
  109728. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  109729. };
  109730. /**
  109731. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  109732. */
  109733. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  109734. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  109735. this._lastInteractionTime = BABYLON.Tools.Now;
  109736. }
  109737. };
  109738. // Tools
  109739. AutoRotationBehavior.prototype._userIsMoving = function () {
  109740. if (!this._attachedCamera) {
  109741. return false;
  109742. }
  109743. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  109744. this._attachedCamera.inertialBetaOffset !== 0 ||
  109745. this._attachedCamera.inertialRadiusOffset !== 0 ||
  109746. this._attachedCamera.inertialPanningX !== 0 ||
  109747. this._attachedCamera.inertialPanningY !== 0 ||
  109748. this._isPointerDown;
  109749. };
  109750. return AutoRotationBehavior;
  109751. }());
  109752. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  109753. })(BABYLON || (BABYLON = {}));
  109754. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  109755. var BABYLON;
  109756. (function (BABYLON) {
  109757. var NullEngineOptions = /** @class */ (function () {
  109758. function NullEngineOptions() {
  109759. this.renderWidth = 512;
  109760. this.renderHeight = 256;
  109761. this.textureSize = 512;
  109762. this.deterministicLockstep = false;
  109763. this.lockstepMaxSteps = 4;
  109764. }
  109765. return NullEngineOptions;
  109766. }());
  109767. BABYLON.NullEngineOptions = NullEngineOptions;
  109768. /**
  109769. * The null engine class provides support for headless version of babylon.js.
  109770. * This can be used in server side scenario or for testing purposes
  109771. */
  109772. var NullEngine = /** @class */ (function (_super) {
  109773. __extends(NullEngine, _super);
  109774. function NullEngine(options) {
  109775. if (options === void 0) { options = new NullEngineOptions(); }
  109776. var _this = _super.call(this, null) || this;
  109777. if (options.deterministicLockstep === undefined) {
  109778. options.deterministicLockstep = false;
  109779. }
  109780. if (options.lockstepMaxSteps === undefined) {
  109781. options.lockstepMaxSteps = 4;
  109782. }
  109783. _this._options = options;
  109784. // Init caps
  109785. // We consider we are on a webgl1 capable device
  109786. _this._caps = new BABYLON.EngineCapabilities();
  109787. _this._caps.maxTexturesImageUnits = 16;
  109788. _this._caps.maxVertexTextureImageUnits = 16;
  109789. _this._caps.maxTextureSize = 512;
  109790. _this._caps.maxCubemapTextureSize = 512;
  109791. _this._caps.maxRenderTextureSize = 512;
  109792. _this._caps.maxVertexAttribs = 16;
  109793. _this._caps.maxVaryingVectors = 16;
  109794. _this._caps.maxFragmentUniformVectors = 16;
  109795. _this._caps.maxVertexUniformVectors = 16;
  109796. // Extensions
  109797. _this._caps.standardDerivatives = false;
  109798. _this._caps.astc = null;
  109799. _this._caps.s3tc = null;
  109800. _this._caps.pvrtc = null;
  109801. _this._caps.etc1 = null;
  109802. _this._caps.etc2 = null;
  109803. _this._caps.textureAnisotropicFilterExtension = null;
  109804. _this._caps.maxAnisotropy = 0;
  109805. _this._caps.uintIndices = false;
  109806. _this._caps.fragmentDepthSupported = false;
  109807. _this._caps.highPrecisionShaderSupported = true;
  109808. _this._caps.colorBufferFloat = false;
  109809. _this._caps.textureFloat = false;
  109810. _this._caps.textureFloatLinearFiltering = false;
  109811. _this._caps.textureFloatRender = false;
  109812. _this._caps.textureHalfFloat = false;
  109813. _this._caps.textureHalfFloatLinearFiltering = false;
  109814. _this._caps.textureHalfFloatRender = false;
  109815. _this._caps.textureLOD = false;
  109816. _this._caps.drawBuffersExtension = false;
  109817. _this._caps.depthTextureExtension = false;
  109818. _this._caps.vertexArrayObject = false;
  109819. _this._caps.instancedArrays = false;
  109820. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  109821. // Wrappers
  109822. if (typeof URL === "undefined") {
  109823. URL = {
  109824. createObjectURL: function () { },
  109825. revokeObjectURL: function () { }
  109826. };
  109827. }
  109828. if (typeof Blob === "undefined") {
  109829. Blob = function () { };
  109830. }
  109831. return _this;
  109832. }
  109833. NullEngine.prototype.isDeterministicLockStep = function () {
  109834. return this._options.deterministicLockstep;
  109835. };
  109836. NullEngine.prototype.getLockstepMaxSteps = function () {
  109837. return this._options.lockstepMaxSteps;
  109838. };
  109839. NullEngine.prototype.getHardwareScalingLevel = function () {
  109840. return 1.0;
  109841. };
  109842. NullEngine.prototype.createVertexBuffer = function (vertices) {
  109843. return {
  109844. capacity: 0,
  109845. references: 1,
  109846. is32Bits: false
  109847. };
  109848. };
  109849. NullEngine.prototype.createIndexBuffer = function (indices) {
  109850. return {
  109851. capacity: 0,
  109852. references: 1,
  109853. is32Bits: false
  109854. };
  109855. };
  109856. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  109857. if (stencil === void 0) { stencil = false; }
  109858. };
  109859. NullEngine.prototype.getRenderWidth = function (useScreen) {
  109860. if (useScreen === void 0) { useScreen = false; }
  109861. if (!useScreen && this._currentRenderTarget) {
  109862. return this._currentRenderTarget.width;
  109863. }
  109864. return this._options.renderWidth;
  109865. };
  109866. NullEngine.prototype.getRenderHeight = function (useScreen) {
  109867. if (useScreen === void 0) { useScreen = false; }
  109868. if (!useScreen && this._currentRenderTarget) {
  109869. return this._currentRenderTarget.height;
  109870. }
  109871. return this._options.renderHeight;
  109872. };
  109873. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  109874. this._cachedViewport = viewport;
  109875. };
  109876. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  109877. return {
  109878. transformFeedback: null,
  109879. __SPECTOR_rebuildProgram: null
  109880. };
  109881. };
  109882. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  109883. return [];
  109884. };
  109885. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  109886. return [];
  109887. };
  109888. NullEngine.prototype.bindSamplers = function (effect) {
  109889. this._currentEffect = null;
  109890. };
  109891. NullEngine.prototype.enableEffect = function (effect) {
  109892. this._currentEffect = effect;
  109893. if (effect.onBind) {
  109894. effect.onBind(effect);
  109895. }
  109896. if (effect._onBindObservable) {
  109897. effect._onBindObservable.notifyObservers(effect);
  109898. }
  109899. };
  109900. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  109901. if (zOffset === void 0) { zOffset = 0; }
  109902. if (reverseSide === void 0) { reverseSide = false; }
  109903. };
  109904. NullEngine.prototype.setIntArray = function (uniform, array) {
  109905. };
  109906. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  109907. };
  109908. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  109909. };
  109910. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  109911. };
  109912. NullEngine.prototype.setFloatArray = function (uniform, array) {
  109913. };
  109914. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  109915. };
  109916. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  109917. };
  109918. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  109919. };
  109920. NullEngine.prototype.setArray = function (uniform, array) {
  109921. };
  109922. NullEngine.prototype.setArray2 = function (uniform, array) {
  109923. };
  109924. NullEngine.prototype.setArray3 = function (uniform, array) {
  109925. };
  109926. NullEngine.prototype.setArray4 = function (uniform, array) {
  109927. };
  109928. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  109929. };
  109930. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  109931. };
  109932. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  109933. };
  109934. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  109935. };
  109936. NullEngine.prototype.setFloat = function (uniform, value) {
  109937. };
  109938. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  109939. };
  109940. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  109941. };
  109942. NullEngine.prototype.setBool = function (uniform, bool) {
  109943. };
  109944. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  109945. };
  109946. NullEngine.prototype.setColor3 = function (uniform, color3) {
  109947. };
  109948. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  109949. };
  109950. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  109951. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  109952. if (this._alphaMode === mode) {
  109953. return;
  109954. }
  109955. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  109956. if (!noDepthWriteChange) {
  109957. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  109958. }
  109959. this._alphaMode = mode;
  109960. };
  109961. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  109962. };
  109963. NullEngine.prototype.wipeCaches = function (bruteForce) {
  109964. if (this.preventCacheWipeBetweenFrames) {
  109965. return;
  109966. }
  109967. this.resetTextureCache();
  109968. this._currentEffect = null;
  109969. if (bruteForce) {
  109970. this._currentProgram = null;
  109971. this._stencilState.reset();
  109972. this._depthCullingState.reset();
  109973. this._alphaState.reset();
  109974. }
  109975. this._cachedVertexBuffers = null;
  109976. this._cachedIndexBuffer = null;
  109977. this._cachedEffectForVertexBuffers = null;
  109978. };
  109979. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  109980. };
  109981. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  109982. };
  109983. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  109984. };
  109985. /** @hidden */
  109986. NullEngine.prototype._createTexture = function () {
  109987. return {};
  109988. };
  109989. /** @hidden */
  109990. NullEngine.prototype._releaseTexture = function (texture) {
  109991. };
  109992. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  109993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109994. if (onLoad === void 0) { onLoad = null; }
  109995. if (onError === void 0) { onError = null; }
  109996. if (buffer === void 0) { buffer = null; }
  109997. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  109998. var url = String(urlArg);
  109999. texture.url = url;
  110000. texture.generateMipMaps = !noMipmap;
  110001. texture.samplingMode = samplingMode;
  110002. texture.invertY = invertY;
  110003. texture.baseWidth = this._options.textureSize;
  110004. texture.baseHeight = this._options.textureSize;
  110005. texture.width = this._options.textureSize;
  110006. texture.height = this._options.textureSize;
  110007. if (format) {
  110008. texture.format = format;
  110009. }
  110010. texture.isReady = true;
  110011. if (onLoad) {
  110012. onLoad();
  110013. }
  110014. this._internalTexturesCache.push(texture);
  110015. return texture;
  110016. };
  110017. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  110018. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  110019. if (options !== undefined && typeof options === "object") {
  110020. fullOptions.generateMipMaps = options.generateMipMaps;
  110021. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  110022. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  110023. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  110024. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  110025. }
  110026. else {
  110027. fullOptions.generateMipMaps = options;
  110028. fullOptions.generateDepthBuffer = true;
  110029. fullOptions.generateStencilBuffer = false;
  110030. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  110031. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  110032. }
  110033. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  110034. var width = size.width || size;
  110035. var height = size.height || size;
  110036. texture._depthStencilBuffer = {};
  110037. texture._framebuffer = {};
  110038. texture.baseWidth = width;
  110039. texture.baseHeight = height;
  110040. texture.width = width;
  110041. texture.height = height;
  110042. texture.isReady = true;
  110043. texture.samples = 1;
  110044. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  110045. texture.samplingMode = fullOptions.samplingMode;
  110046. texture.type = fullOptions.type;
  110047. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  110048. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  110049. this._internalTexturesCache.push(texture);
  110050. return texture;
  110051. };
  110052. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  110053. texture.samplingMode = samplingMode;
  110054. };
  110055. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  110056. if (this._currentRenderTarget) {
  110057. this.unBindFramebuffer(this._currentRenderTarget);
  110058. }
  110059. this._currentRenderTarget = texture;
  110060. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  110061. if (this._cachedViewport && !forceFullscreenViewport) {
  110062. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  110063. }
  110064. };
  110065. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  110066. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  110067. this._currentRenderTarget = null;
  110068. if (onBeforeUnbind) {
  110069. if (texture._MSAAFramebuffer) {
  110070. this._currentFramebuffer = texture._framebuffer;
  110071. }
  110072. onBeforeUnbind();
  110073. }
  110074. this._currentFramebuffer = null;
  110075. };
  110076. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  110077. var vbo = {
  110078. capacity: 1,
  110079. references: 1,
  110080. is32Bits: false
  110081. };
  110082. return vbo;
  110083. };
  110084. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  110085. if (premulAlpha === void 0) { premulAlpha = false; }
  110086. };
  110087. /**
  110088. * @hidden
  110089. * Get the current error code of the webGL context
  110090. * @returns the error code
  110091. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  110092. */
  110093. NullEngine.prototype.getError = function () {
  110094. return 0;
  110095. };
  110096. /** @hidden */
  110097. NullEngine.prototype._getUnpackAlignement = function () {
  110098. return 1;
  110099. };
  110100. /** @hidden */
  110101. NullEngine.prototype._unpackFlipY = function (value) {
  110102. };
  110103. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  110104. if (offset === void 0) { offset = 0; }
  110105. };
  110106. /**
  110107. * Updates a dynamic vertex buffer.
  110108. * @param vertexBuffer the vertex buffer to update
  110109. * @param data the data used to update the vertex buffer
  110110. * @param byteOffset the byte offset of the data (optional)
  110111. * @param byteLength the byte length of the data (optional)
  110112. */
  110113. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  110114. };
  110115. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  110116. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  110117. this._boundTexturesCache[this._activeChannel] = texture;
  110118. return true;
  110119. }
  110120. return false;
  110121. };
  110122. /** @hidden */
  110123. NullEngine.prototype._bindTexture = function (channel, texture) {
  110124. if (channel < 0) {
  110125. return;
  110126. }
  110127. this._bindTextureDirectly(0, texture);
  110128. };
  110129. /** @hidden */
  110130. NullEngine.prototype._releaseBuffer = function (buffer) {
  110131. buffer.references--;
  110132. if (buffer.references === 0) {
  110133. return true;
  110134. }
  110135. return false;
  110136. };
  110137. NullEngine.prototype.releaseEffects = function () {
  110138. };
  110139. NullEngine.prototype.displayLoadingUI = function () {
  110140. };
  110141. NullEngine.prototype.hideLoadingUI = function () {
  110142. };
  110143. /** @hidden */
  110144. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  110145. if (faceIndex === void 0) { faceIndex = 0; }
  110146. if (lod === void 0) { lod = 0; }
  110147. };
  110148. /** @hidden */
  110149. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  110150. if (faceIndex === void 0) { faceIndex = 0; }
  110151. if (lod === void 0) { lod = 0; }
  110152. };
  110153. /** @hidden */
  110154. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  110155. if (faceIndex === void 0) { faceIndex = 0; }
  110156. if (lod === void 0) { lod = 0; }
  110157. };
  110158. /** @hidden */
  110159. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  110160. if (faceIndex === void 0) { faceIndex = 0; }
  110161. if (lod === void 0) { lod = 0; }
  110162. };
  110163. return NullEngine;
  110164. }(BABYLON.Engine));
  110165. BABYLON.NullEngine = NullEngine;
  110166. })(BABYLON || (BABYLON = {}));
  110167. //# sourceMappingURL=babylon.nullEngine.js.map
  110168. var BABYLON;
  110169. (function (BABYLON) {
  110170. /**
  110171. * This class can be used to get instrumentation data from a Babylon engine
  110172. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  110173. */
  110174. var EngineInstrumentation = /** @class */ (function () {
  110175. /**
  110176. * Instantiates a new engine instrumentation.
  110177. * This class can be used to get instrumentation data from a Babylon engine
  110178. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  110179. * @param engine Defines the engine to instrument
  110180. */
  110181. function EngineInstrumentation(
  110182. /**
  110183. * Define the instrumented engine.
  110184. */
  110185. engine) {
  110186. this.engine = engine;
  110187. this._captureGPUFrameTime = false;
  110188. this._gpuFrameTime = new BABYLON.PerfCounter();
  110189. this._captureShaderCompilationTime = false;
  110190. this._shaderCompilationTime = new BABYLON.PerfCounter();
  110191. // Observers
  110192. this._onBeginFrameObserver = null;
  110193. this._onEndFrameObserver = null;
  110194. this._onBeforeShaderCompilationObserver = null;
  110195. this._onAfterShaderCompilationObserver = null;
  110196. }
  110197. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  110198. // Properties
  110199. /**
  110200. * Gets the perf counter used for GPU frame time
  110201. */
  110202. get: function () {
  110203. return this._gpuFrameTime;
  110204. },
  110205. enumerable: true,
  110206. configurable: true
  110207. });
  110208. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  110209. /**
  110210. * Gets the GPU frame time capture status
  110211. */
  110212. get: function () {
  110213. return this._captureGPUFrameTime;
  110214. },
  110215. /**
  110216. * Enable or disable the GPU frame time capture
  110217. */
  110218. set: function (value) {
  110219. var _this = this;
  110220. if (value === this._captureGPUFrameTime) {
  110221. return;
  110222. }
  110223. this._captureGPUFrameTime = value;
  110224. if (value) {
  110225. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  110226. if (!_this._gpuFrameTimeToken) {
  110227. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  110228. }
  110229. });
  110230. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  110231. if (!_this._gpuFrameTimeToken) {
  110232. return;
  110233. }
  110234. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  110235. if (time > -1) {
  110236. _this._gpuFrameTimeToken = null;
  110237. _this._gpuFrameTime.fetchNewFrame();
  110238. _this._gpuFrameTime.addCount(time, true);
  110239. }
  110240. });
  110241. }
  110242. else {
  110243. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  110244. this._onBeginFrameObserver = null;
  110245. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  110246. this._onEndFrameObserver = null;
  110247. }
  110248. },
  110249. enumerable: true,
  110250. configurable: true
  110251. });
  110252. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  110253. /**
  110254. * Gets the perf counter used for shader compilation time
  110255. */
  110256. get: function () {
  110257. return this._shaderCompilationTime;
  110258. },
  110259. enumerable: true,
  110260. configurable: true
  110261. });
  110262. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  110263. /**
  110264. * Gets the shader compilation time capture status
  110265. */
  110266. get: function () {
  110267. return this._captureShaderCompilationTime;
  110268. },
  110269. /**
  110270. * Enable or disable the shader compilation time capture
  110271. */
  110272. set: function (value) {
  110273. var _this = this;
  110274. if (value === this._captureShaderCompilationTime) {
  110275. return;
  110276. }
  110277. this._captureShaderCompilationTime = value;
  110278. if (value) {
  110279. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  110280. _this._shaderCompilationTime.fetchNewFrame();
  110281. _this._shaderCompilationTime.beginMonitoring();
  110282. });
  110283. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  110284. _this._shaderCompilationTime.endMonitoring();
  110285. });
  110286. }
  110287. else {
  110288. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  110289. this._onBeforeShaderCompilationObserver = null;
  110290. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  110291. this._onAfterShaderCompilationObserver = null;
  110292. }
  110293. },
  110294. enumerable: true,
  110295. configurable: true
  110296. });
  110297. /**
  110298. * Dispose and release associated resources.
  110299. */
  110300. EngineInstrumentation.prototype.dispose = function () {
  110301. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  110302. this._onBeginFrameObserver = null;
  110303. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  110304. this._onEndFrameObserver = null;
  110305. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  110306. this._onBeforeShaderCompilationObserver = null;
  110307. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  110308. this._onAfterShaderCompilationObserver = null;
  110309. this.engine = null;
  110310. };
  110311. return EngineInstrumentation;
  110312. }());
  110313. BABYLON.EngineInstrumentation = EngineInstrumentation;
  110314. })(BABYLON || (BABYLON = {}));
  110315. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  110316. var BABYLON;
  110317. (function (BABYLON) {
  110318. /**
  110319. * This class can be used to get instrumentation data from a Babylon engine
  110320. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  110321. */
  110322. var SceneInstrumentation = /** @class */ (function () {
  110323. /**
  110324. * Instantiates a new scene instrumentation.
  110325. * This class can be used to get instrumentation data from a Babylon engine
  110326. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  110327. * @param scene Defines the scene to instrument
  110328. */
  110329. function SceneInstrumentation(
  110330. /**
  110331. * Defines the scene to instrument
  110332. */
  110333. scene) {
  110334. var _this = this;
  110335. this.scene = scene;
  110336. this._captureActiveMeshesEvaluationTime = false;
  110337. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  110338. this._captureRenderTargetsRenderTime = false;
  110339. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  110340. this._captureFrameTime = false;
  110341. this._frameTime = new BABYLON.PerfCounter();
  110342. this._captureRenderTime = false;
  110343. this._renderTime = new BABYLON.PerfCounter();
  110344. this._captureInterFrameTime = false;
  110345. this._interFrameTime = new BABYLON.PerfCounter();
  110346. this._captureParticlesRenderTime = false;
  110347. this._particlesRenderTime = new BABYLON.PerfCounter();
  110348. this._captureSpritesRenderTime = false;
  110349. this._spritesRenderTime = new BABYLON.PerfCounter();
  110350. this._capturePhysicsTime = false;
  110351. this._physicsTime = new BABYLON.PerfCounter();
  110352. this._captureAnimationsTime = false;
  110353. this._animationsTime = new BABYLON.PerfCounter();
  110354. this._captureCameraRenderTime = false;
  110355. this._cameraRenderTime = new BABYLON.PerfCounter();
  110356. // Observers
  110357. this._onBeforeActiveMeshesEvaluationObserver = null;
  110358. this._onAfterActiveMeshesEvaluationObserver = null;
  110359. this._onBeforeRenderTargetsRenderObserver = null;
  110360. this._onAfterRenderTargetsRenderObserver = null;
  110361. this._onAfterRenderObserver = null;
  110362. this._onBeforeDrawPhaseObserver = null;
  110363. this._onAfterDrawPhaseObserver = null;
  110364. this._onBeforeAnimationsObserver = null;
  110365. this._onBeforeParticlesRenderingObserver = null;
  110366. this._onAfterParticlesRenderingObserver = null;
  110367. this._onBeforeSpritesRenderingObserver = null;
  110368. this._onAfterSpritesRenderingObserver = null;
  110369. this._onBeforePhysicsObserver = null;
  110370. this._onAfterPhysicsObserver = null;
  110371. this._onAfterAnimationsObserver = null;
  110372. this._onBeforeCameraRenderObserver = null;
  110373. this._onAfterCameraRenderObserver = null;
  110374. // Before render
  110375. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  110376. if (_this._captureActiveMeshesEvaluationTime) {
  110377. _this._activeMeshesEvaluationTime.fetchNewFrame();
  110378. }
  110379. if (_this._captureRenderTargetsRenderTime) {
  110380. _this._renderTargetsRenderTime.fetchNewFrame();
  110381. }
  110382. if (_this._captureFrameTime) {
  110383. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  110384. _this._frameTime.beginMonitoring();
  110385. }
  110386. if (_this._captureInterFrameTime) {
  110387. _this._interFrameTime.endMonitoring();
  110388. }
  110389. if (_this._captureParticlesRenderTime) {
  110390. _this._particlesRenderTime.fetchNewFrame();
  110391. }
  110392. if (_this._captureSpritesRenderTime) {
  110393. _this._spritesRenderTime.fetchNewFrame();
  110394. }
  110395. if (_this._captureAnimationsTime) {
  110396. _this._animationsTime.beginMonitoring();
  110397. }
  110398. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  110399. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  110400. });
  110401. // After render
  110402. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  110403. if (_this._captureFrameTime) {
  110404. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  110405. _this._frameTime.endMonitoring();
  110406. }
  110407. if (_this._captureRenderTime) {
  110408. _this._renderTime.endMonitoring(false);
  110409. }
  110410. if (_this._captureInterFrameTime) {
  110411. _this._interFrameTime.beginMonitoring();
  110412. }
  110413. });
  110414. }
  110415. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  110416. // Properties
  110417. /**
  110418. * Gets the perf counter used for active meshes evaluation time
  110419. */
  110420. get: function () {
  110421. return this._activeMeshesEvaluationTime;
  110422. },
  110423. enumerable: true,
  110424. configurable: true
  110425. });
  110426. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  110427. /**
  110428. * Gets the active meshes evaluation time capture status
  110429. */
  110430. get: function () {
  110431. return this._captureActiveMeshesEvaluationTime;
  110432. },
  110433. /**
  110434. * Enable or disable the active meshes evaluation time capture
  110435. */
  110436. set: function (value) {
  110437. var _this = this;
  110438. if (value === this._captureActiveMeshesEvaluationTime) {
  110439. return;
  110440. }
  110441. this._captureActiveMeshesEvaluationTime = value;
  110442. if (value) {
  110443. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  110444. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  110445. _this._activeMeshesEvaluationTime.beginMonitoring();
  110446. });
  110447. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  110448. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  110449. _this._activeMeshesEvaluationTime.endMonitoring();
  110450. });
  110451. }
  110452. else {
  110453. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  110454. this._onBeforeActiveMeshesEvaluationObserver = null;
  110455. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  110456. this._onAfterActiveMeshesEvaluationObserver = null;
  110457. }
  110458. },
  110459. enumerable: true,
  110460. configurable: true
  110461. });
  110462. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  110463. /**
  110464. * Gets the perf counter used for render targets render time
  110465. */
  110466. get: function () {
  110467. return this._renderTargetsRenderTime;
  110468. },
  110469. enumerable: true,
  110470. configurable: true
  110471. });
  110472. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  110473. /**
  110474. * Gets the render targets render time capture status
  110475. */
  110476. get: function () {
  110477. return this._captureRenderTargetsRenderTime;
  110478. },
  110479. /**
  110480. * Enable or disable the render targets render time capture
  110481. */
  110482. set: function (value) {
  110483. var _this = this;
  110484. if (value === this._captureRenderTargetsRenderTime) {
  110485. return;
  110486. }
  110487. this._captureRenderTargetsRenderTime = value;
  110488. if (value) {
  110489. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  110490. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  110491. _this._renderTargetsRenderTime.beginMonitoring();
  110492. });
  110493. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  110494. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  110495. _this._renderTargetsRenderTime.endMonitoring(false);
  110496. });
  110497. }
  110498. else {
  110499. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  110500. this._onBeforeRenderTargetsRenderObserver = null;
  110501. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  110502. this._onAfterRenderTargetsRenderObserver = null;
  110503. }
  110504. },
  110505. enumerable: true,
  110506. configurable: true
  110507. });
  110508. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  110509. /**
  110510. * Gets the perf counter used for particles render time
  110511. */
  110512. get: function () {
  110513. return this._particlesRenderTime;
  110514. },
  110515. enumerable: true,
  110516. configurable: true
  110517. });
  110518. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  110519. /**
  110520. * Gets the particles render time capture status
  110521. */
  110522. get: function () {
  110523. return this._captureParticlesRenderTime;
  110524. },
  110525. /**
  110526. * Enable or disable the particles render time capture
  110527. */
  110528. set: function (value) {
  110529. var _this = this;
  110530. if (value === this._captureParticlesRenderTime) {
  110531. return;
  110532. }
  110533. this._captureParticlesRenderTime = value;
  110534. if (value) {
  110535. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  110536. BABYLON.Tools.StartPerformanceCounter("Particles");
  110537. _this._particlesRenderTime.beginMonitoring();
  110538. });
  110539. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  110540. BABYLON.Tools.EndPerformanceCounter("Particles");
  110541. _this._particlesRenderTime.endMonitoring(false);
  110542. });
  110543. }
  110544. else {
  110545. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  110546. this._onBeforeParticlesRenderingObserver = null;
  110547. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  110548. this._onAfterParticlesRenderingObserver = null;
  110549. }
  110550. },
  110551. enumerable: true,
  110552. configurable: true
  110553. });
  110554. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  110555. /**
  110556. * Gets the perf counter used for sprites render time
  110557. */
  110558. get: function () {
  110559. return this._spritesRenderTime;
  110560. },
  110561. enumerable: true,
  110562. configurable: true
  110563. });
  110564. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  110565. /**
  110566. * Gets the sprites render time capture status
  110567. */
  110568. get: function () {
  110569. return this._captureSpritesRenderTime;
  110570. },
  110571. /**
  110572. * Enable or disable the sprites render time capture
  110573. */
  110574. set: function (value) {
  110575. var _this = this;
  110576. if (value === this._captureSpritesRenderTime) {
  110577. return;
  110578. }
  110579. this._captureSpritesRenderTime = value;
  110580. if (!this.scene.spriteManagers) {
  110581. return;
  110582. }
  110583. if (value) {
  110584. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  110585. BABYLON.Tools.StartPerformanceCounter("Sprites");
  110586. _this._spritesRenderTime.beginMonitoring();
  110587. });
  110588. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  110589. BABYLON.Tools.EndPerformanceCounter("Sprites");
  110590. _this._spritesRenderTime.endMonitoring(false);
  110591. });
  110592. }
  110593. else {
  110594. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  110595. this._onBeforeSpritesRenderingObserver = null;
  110596. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  110597. this._onAfterSpritesRenderingObserver = null;
  110598. }
  110599. },
  110600. enumerable: true,
  110601. configurable: true
  110602. });
  110603. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  110604. /**
  110605. * Gets the perf counter used for physics time
  110606. */
  110607. get: function () {
  110608. return this._physicsTime;
  110609. },
  110610. enumerable: true,
  110611. configurable: true
  110612. });
  110613. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  110614. /**
  110615. * Gets the physics time capture status
  110616. */
  110617. get: function () {
  110618. return this._capturePhysicsTime;
  110619. },
  110620. /**
  110621. * Enable or disable the physics time capture
  110622. */
  110623. set: function (value) {
  110624. var _this = this;
  110625. if (value === this._capturePhysicsTime) {
  110626. return;
  110627. }
  110628. if (!this.scene.onBeforePhysicsObservable) {
  110629. return;
  110630. }
  110631. this._capturePhysicsTime = value;
  110632. if (value) {
  110633. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  110634. BABYLON.Tools.StartPerformanceCounter("Physics");
  110635. _this._physicsTime.beginMonitoring();
  110636. });
  110637. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  110638. BABYLON.Tools.EndPerformanceCounter("Physics");
  110639. _this._physicsTime.endMonitoring();
  110640. });
  110641. }
  110642. else {
  110643. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110644. this._onBeforePhysicsObserver = null;
  110645. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110646. this._onAfterPhysicsObserver = null;
  110647. }
  110648. },
  110649. enumerable: true,
  110650. configurable: true
  110651. });
  110652. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  110653. /**
  110654. * Gets the perf counter used for animations time
  110655. */
  110656. get: function () {
  110657. return this._animationsTime;
  110658. },
  110659. enumerable: true,
  110660. configurable: true
  110661. });
  110662. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  110663. /**
  110664. * Gets the animations time capture status
  110665. */
  110666. get: function () {
  110667. return this._captureAnimationsTime;
  110668. },
  110669. /**
  110670. * Enable or disable the animations time capture
  110671. */
  110672. set: function (value) {
  110673. var _this = this;
  110674. if (value === this._captureAnimationsTime) {
  110675. return;
  110676. }
  110677. this._captureAnimationsTime = value;
  110678. if (value) {
  110679. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  110680. _this._animationsTime.endMonitoring();
  110681. });
  110682. }
  110683. else {
  110684. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110685. this._onAfterAnimationsObserver = null;
  110686. }
  110687. },
  110688. enumerable: true,
  110689. configurable: true
  110690. });
  110691. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  110692. /**
  110693. * Gets the perf counter used for frame time capture
  110694. */
  110695. get: function () {
  110696. return this._frameTime;
  110697. },
  110698. enumerable: true,
  110699. configurable: true
  110700. });
  110701. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  110702. /**
  110703. * Gets the frame time capture status
  110704. */
  110705. get: function () {
  110706. return this._captureFrameTime;
  110707. },
  110708. /**
  110709. * Enable or disable the frame time capture
  110710. */
  110711. set: function (value) {
  110712. this._captureFrameTime = value;
  110713. },
  110714. enumerable: true,
  110715. configurable: true
  110716. });
  110717. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  110718. /**
  110719. * Gets the perf counter used for inter-frames time capture
  110720. */
  110721. get: function () {
  110722. return this._interFrameTime;
  110723. },
  110724. enumerable: true,
  110725. configurable: true
  110726. });
  110727. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  110728. /**
  110729. * Gets the inter-frames time capture status
  110730. */
  110731. get: function () {
  110732. return this._captureInterFrameTime;
  110733. },
  110734. /**
  110735. * Enable or disable the inter-frames time capture
  110736. */
  110737. set: function (value) {
  110738. this._captureInterFrameTime = value;
  110739. },
  110740. enumerable: true,
  110741. configurable: true
  110742. });
  110743. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  110744. /**
  110745. * Gets the perf counter used for render time capture
  110746. */
  110747. get: function () {
  110748. return this._renderTime;
  110749. },
  110750. enumerable: true,
  110751. configurable: true
  110752. });
  110753. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  110754. /**
  110755. * Gets the render time capture status
  110756. */
  110757. get: function () {
  110758. return this._captureRenderTime;
  110759. },
  110760. /**
  110761. * Enable or disable the render time capture
  110762. */
  110763. set: function (value) {
  110764. var _this = this;
  110765. if (value === this._captureRenderTime) {
  110766. return;
  110767. }
  110768. this._captureRenderTime = value;
  110769. if (value) {
  110770. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  110771. _this._renderTime.beginMonitoring();
  110772. BABYLON.Tools.StartPerformanceCounter("Main render");
  110773. });
  110774. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  110775. _this._renderTime.endMonitoring(false);
  110776. BABYLON.Tools.EndPerformanceCounter("Main render");
  110777. });
  110778. }
  110779. else {
  110780. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110781. this._onBeforeDrawPhaseObserver = null;
  110782. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110783. this._onAfterDrawPhaseObserver = null;
  110784. }
  110785. },
  110786. enumerable: true,
  110787. configurable: true
  110788. });
  110789. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  110790. /**
  110791. * Gets the perf counter used for camera render time capture
  110792. */
  110793. get: function () {
  110794. return this._cameraRenderTime;
  110795. },
  110796. enumerable: true,
  110797. configurable: true
  110798. });
  110799. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  110800. /**
  110801. * Gets the camera render time capture status
  110802. */
  110803. get: function () {
  110804. return this._captureCameraRenderTime;
  110805. },
  110806. /**
  110807. * Enable or disable the camera render time capture
  110808. */
  110809. set: function (value) {
  110810. var _this = this;
  110811. if (value === this._captureCameraRenderTime) {
  110812. return;
  110813. }
  110814. this._captureCameraRenderTime = value;
  110815. if (value) {
  110816. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  110817. _this._cameraRenderTime.beginMonitoring();
  110818. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  110819. });
  110820. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  110821. _this._cameraRenderTime.endMonitoring(false);
  110822. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  110823. });
  110824. }
  110825. else {
  110826. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110827. this._onBeforeCameraRenderObserver = null;
  110828. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110829. this._onAfterCameraRenderObserver = null;
  110830. }
  110831. },
  110832. enumerable: true,
  110833. configurable: true
  110834. });
  110835. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  110836. /**
  110837. * Gets the perf counter used for draw calls
  110838. */
  110839. get: function () {
  110840. return this.scene.getEngine()._drawCalls;
  110841. },
  110842. enumerable: true,
  110843. configurable: true
  110844. });
  110845. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  110846. /**
  110847. * Gets the perf counter used for texture collisions
  110848. */
  110849. get: function () {
  110850. return this.scene.getEngine()._textureCollisions;
  110851. },
  110852. enumerable: true,
  110853. configurable: true
  110854. });
  110855. /**
  110856. * Dispose and release associated resources.
  110857. */
  110858. SceneInstrumentation.prototype.dispose = function () {
  110859. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  110860. this._onAfterRenderObserver = null;
  110861. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  110862. this._onBeforeActiveMeshesEvaluationObserver = null;
  110863. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  110864. this._onAfterActiveMeshesEvaluationObserver = null;
  110865. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  110866. this._onBeforeRenderTargetsRenderObserver = null;
  110867. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  110868. this._onAfterRenderTargetsRenderObserver = null;
  110869. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  110870. this._onBeforeAnimationsObserver = null;
  110871. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  110872. this._onBeforeParticlesRenderingObserver = null;
  110873. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  110874. this._onAfterParticlesRenderingObserver = null;
  110875. if (this._onBeforeSpritesRenderingObserver) {
  110876. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  110877. this._onBeforeSpritesRenderingObserver = null;
  110878. }
  110879. if (this._onAfterSpritesRenderingObserver) {
  110880. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  110881. this._onAfterSpritesRenderingObserver = null;
  110882. }
  110883. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110884. this._onBeforeDrawPhaseObserver = null;
  110885. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110886. this._onAfterDrawPhaseObserver = null;
  110887. if (this._onBeforePhysicsObserver) {
  110888. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110889. this._onBeforePhysicsObserver = null;
  110890. }
  110891. if (this._onAfterPhysicsObserver) {
  110892. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110893. this._onAfterPhysicsObserver = null;
  110894. }
  110895. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110896. this._onAfterAnimationsObserver = null;
  110897. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110898. this._onBeforeCameraRenderObserver = null;
  110899. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110900. this._onAfterCameraRenderObserver = null;
  110901. this.scene = null;
  110902. };
  110903. return SceneInstrumentation;
  110904. }());
  110905. BABYLON.SceneInstrumentation = SceneInstrumentation;
  110906. })(BABYLON || (BABYLON = {}));
  110907. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  110908. var BABYLON;
  110909. (function (BABYLON) {
  110910. /**
  110911. * @hidden
  110912. **/
  110913. var _TimeToken = /** @class */ (function () {
  110914. function _TimeToken() {
  110915. this._timeElapsedQueryEnded = false;
  110916. }
  110917. return _TimeToken;
  110918. }());
  110919. BABYLON._TimeToken = _TimeToken;
  110920. })(BABYLON || (BABYLON = {}));
  110921. //# sourceMappingURL=babylon.timeToken.js.map
  110922. var BABYLON;
  110923. (function (BABYLON) {
  110924. /**
  110925. * Background material defines definition.
  110926. * @hidden Mainly internal Use
  110927. */
  110928. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  110929. __extends(BackgroundMaterialDefines, _super);
  110930. /**
  110931. * Constructor of the defines.
  110932. */
  110933. function BackgroundMaterialDefines() {
  110934. var _this = _super.call(this) || this;
  110935. /**
  110936. * True if the diffuse texture is in use.
  110937. */
  110938. _this.DIFFUSE = false;
  110939. /**
  110940. * The direct UV channel to use.
  110941. */
  110942. _this.DIFFUSEDIRECTUV = 0;
  110943. /**
  110944. * True if the diffuse texture is in gamma space.
  110945. */
  110946. _this.GAMMADIFFUSE = false;
  110947. /**
  110948. * True if the diffuse texture has opacity in the alpha channel.
  110949. */
  110950. _this.DIFFUSEHASALPHA = false;
  110951. /**
  110952. * True if you want the material to fade to transparent at grazing angle.
  110953. */
  110954. _this.OPACITYFRESNEL = false;
  110955. /**
  110956. * True if an extra blur needs to be added in the reflection.
  110957. */
  110958. _this.REFLECTIONBLUR = false;
  110959. /**
  110960. * True if you want the material to fade to reflection at grazing angle.
  110961. */
  110962. _this.REFLECTIONFRESNEL = false;
  110963. /**
  110964. * True if you want the material to falloff as far as you move away from the scene center.
  110965. */
  110966. _this.REFLECTIONFALLOFF = false;
  110967. /**
  110968. * False if the current Webgl implementation does not support the texture lod extension.
  110969. */
  110970. _this.TEXTURELODSUPPORT = false;
  110971. /**
  110972. * True to ensure the data are premultiplied.
  110973. */
  110974. _this.PREMULTIPLYALPHA = false;
  110975. /**
  110976. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  110977. */
  110978. _this.USERGBCOLOR = false;
  110979. /**
  110980. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  110981. * stays aligned with the desired configuration.
  110982. */
  110983. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  110984. /**
  110985. * True to add noise in order to reduce the banding effect.
  110986. */
  110987. _this.NOISE = false;
  110988. /**
  110989. * is the reflection texture in BGR color scheme?
  110990. * Mainly used to solve a bug in ios10 video tag
  110991. */
  110992. _this.REFLECTIONBGR = false;
  110993. _this.IMAGEPROCESSING = false;
  110994. _this.VIGNETTE = false;
  110995. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  110996. _this.VIGNETTEBLENDMODEOPAQUE = false;
  110997. _this.TONEMAPPING = false;
  110998. _this.TONEMAPPING_ACES = false;
  110999. _this.CONTRAST = false;
  111000. _this.COLORCURVES = false;
  111001. _this.COLORGRADING = false;
  111002. _this.COLORGRADING3D = false;
  111003. _this.SAMPLER3DGREENDEPTH = false;
  111004. _this.SAMPLER3DBGRMAP = false;
  111005. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  111006. _this.EXPOSURE = false;
  111007. // Reflection.
  111008. _this.REFLECTION = false;
  111009. _this.REFLECTIONMAP_3D = false;
  111010. _this.REFLECTIONMAP_SPHERICAL = false;
  111011. _this.REFLECTIONMAP_PLANAR = false;
  111012. _this.REFLECTIONMAP_CUBIC = false;
  111013. _this.REFLECTIONMAP_PROJECTION = false;
  111014. _this.REFLECTIONMAP_SKYBOX = false;
  111015. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  111016. _this.REFLECTIONMAP_EXPLICIT = false;
  111017. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  111018. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  111019. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  111020. _this.INVERTCUBICMAP = false;
  111021. _this.REFLECTIONMAP_OPPOSITEZ = false;
  111022. _this.LODINREFLECTIONALPHA = false;
  111023. _this.GAMMAREFLECTION = false;
  111024. _this.RGBDREFLECTION = false;
  111025. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  111026. // Default BJS.
  111027. _this.MAINUV1 = false;
  111028. _this.MAINUV2 = false;
  111029. _this.UV1 = false;
  111030. _this.UV2 = false;
  111031. _this.CLIPPLANE = false;
  111032. _this.CLIPPLANE2 = false;
  111033. _this.CLIPPLANE3 = false;
  111034. _this.CLIPPLANE4 = false;
  111035. _this.POINTSIZE = false;
  111036. _this.FOG = false;
  111037. _this.NORMAL = false;
  111038. _this.NUM_BONE_INFLUENCERS = 0;
  111039. _this.BonesPerMesh = 0;
  111040. _this.INSTANCES = false;
  111041. _this.SHADOWFLOAT = false;
  111042. _this.rebuild();
  111043. return _this;
  111044. }
  111045. return BackgroundMaterialDefines;
  111046. }(BABYLON.MaterialDefines));
  111047. /**
  111048. * Background material used to create an efficient environement around your scene.
  111049. */
  111050. var BackgroundMaterial = /** @class */ (function (_super) {
  111051. __extends(BackgroundMaterial, _super);
  111052. /**
  111053. * Instantiates a Background Material in the given scene
  111054. * @param name The friendly name of the material
  111055. * @param scene The scene to add the material to
  111056. */
  111057. function BackgroundMaterial(name, scene) {
  111058. var _this = _super.call(this, name, scene) || this;
  111059. /**
  111060. * Key light Color (multiply against the environement texture)
  111061. */
  111062. _this.primaryColor = BABYLON.Color3.White();
  111063. _this._primaryColorShadowLevel = 0;
  111064. _this._primaryColorHighlightLevel = 0;
  111065. /**
  111066. * Reflection Texture used in the material.
  111067. * Should be author in a specific way for the best result (refer to the documentation).
  111068. */
  111069. _this.reflectionTexture = null;
  111070. /**
  111071. * Reflection Texture level of blur.
  111072. *
  111073. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  111074. * texture twice.
  111075. */
  111076. _this.reflectionBlur = 0;
  111077. /**
  111078. * Diffuse Texture used in the material.
  111079. * Should be author in a specific way for the best result (refer to the documentation).
  111080. */
  111081. _this.diffuseTexture = null;
  111082. _this._shadowLights = null;
  111083. /**
  111084. * Specify the list of lights casting shadow on the material.
  111085. * All scene shadow lights will be included if null.
  111086. */
  111087. _this.shadowLights = null;
  111088. /**
  111089. * Helps adjusting the shadow to a softer level if required.
  111090. * 0 means black shadows and 1 means no shadows.
  111091. */
  111092. _this.shadowLevel = 0;
  111093. /**
  111094. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  111095. * It is usually zero but might be interesting to modify according to your setup.
  111096. */
  111097. _this.sceneCenter = BABYLON.Vector3.Zero();
  111098. /**
  111099. * This helps specifying that the material is falling off to the sky box at grazing angle.
  111100. * This helps ensuring a nice transition when the camera goes under the ground.
  111101. */
  111102. _this.opacityFresnel = true;
  111103. /**
  111104. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  111105. * This helps adding a mirror texture on the ground.
  111106. */
  111107. _this.reflectionFresnel = false;
  111108. /**
  111109. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  111110. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  111111. */
  111112. _this.reflectionFalloffDistance = 0.0;
  111113. /**
  111114. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  111115. */
  111116. _this.reflectionAmount = 1.0;
  111117. /**
  111118. * This specifies the weight of the reflection at grazing angle.
  111119. */
  111120. _this.reflectionReflectance0 = 0.05;
  111121. /**
  111122. * This specifies the weight of the reflection at a perpendicular point of view.
  111123. */
  111124. _this.reflectionReflectance90 = 0.5;
  111125. /**
  111126. * Helps to directly use the maps channels instead of their level.
  111127. */
  111128. _this.useRGBColor = true;
  111129. /**
  111130. * This helps reducing the banding effect that could occur on the background.
  111131. */
  111132. _this.enableNoise = false;
  111133. _this._fovMultiplier = 1.0;
  111134. /**
  111135. * Enable the FOV adjustment feature controlled by fovMultiplier.
  111136. */
  111137. _this.useEquirectangularFOV = false;
  111138. _this._maxSimultaneousLights = 4;
  111139. /**
  111140. * Number of Simultaneous lights allowed on the material.
  111141. */
  111142. _this.maxSimultaneousLights = 4;
  111143. /**
  111144. * Keep track of the image processing observer to allow dispose and replace.
  111145. */
  111146. _this._imageProcessingObserver = null;
  111147. /**
  111148. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  111149. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  111150. */
  111151. _this.switchToBGR = false;
  111152. // Temp values kept as cache in the material.
  111153. _this._renderTargets = new BABYLON.SmartArray(16);
  111154. _this._reflectionControls = BABYLON.Vector4.Zero();
  111155. _this._white = BABYLON.Color3.White();
  111156. _this._primaryShadowColor = BABYLON.Color3.Black();
  111157. _this._primaryHighlightColor = BABYLON.Color3.Black();
  111158. // Setup the default processing configuration to the scene.
  111159. _this._attachImageProcessingConfiguration(null);
  111160. _this.getRenderTargetTextures = function () {
  111161. _this._renderTargets.reset();
  111162. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  111163. _this._renderTargets.push(_this._diffuseTexture);
  111164. }
  111165. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  111166. _this._renderTargets.push(_this._reflectionTexture);
  111167. }
  111168. return _this._renderTargets;
  111169. };
  111170. return _this;
  111171. }
  111172. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  111173. /**
  111174. * Experimental Internal Use Only.
  111175. *
  111176. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  111177. * This acts as a helper to set the primary color to a more "human friendly" value.
  111178. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  111179. * output color as close as possible from the chosen value.
  111180. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  111181. * part of lighting setup.)
  111182. */
  111183. get: function () {
  111184. return this.__perceptualColor;
  111185. },
  111186. set: function (value) {
  111187. this.__perceptualColor = value;
  111188. this._computePrimaryColorFromPerceptualColor();
  111189. this._markAllSubMeshesAsLightsDirty();
  111190. },
  111191. enumerable: true,
  111192. configurable: true
  111193. });
  111194. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  111195. /**
  111196. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  111197. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  111198. */
  111199. get: function () {
  111200. return this._primaryColorShadowLevel;
  111201. },
  111202. set: function (value) {
  111203. this._primaryColorShadowLevel = value;
  111204. this._computePrimaryColors();
  111205. this._markAllSubMeshesAsLightsDirty();
  111206. },
  111207. enumerable: true,
  111208. configurable: true
  111209. });
  111210. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  111211. /**
  111212. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  111213. * The primary color is used at the level chosen to define what the white area would look.
  111214. */
  111215. get: function () {
  111216. return this._primaryColorHighlightLevel;
  111217. },
  111218. set: function (value) {
  111219. this._primaryColorHighlightLevel = value;
  111220. this._computePrimaryColors();
  111221. this._markAllSubMeshesAsLightsDirty();
  111222. },
  111223. enumerable: true,
  111224. configurable: true
  111225. });
  111226. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  111227. /**
  111228. * Sets the reflection reflectance fresnel values according to the default standard
  111229. * empirically know to work well :-)
  111230. */
  111231. set: function (value) {
  111232. var reflectionWeight = value;
  111233. if (reflectionWeight < 0.5) {
  111234. reflectionWeight = reflectionWeight * 2.0;
  111235. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  111236. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  111237. }
  111238. else {
  111239. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  111240. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  111241. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  111242. }
  111243. },
  111244. enumerable: true,
  111245. configurable: true
  111246. });
  111247. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  111248. /**
  111249. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  111250. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  111251. * Recommended to be keep at 1.0 except for special cases.
  111252. */
  111253. get: function () {
  111254. return this._fovMultiplier;
  111255. },
  111256. set: function (value) {
  111257. if (isNaN(value)) {
  111258. value = 1.0;
  111259. }
  111260. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  111261. },
  111262. enumerable: true,
  111263. configurable: true
  111264. });
  111265. /**
  111266. * Attaches a new image processing configuration to the PBR Material.
  111267. * @param configuration (if null the scene configuration will be use)
  111268. */
  111269. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  111270. var _this = this;
  111271. if (configuration === this._imageProcessingConfiguration) {
  111272. return;
  111273. }
  111274. // Detaches observer.
  111275. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  111276. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  111277. }
  111278. // Pick the scene configuration if needed.
  111279. if (!configuration) {
  111280. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  111281. }
  111282. else {
  111283. this._imageProcessingConfiguration = configuration;
  111284. }
  111285. // Attaches observer.
  111286. if (this._imageProcessingConfiguration) {
  111287. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  111288. _this._computePrimaryColorFromPerceptualColor();
  111289. _this._markAllSubMeshesAsImageProcessingDirty();
  111290. });
  111291. }
  111292. };
  111293. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  111294. /**
  111295. * Gets the image processing configuration used either in this material.
  111296. */
  111297. get: function () {
  111298. return this._imageProcessingConfiguration;
  111299. },
  111300. /**
  111301. * Sets the Default image processing configuration used either in the this material.
  111302. *
  111303. * If sets to null, the scene one is in use.
  111304. */
  111305. set: function (value) {
  111306. this._attachImageProcessingConfiguration(value);
  111307. // Ensure the effect will be rebuilt.
  111308. this._markAllSubMeshesAsTexturesDirty();
  111309. },
  111310. enumerable: true,
  111311. configurable: true
  111312. });
  111313. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  111314. /**
  111315. * Gets wether the color curves effect is enabled.
  111316. */
  111317. get: function () {
  111318. return this.imageProcessingConfiguration.colorCurvesEnabled;
  111319. },
  111320. /**
  111321. * Sets wether the color curves effect is enabled.
  111322. */
  111323. set: function (value) {
  111324. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  111325. },
  111326. enumerable: true,
  111327. configurable: true
  111328. });
  111329. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  111330. /**
  111331. * Gets wether the color grading effect is enabled.
  111332. */
  111333. get: function () {
  111334. return this.imageProcessingConfiguration.colorGradingEnabled;
  111335. },
  111336. /**
  111337. * Gets wether the color grading effect is enabled.
  111338. */
  111339. set: function (value) {
  111340. this.imageProcessingConfiguration.colorGradingEnabled = value;
  111341. },
  111342. enumerable: true,
  111343. configurable: true
  111344. });
  111345. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  111346. /**
  111347. * Gets wether tonemapping is enabled or not.
  111348. */
  111349. get: function () {
  111350. return this._imageProcessingConfiguration.toneMappingEnabled;
  111351. },
  111352. /**
  111353. * Sets wether tonemapping is enabled or not
  111354. */
  111355. set: function (value) {
  111356. this._imageProcessingConfiguration.toneMappingEnabled = value;
  111357. },
  111358. enumerable: true,
  111359. configurable: true
  111360. });
  111361. ;
  111362. ;
  111363. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  111364. /**
  111365. * The camera exposure used on this material.
  111366. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  111367. * This corresponds to a photographic exposure.
  111368. */
  111369. get: function () {
  111370. return this._imageProcessingConfiguration.exposure;
  111371. },
  111372. /**
  111373. * The camera exposure used on this material.
  111374. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  111375. * This corresponds to a photographic exposure.
  111376. */
  111377. set: function (value) {
  111378. this._imageProcessingConfiguration.exposure = value;
  111379. },
  111380. enumerable: true,
  111381. configurable: true
  111382. });
  111383. ;
  111384. ;
  111385. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  111386. /**
  111387. * Gets The camera contrast used on this material.
  111388. */
  111389. get: function () {
  111390. return this._imageProcessingConfiguration.contrast;
  111391. },
  111392. /**
  111393. * Sets The camera contrast used on this material.
  111394. */
  111395. set: function (value) {
  111396. this._imageProcessingConfiguration.contrast = value;
  111397. },
  111398. enumerable: true,
  111399. configurable: true
  111400. });
  111401. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  111402. /**
  111403. * Gets the Color Grading 2D Lookup Texture.
  111404. */
  111405. get: function () {
  111406. return this._imageProcessingConfiguration.colorGradingTexture;
  111407. },
  111408. /**
  111409. * Sets the Color Grading 2D Lookup Texture.
  111410. */
  111411. set: function (value) {
  111412. this.imageProcessingConfiguration.colorGradingTexture = value;
  111413. },
  111414. enumerable: true,
  111415. configurable: true
  111416. });
  111417. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  111418. /**
  111419. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  111420. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  111421. * 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;
  111422. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  111423. */
  111424. get: function () {
  111425. return this.imageProcessingConfiguration.colorCurves;
  111426. },
  111427. /**
  111428. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  111429. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  111430. * 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;
  111431. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  111432. */
  111433. set: function (value) {
  111434. this.imageProcessingConfiguration.colorCurves = value;
  111435. },
  111436. enumerable: true,
  111437. configurable: true
  111438. });
  111439. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  111440. /**
  111441. * Gets a boolean indicating that current material needs to register RTT
  111442. */
  111443. get: function () {
  111444. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  111445. return true;
  111446. }
  111447. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  111448. return true;
  111449. }
  111450. return false;
  111451. },
  111452. enumerable: true,
  111453. configurable: true
  111454. });
  111455. /**
  111456. * The entire material has been created in order to prevent overdraw.
  111457. * @returns false
  111458. */
  111459. BackgroundMaterial.prototype.needAlphaTesting = function () {
  111460. return true;
  111461. };
  111462. /**
  111463. * The entire material has been created in order to prevent overdraw.
  111464. * @returns true if blending is enable
  111465. */
  111466. BackgroundMaterial.prototype.needAlphaBlending = function () {
  111467. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  111468. };
  111469. /**
  111470. * Checks wether the material is ready to be rendered for a given mesh.
  111471. * @param mesh The mesh to render
  111472. * @param subMesh The submesh to check against
  111473. * @param useInstances Specify wether or not the material is used with instances
  111474. * @returns true if all the dependencies are ready (Textures, Effects...)
  111475. */
  111476. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  111477. var _this = this;
  111478. if (useInstances === void 0) { useInstances = false; }
  111479. if (subMesh.effect && this.isFrozen) {
  111480. if (this._wasPreviouslyReady) {
  111481. return true;
  111482. }
  111483. }
  111484. if (!subMesh._materialDefines) {
  111485. subMesh._materialDefines = new BackgroundMaterialDefines();
  111486. }
  111487. var scene = this.getScene();
  111488. var defines = subMesh._materialDefines;
  111489. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  111490. if (defines._renderId === scene.getRenderId()) {
  111491. return true;
  111492. }
  111493. }
  111494. var engine = scene.getEngine();
  111495. // Lights
  111496. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  111497. defines._needNormals = true;
  111498. // Textures
  111499. if (defines._areTexturesDirty) {
  111500. defines._needUVs = false;
  111501. if (scene.texturesEnabled) {
  111502. if (scene.getEngine().getCaps().textureLOD) {
  111503. defines.TEXTURELODSUPPORT = true;
  111504. }
  111505. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111506. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  111507. return false;
  111508. }
  111509. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  111510. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  111511. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  111512. defines.OPACITYFRESNEL = this._opacityFresnel;
  111513. }
  111514. else {
  111515. defines.DIFFUSE = false;
  111516. defines.DIFFUSEHASALPHA = false;
  111517. defines.GAMMADIFFUSE = false;
  111518. defines.OPACITYFRESNEL = false;
  111519. }
  111520. var reflectionTexture = this._reflectionTexture;
  111521. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111522. if (!reflectionTexture.isReadyOrNotBlocking()) {
  111523. return false;
  111524. }
  111525. defines.REFLECTION = true;
  111526. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  111527. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  111528. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  111529. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  111530. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  111531. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  111532. defines.REFLECTIONBGR = this.switchToBGR;
  111533. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  111534. defines.INVERTCUBICMAP = true;
  111535. }
  111536. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  111537. switch (reflectionTexture.coordinatesMode) {
  111538. case BABYLON.Texture.EXPLICIT_MODE:
  111539. defines.REFLECTIONMAP_EXPLICIT = true;
  111540. break;
  111541. case BABYLON.Texture.PLANAR_MODE:
  111542. defines.REFLECTIONMAP_PLANAR = true;
  111543. break;
  111544. case BABYLON.Texture.PROJECTION_MODE:
  111545. defines.REFLECTIONMAP_PROJECTION = true;
  111546. break;
  111547. case BABYLON.Texture.SKYBOX_MODE:
  111548. defines.REFLECTIONMAP_SKYBOX = true;
  111549. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  111550. break;
  111551. case BABYLON.Texture.SPHERICAL_MODE:
  111552. defines.REFLECTIONMAP_SPHERICAL = true;
  111553. break;
  111554. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  111555. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  111556. break;
  111557. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  111558. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  111559. break;
  111560. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  111561. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  111562. break;
  111563. case BABYLON.Texture.CUBIC_MODE:
  111564. case BABYLON.Texture.INVCUBIC_MODE:
  111565. default:
  111566. defines.REFLECTIONMAP_CUBIC = true;
  111567. break;
  111568. }
  111569. if (this.reflectionFresnel) {
  111570. defines.REFLECTIONFRESNEL = true;
  111571. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  111572. this._reflectionControls.x = this.reflectionAmount;
  111573. this._reflectionControls.y = this.reflectionReflectance0;
  111574. this._reflectionControls.z = this.reflectionReflectance90;
  111575. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  111576. }
  111577. else {
  111578. defines.REFLECTIONFRESNEL = false;
  111579. defines.REFLECTIONFALLOFF = false;
  111580. }
  111581. }
  111582. else {
  111583. defines.REFLECTION = false;
  111584. defines.REFLECTIONFRESNEL = false;
  111585. defines.REFLECTIONFALLOFF = false;
  111586. defines.REFLECTIONBLUR = false;
  111587. defines.REFLECTIONMAP_3D = false;
  111588. defines.REFLECTIONMAP_SPHERICAL = false;
  111589. defines.REFLECTIONMAP_PLANAR = false;
  111590. defines.REFLECTIONMAP_CUBIC = false;
  111591. defines.REFLECTIONMAP_PROJECTION = false;
  111592. defines.REFLECTIONMAP_SKYBOX = false;
  111593. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  111594. defines.REFLECTIONMAP_EXPLICIT = false;
  111595. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  111596. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  111597. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  111598. defines.INVERTCUBICMAP = false;
  111599. defines.REFLECTIONMAP_OPPOSITEZ = false;
  111600. defines.LODINREFLECTIONALPHA = false;
  111601. defines.GAMMAREFLECTION = false;
  111602. defines.RGBDREFLECTION = false;
  111603. }
  111604. }
  111605. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  111606. defines.USERGBCOLOR = this._useRGBColor;
  111607. defines.NOISE = this._enableNoise;
  111608. }
  111609. if (defines._areLightsDirty) {
  111610. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  111611. }
  111612. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  111613. if (!this._imageProcessingConfiguration.isReady()) {
  111614. return false;
  111615. }
  111616. this._imageProcessingConfiguration.prepareDefines(defines);
  111617. }
  111618. // Misc.
  111619. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  111620. // Values that need to be evaluated on every frame
  111621. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  111622. // Attribs
  111623. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  111624. if (mesh) {
  111625. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  111626. mesh.createNormals(true);
  111627. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  111628. }
  111629. }
  111630. }
  111631. // Get correct effect
  111632. if (defines.isDirty) {
  111633. defines.markAsProcessed();
  111634. scene.resetCachedMaterial();
  111635. // Fallbacks
  111636. var fallbacks = new BABYLON.EffectFallbacks();
  111637. if (defines.FOG) {
  111638. fallbacks.addFallback(0, "FOG");
  111639. }
  111640. if (defines.POINTSIZE) {
  111641. fallbacks.addFallback(1, "POINTSIZE");
  111642. }
  111643. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  111644. if (defines.NUM_BONE_INFLUENCERS > 0) {
  111645. fallbacks.addCPUSkinningFallback(0, mesh);
  111646. }
  111647. //Attributes
  111648. var attribs = [BABYLON.VertexBuffer.PositionKind];
  111649. if (defines.NORMAL) {
  111650. attribs.push(BABYLON.VertexBuffer.NormalKind);
  111651. }
  111652. if (defines.UV1) {
  111653. attribs.push(BABYLON.VertexBuffer.UVKind);
  111654. }
  111655. if (defines.UV2) {
  111656. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  111657. }
  111658. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  111659. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  111660. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  111661. "vFogInfos", "vFogColor", "pointSize",
  111662. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  111663. "vPrimaryColor", "vPrimaryColorShadow",
  111664. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  111665. "shadowLevel", "alpha",
  111666. "vBackgroundCenter", "vReflectionControl",
  111667. "vDiffuseInfos", "diffuseMatrix",
  111668. ];
  111669. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  111670. var uniformBuffers = ["Material", "Scene"];
  111671. if (BABYLON.ImageProcessingConfiguration) {
  111672. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  111673. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  111674. }
  111675. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  111676. uniformsNames: uniforms,
  111677. uniformBuffersNames: uniformBuffers,
  111678. samplers: samplers,
  111679. defines: defines,
  111680. maxSimultaneousLights: this._maxSimultaneousLights
  111681. });
  111682. var onCompiled = function (effect) {
  111683. if (_this.onCompiled) {
  111684. _this.onCompiled(effect);
  111685. }
  111686. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  111687. };
  111688. var join = defines.toString();
  111689. subMesh.setEffect(scene.getEngine().createEffect("background", {
  111690. attributes: attribs,
  111691. uniformsNames: uniforms,
  111692. uniformBuffersNames: uniformBuffers,
  111693. samplers: samplers,
  111694. defines: join,
  111695. fallbacks: fallbacks,
  111696. onCompiled: onCompiled,
  111697. onError: this.onError,
  111698. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  111699. }, engine), defines);
  111700. this.buildUniformLayout();
  111701. }
  111702. if (!subMesh.effect || !subMesh.effect.isReady()) {
  111703. return false;
  111704. }
  111705. defines._renderId = scene.getRenderId();
  111706. this._wasPreviouslyReady = true;
  111707. return true;
  111708. };
  111709. /**
  111710. * Compute the primary color according to the chosen perceptual color.
  111711. */
  111712. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  111713. if (!this.__perceptualColor) {
  111714. return;
  111715. }
  111716. this._primaryColor.copyFrom(this.__perceptualColor);
  111717. // Revert gamma space.
  111718. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  111719. // Revert image processing configuration.
  111720. if (this._imageProcessingConfiguration) {
  111721. // Revert Exposure.
  111722. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  111723. }
  111724. this._computePrimaryColors();
  111725. };
  111726. /**
  111727. * Compute the highlights and shadow colors according to their chosen levels.
  111728. */
  111729. BackgroundMaterial.prototype._computePrimaryColors = function () {
  111730. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  111731. return;
  111732. }
  111733. // Find the highlight color based on the configuration.
  111734. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  111735. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  111736. // Find the shadow color based on the configuration.
  111737. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  111738. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  111739. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  111740. };
  111741. /**
  111742. * Build the uniform buffer used in the material.
  111743. */
  111744. BackgroundMaterial.prototype.buildUniformLayout = function () {
  111745. // Order is important !
  111746. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  111747. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  111748. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  111749. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  111750. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  111751. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  111752. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  111753. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  111754. this._uniformBuffer.addUniform("pointSize", 1);
  111755. this._uniformBuffer.addUniform("shadowLevel", 1);
  111756. this._uniformBuffer.addUniform("alpha", 1);
  111757. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  111758. this._uniformBuffer.addUniform("vReflectionControl", 4);
  111759. this._uniformBuffer.create();
  111760. };
  111761. /**
  111762. * Unbind the material.
  111763. */
  111764. BackgroundMaterial.prototype.unbind = function () {
  111765. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  111766. this._uniformBuffer.setTexture("diffuseSampler", null);
  111767. }
  111768. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  111769. this._uniformBuffer.setTexture("reflectionSampler", null);
  111770. }
  111771. _super.prototype.unbind.call(this);
  111772. };
  111773. /**
  111774. * Bind only the world matrix to the material.
  111775. * @param world The world matrix to bind.
  111776. */
  111777. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  111778. this._activeEffect.setMatrix("world", world);
  111779. };
  111780. /**
  111781. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  111782. * @param world The world matrix to bind.
  111783. * @param subMesh The submesh to bind for.
  111784. */
  111785. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  111786. var scene = this.getScene();
  111787. var defines = subMesh._materialDefines;
  111788. if (!defines) {
  111789. return;
  111790. }
  111791. var effect = subMesh.effect;
  111792. if (!effect) {
  111793. return;
  111794. }
  111795. this._activeEffect = effect;
  111796. // Matrices
  111797. this.bindOnlyWorldMatrix(world);
  111798. // Bones
  111799. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  111800. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  111801. if (mustRebind) {
  111802. this._uniformBuffer.bindToEffect(effect, "Material");
  111803. this.bindViewProjection(effect);
  111804. var reflectionTexture = this._reflectionTexture;
  111805. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  111806. // Texture uniforms
  111807. if (scene.texturesEnabled) {
  111808. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111809. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  111810. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  111811. }
  111812. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111813. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  111814. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  111815. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  111816. }
  111817. }
  111818. if (this.shadowLevel > 0) {
  111819. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  111820. }
  111821. this._uniformBuffer.updateFloat("alpha", this.alpha);
  111822. // Point size
  111823. if (this.pointsCloud) {
  111824. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  111825. }
  111826. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  111827. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  111828. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  111829. }
  111830. else {
  111831. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  111832. }
  111833. }
  111834. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  111835. // Textures
  111836. if (scene.texturesEnabled) {
  111837. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111838. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  111839. }
  111840. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111841. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  111842. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111843. }
  111844. else if (!defines.REFLECTIONBLUR) {
  111845. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111846. }
  111847. else {
  111848. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  111849. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  111850. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  111851. }
  111852. if (defines.REFLECTIONFRESNEL) {
  111853. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  111854. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  111855. }
  111856. }
  111857. }
  111858. // Clip plane
  111859. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  111860. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  111861. }
  111862. if (mustRebind || !this.isFrozen) {
  111863. if (scene.lightsEnabled) {
  111864. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  111865. }
  111866. // View
  111867. this.bindView(effect);
  111868. // Fog
  111869. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  111870. // image processing
  111871. if (this._imageProcessingConfiguration) {
  111872. this._imageProcessingConfiguration.bind(this._activeEffect);
  111873. }
  111874. }
  111875. this._uniformBuffer.update();
  111876. this._afterBind(mesh, this._activeEffect);
  111877. };
  111878. /**
  111879. * Dispose the material.
  111880. * @param forceDisposeEffect Force disposal of the associated effect.
  111881. * @param forceDisposeTextures Force disposal of the associated textures.
  111882. */
  111883. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  111884. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  111885. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  111886. if (forceDisposeTextures) {
  111887. if (this.diffuseTexture) {
  111888. this.diffuseTexture.dispose();
  111889. }
  111890. if (this.reflectionTexture) {
  111891. this.reflectionTexture.dispose();
  111892. }
  111893. }
  111894. this._renderTargets.dispose();
  111895. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  111896. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  111897. }
  111898. _super.prototype.dispose.call(this, forceDisposeEffect);
  111899. };
  111900. /**
  111901. * Clones the material.
  111902. * @param name The cloned name.
  111903. * @returns The cloned material.
  111904. */
  111905. BackgroundMaterial.prototype.clone = function (name) {
  111906. var _this = this;
  111907. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  111908. };
  111909. /**
  111910. * Serializes the current material to its JSON representation.
  111911. * @returns The JSON representation.
  111912. */
  111913. BackgroundMaterial.prototype.serialize = function () {
  111914. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  111915. serializationObject.customType = "BABYLON.BackgroundMaterial";
  111916. return serializationObject;
  111917. };
  111918. /**
  111919. * Gets the class name of the material
  111920. * @returns "BackgroundMaterial"
  111921. */
  111922. BackgroundMaterial.prototype.getClassName = function () {
  111923. return "BackgroundMaterial";
  111924. };
  111925. /**
  111926. * Parse a JSON input to create back a background material.
  111927. * @param source The JSON data to parse
  111928. * @param scene The scene to create the parsed material in
  111929. * @param rootUrl The root url of the assets the material depends upon
  111930. * @returns the instantiated BackgroundMaterial.
  111931. */
  111932. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  111933. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  111934. };
  111935. /**
  111936. * Standard reflectance value at parallel view angle.
  111937. */
  111938. BackgroundMaterial.StandardReflectance0 = 0.05;
  111939. /**
  111940. * Standard reflectance value at grazing angle.
  111941. */
  111942. BackgroundMaterial.StandardReflectance90 = 0.5;
  111943. __decorate([
  111944. BABYLON.serializeAsColor3()
  111945. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  111946. __decorate([
  111947. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111948. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  111949. __decorate([
  111950. BABYLON.serializeAsColor3()
  111951. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  111952. __decorate([
  111953. BABYLON.serialize()
  111954. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  111955. __decorate([
  111956. BABYLON.serialize()
  111957. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  111958. __decorate([
  111959. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111960. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  111961. __decorate([
  111962. BABYLON.serializeAsTexture()
  111963. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  111964. __decorate([
  111965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111966. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  111967. __decorate([
  111968. BABYLON.serialize()
  111969. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  111970. __decorate([
  111971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111972. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  111973. __decorate([
  111974. BABYLON.serializeAsTexture()
  111975. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  111976. __decorate([
  111977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111978. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  111979. __decorate([
  111980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111981. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  111982. __decorate([
  111983. BABYLON.serialize()
  111984. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  111985. __decorate([
  111986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111987. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  111988. __decorate([
  111989. BABYLON.serializeAsVector3()
  111990. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  111991. __decorate([
  111992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111993. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  111994. __decorate([
  111995. BABYLON.serialize()
  111996. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  111997. __decorate([
  111998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111999. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  112000. __decorate([
  112001. BABYLON.serialize()
  112002. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  112003. __decorate([
  112004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112005. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  112006. __decorate([
  112007. BABYLON.serialize()
  112008. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  112009. __decorate([
  112010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112011. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  112012. __decorate([
  112013. BABYLON.serialize()
  112014. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  112015. __decorate([
  112016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112017. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  112018. __decorate([
  112019. BABYLON.serialize()
  112020. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  112021. __decorate([
  112022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112023. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  112024. __decorate([
  112025. BABYLON.serialize()
  112026. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  112027. __decorate([
  112028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112029. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  112030. __decorate([
  112031. BABYLON.serialize()
  112032. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  112033. __decorate([
  112034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112035. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  112036. __decorate([
  112037. BABYLON.serialize()
  112038. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  112039. __decorate([
  112040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112041. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  112042. __decorate([
  112043. BABYLON.serialize()
  112044. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  112045. __decorate([
  112046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112047. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  112048. __decorate([
  112049. BABYLON.serializeAsImageProcessingConfiguration()
  112050. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  112051. return BackgroundMaterial;
  112052. }(BABYLON.PushMaterial));
  112053. BABYLON.BackgroundMaterial = BackgroundMaterial;
  112054. })(BABYLON || (BABYLON = {}));
  112055. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  112056. var __assign = (this && this.__assign) || function () {
  112057. __assign = Object.assign || function(t) {
  112058. for (var s, i = 1, n = arguments.length; i < n; i++) {
  112059. s = arguments[i];
  112060. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  112061. t[p] = s[p];
  112062. }
  112063. return t;
  112064. };
  112065. return __assign.apply(this, arguments);
  112066. };
  112067. var BABYLON;
  112068. (function (BABYLON) {
  112069. /**
  112070. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  112071. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  112072. * It also helps with the default setup of your imageProcessing configuration.
  112073. */
  112074. var EnvironmentHelper = /** @class */ (function () {
  112075. /**
  112076. * constructor
  112077. * @param options
  112078. * @param scene The scene to add the material to
  112079. */
  112080. function EnvironmentHelper(options, scene) {
  112081. var _this = this;
  112082. this._errorHandler = function (message, exception) {
  112083. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  112084. };
  112085. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  112086. this._scene = scene;
  112087. this.onErrorObservable = new BABYLON.Observable();
  112088. this._setupBackground();
  112089. this._setupImageProcessing();
  112090. }
  112091. /**
  112092. * Creates the default options for the helper.
  112093. */
  112094. EnvironmentHelper._getDefaultOptions = function () {
  112095. return {
  112096. createGround: true,
  112097. groundSize: 15,
  112098. groundTexture: this._groundTextureCDNUrl,
  112099. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  112100. groundOpacity: 0.9,
  112101. enableGroundShadow: true,
  112102. groundShadowLevel: 0.5,
  112103. enableGroundMirror: false,
  112104. groundMirrorSizeRatio: 0.3,
  112105. groundMirrorBlurKernel: 64,
  112106. groundMirrorAmount: 1,
  112107. groundMirrorFresnelWeight: 1,
  112108. groundMirrorFallOffDistance: 0,
  112109. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  112110. groundYBias: 0.00001,
  112111. createSkybox: true,
  112112. skyboxSize: 20,
  112113. skyboxTexture: this._skyboxTextureCDNUrl,
  112114. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  112115. backgroundYRotation: 0,
  112116. sizeAuto: true,
  112117. rootPosition: BABYLON.Vector3.Zero(),
  112118. setupImageProcessing: true,
  112119. environmentTexture: this._environmentTextureCDNUrl,
  112120. cameraExposure: 0.8,
  112121. cameraContrast: 1.2,
  112122. toneMappingEnabled: true,
  112123. };
  112124. };
  112125. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  112126. /**
  112127. * Gets the root mesh created by the helper.
  112128. */
  112129. get: function () {
  112130. return this._rootMesh;
  112131. },
  112132. enumerable: true,
  112133. configurable: true
  112134. });
  112135. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  112136. /**
  112137. * Gets the skybox created by the helper.
  112138. */
  112139. get: function () {
  112140. return this._skybox;
  112141. },
  112142. enumerable: true,
  112143. configurable: true
  112144. });
  112145. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  112146. /**
  112147. * Gets the skybox texture created by the helper.
  112148. */
  112149. get: function () {
  112150. return this._skyboxTexture;
  112151. },
  112152. enumerable: true,
  112153. configurable: true
  112154. });
  112155. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  112156. /**
  112157. * Gets the skybox material created by the helper.
  112158. */
  112159. get: function () {
  112160. return this._skyboxMaterial;
  112161. },
  112162. enumerable: true,
  112163. configurable: true
  112164. });
  112165. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  112166. /**
  112167. * Gets the ground mesh created by the helper.
  112168. */
  112169. get: function () {
  112170. return this._ground;
  112171. },
  112172. enumerable: true,
  112173. configurable: true
  112174. });
  112175. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  112176. /**
  112177. * Gets the ground texture created by the helper.
  112178. */
  112179. get: function () {
  112180. return this._groundTexture;
  112181. },
  112182. enumerable: true,
  112183. configurable: true
  112184. });
  112185. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  112186. /**
  112187. * Gets the ground mirror created by the helper.
  112188. */
  112189. get: function () {
  112190. return this._groundMirror;
  112191. },
  112192. enumerable: true,
  112193. configurable: true
  112194. });
  112195. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  112196. /**
  112197. * Gets the ground mirror render list to helps pushing the meshes
  112198. * you wish in the ground reflection.
  112199. */
  112200. get: function () {
  112201. if (this._groundMirror) {
  112202. return this._groundMirror.renderList;
  112203. }
  112204. return null;
  112205. },
  112206. enumerable: true,
  112207. configurable: true
  112208. });
  112209. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  112210. /**
  112211. * Gets the ground material created by the helper.
  112212. */
  112213. get: function () {
  112214. return this._groundMaterial;
  112215. },
  112216. enumerable: true,
  112217. configurable: true
  112218. });
  112219. /**
  112220. * Updates the background according to the new options
  112221. * @param options
  112222. */
  112223. EnvironmentHelper.prototype.updateOptions = function (options) {
  112224. var newOptions = __assign({}, this._options, options);
  112225. if (this._ground && !newOptions.createGround) {
  112226. this._ground.dispose();
  112227. this._ground = null;
  112228. }
  112229. if (this._groundMaterial && !newOptions.createGround) {
  112230. this._groundMaterial.dispose();
  112231. this._groundMaterial = null;
  112232. }
  112233. if (this._groundTexture) {
  112234. if (this._options.groundTexture != newOptions.groundTexture) {
  112235. this._groundTexture.dispose();
  112236. this._groundTexture = null;
  112237. }
  112238. }
  112239. if (this._skybox && !newOptions.createSkybox) {
  112240. this._skybox.dispose();
  112241. this._skybox = null;
  112242. }
  112243. if (this._skyboxMaterial && !newOptions.createSkybox) {
  112244. this._skyboxMaterial.dispose();
  112245. this._skyboxMaterial = null;
  112246. }
  112247. if (this._skyboxTexture) {
  112248. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  112249. this._skyboxTexture.dispose();
  112250. this._skyboxTexture = null;
  112251. }
  112252. }
  112253. if (this._groundMirror && !newOptions.enableGroundMirror) {
  112254. this._groundMirror.dispose();
  112255. this._groundMirror = null;
  112256. }
  112257. if (this._scene.environmentTexture) {
  112258. if (this._options.environmentTexture != newOptions.environmentTexture) {
  112259. this._scene.environmentTexture.dispose();
  112260. }
  112261. }
  112262. this._options = newOptions;
  112263. this._setupBackground();
  112264. this._setupImageProcessing();
  112265. };
  112266. /**
  112267. * Sets the primary color of all the available elements.
  112268. * @param color the main color to affect to the ground and the background
  112269. */
  112270. EnvironmentHelper.prototype.setMainColor = function (color) {
  112271. if (this.groundMaterial) {
  112272. this.groundMaterial.primaryColor = color;
  112273. }
  112274. if (this.skyboxMaterial) {
  112275. this.skyboxMaterial.primaryColor = color;
  112276. }
  112277. if (this.groundMirror) {
  112278. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  112279. }
  112280. };
  112281. /**
  112282. * Setup the image processing according to the specified options.
  112283. */
  112284. EnvironmentHelper.prototype._setupImageProcessing = function () {
  112285. if (this._options.setupImageProcessing) {
  112286. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  112287. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  112288. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  112289. this._setupEnvironmentTexture();
  112290. }
  112291. };
  112292. /**
  112293. * Setup the environment texture according to the specified options.
  112294. */
  112295. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  112296. if (this._scene.environmentTexture) {
  112297. return;
  112298. }
  112299. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  112300. this._scene.environmentTexture = this._options.environmentTexture;
  112301. return;
  112302. }
  112303. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  112304. this._scene.environmentTexture = environmentTexture;
  112305. };
  112306. /**
  112307. * Setup the background according to the specified options.
  112308. */
  112309. EnvironmentHelper.prototype._setupBackground = function () {
  112310. if (!this._rootMesh) {
  112311. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  112312. }
  112313. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  112314. var sceneSize = this._getSceneSize();
  112315. if (this._options.createGround) {
  112316. this._setupGround(sceneSize);
  112317. this._setupGroundMaterial();
  112318. this._setupGroundDiffuseTexture();
  112319. if (this._options.enableGroundMirror) {
  112320. this._setupGroundMirrorTexture(sceneSize);
  112321. }
  112322. this._setupMirrorInGroundMaterial();
  112323. }
  112324. if (this._options.createSkybox) {
  112325. this._setupSkybox(sceneSize);
  112326. this._setupSkyboxMaterial();
  112327. this._setupSkyboxReflectionTexture();
  112328. }
  112329. this._rootMesh.position.x = sceneSize.rootPosition.x;
  112330. this._rootMesh.position.z = sceneSize.rootPosition.z;
  112331. this._rootMesh.position.y = sceneSize.rootPosition.y;
  112332. };
  112333. /**
  112334. * Get the scene sizes according to the setup.
  112335. */
  112336. EnvironmentHelper.prototype._getSceneSize = function () {
  112337. var _this = this;
  112338. var groundSize = this._options.groundSize;
  112339. var skyboxSize = this._options.skyboxSize;
  112340. var rootPosition = this._options.rootPosition;
  112341. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  112342. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  112343. }
  112344. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  112345. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  112346. });
  112347. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  112348. if (this._options.sizeAuto) {
  112349. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  112350. this._scene.activeCamera.upperRadiusLimit) {
  112351. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  112352. skyboxSize = groundSize;
  112353. }
  112354. var sceneDiagonalLenght = sceneDiagonal.length();
  112355. if (sceneDiagonalLenght > groundSize) {
  112356. groundSize = sceneDiagonalLenght * 2;
  112357. skyboxSize = groundSize;
  112358. }
  112359. // 10 % bigger.
  112360. groundSize *= 1.1;
  112361. skyboxSize *= 1.5;
  112362. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  112363. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  112364. }
  112365. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  112366. };
  112367. /**
  112368. * Setup the ground according to the specified options.
  112369. */
  112370. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  112371. var _this = this;
  112372. if (!this._ground || this._ground.isDisposed()) {
  112373. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  112374. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  112375. this._ground.parent = this._rootMesh;
  112376. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  112377. }
  112378. this._ground.receiveShadows = this._options.enableGroundShadow;
  112379. };
  112380. /**
  112381. * Setup the ground material according to the specified options.
  112382. */
  112383. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  112384. if (!this._groundMaterial) {
  112385. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  112386. }
  112387. this._groundMaterial.alpha = this._options.groundOpacity;
  112388. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  112389. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  112390. this._groundMaterial.primaryColor = this._options.groundColor;
  112391. this._groundMaterial.useRGBColor = false;
  112392. this._groundMaterial.enableNoise = true;
  112393. if (this._ground) {
  112394. this._ground.material = this._groundMaterial;
  112395. }
  112396. };
  112397. /**
  112398. * Setup the ground diffuse texture according to the specified options.
  112399. */
  112400. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  112401. if (!this._groundMaterial) {
  112402. return;
  112403. }
  112404. if (this._groundTexture) {
  112405. return;
  112406. }
  112407. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  112408. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  112409. return;
  112410. }
  112411. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  112412. diffuseTexture.gammaSpace = false;
  112413. diffuseTexture.hasAlpha = true;
  112414. this._groundMaterial.diffuseTexture = diffuseTexture;
  112415. };
  112416. /**
  112417. * Setup the ground mirror texture according to the specified options.
  112418. */
  112419. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  112420. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112421. if (!this._groundMirror) {
  112422. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  112423. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  112424. this._groundMirror.anisotropicFilteringLevel = 1;
  112425. this._groundMirror.wrapU = wrapping;
  112426. this._groundMirror.wrapV = wrapping;
  112427. this._groundMirror.gammaSpace = false;
  112428. if (this._groundMirror.renderList) {
  112429. for (var i = 0; i < this._scene.meshes.length; i++) {
  112430. var mesh = this._scene.meshes[i];
  112431. if (mesh !== this._ground &&
  112432. mesh !== this._skybox &&
  112433. mesh !== this._rootMesh) {
  112434. this._groundMirror.renderList.push(mesh);
  112435. }
  112436. }
  112437. }
  112438. }
  112439. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  112440. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  112441. };
  112442. /**
  112443. * Setup the ground to receive the mirror texture.
  112444. */
  112445. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  112446. if (this._groundMaterial) {
  112447. this._groundMaterial.reflectionTexture = this._groundMirror;
  112448. this._groundMaterial.reflectionFresnel = true;
  112449. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  112450. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  112451. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  112452. }
  112453. };
  112454. /**
  112455. * Setup the skybox according to the specified options.
  112456. */
  112457. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  112458. var _this = this;
  112459. if (!this._skybox || this._skybox.isDisposed()) {
  112460. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  112461. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  112462. }
  112463. this._skybox.parent = this._rootMesh;
  112464. };
  112465. /**
  112466. * Setup the skybox material according to the specified options.
  112467. */
  112468. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  112469. if (!this._skybox) {
  112470. return;
  112471. }
  112472. if (!this._skyboxMaterial) {
  112473. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  112474. }
  112475. this._skyboxMaterial.useRGBColor = false;
  112476. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  112477. this._skyboxMaterial.enableNoise = true;
  112478. this._skybox.material = this._skyboxMaterial;
  112479. };
  112480. /**
  112481. * Setup the skybox reflection texture according to the specified options.
  112482. */
  112483. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  112484. if (!this._skyboxMaterial) {
  112485. return;
  112486. }
  112487. if (this._skyboxTexture) {
  112488. return;
  112489. }
  112490. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  112491. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  112492. return;
  112493. }
  112494. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  112495. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112496. this._skyboxTexture.gammaSpace = false;
  112497. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  112498. };
  112499. /**
  112500. * Dispose all the elements created by the Helper.
  112501. */
  112502. EnvironmentHelper.prototype.dispose = function () {
  112503. if (this._groundMaterial) {
  112504. this._groundMaterial.dispose(true, true);
  112505. }
  112506. if (this._skyboxMaterial) {
  112507. this._skyboxMaterial.dispose(true, true);
  112508. }
  112509. this._rootMesh.dispose(false);
  112510. };
  112511. /**
  112512. * Default ground texture URL.
  112513. */
  112514. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  112515. /**
  112516. * Default skybox texture URL.
  112517. */
  112518. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  112519. /**
  112520. * Default environment texture URL.
  112521. */
  112522. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  112523. return EnvironmentHelper;
  112524. }());
  112525. BABYLON.EnvironmentHelper = EnvironmentHelper;
  112526. })(BABYLON || (BABYLON = {}));
  112527. //# sourceMappingURL=babylon.environmentHelper.js.map
  112528. var BABYLON;
  112529. (function (BABYLON) {
  112530. /** Internal class used to store shapes for emitters */
  112531. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  112532. function ParticleSystemSetEmitterCreationOptions() {
  112533. }
  112534. return ParticleSystemSetEmitterCreationOptions;
  112535. }());
  112536. /**
  112537. * Represents a set of particle systems working together to create a specific effect
  112538. */
  112539. var ParticleSystemSet = /** @class */ (function () {
  112540. function ParticleSystemSet() {
  112541. /**
  112542. * Gets the particle system list
  112543. */
  112544. this.systems = new Array();
  112545. }
  112546. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  112547. /**
  112548. * Gets the emitter node used with this set
  112549. */
  112550. get: function () {
  112551. return this._emitterNode;
  112552. },
  112553. enumerable: true,
  112554. configurable: true
  112555. });
  112556. /**
  112557. * Creates a new emitter mesh as a sphere
  112558. * @param options defines the options used to create the sphere
  112559. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  112560. * @param scene defines the hosting scene
  112561. */
  112562. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  112563. if (this._emitterNode) {
  112564. this._emitterNode.dispose();
  112565. }
  112566. this._emitterCreationOptions = {
  112567. kind: "Sphere",
  112568. options: options,
  112569. renderingGroupId: renderingGroupId
  112570. };
  112571. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  112572. emitterMesh.renderingGroupId = renderingGroupId;
  112573. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  112574. material.emissiveColor = options.color;
  112575. emitterMesh.material = material;
  112576. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  112577. var system = _a[_i];
  112578. system.emitter = emitterMesh;
  112579. }
  112580. this._emitterNode = emitterMesh;
  112581. };
  112582. /**
  112583. * Starts all particle systems of the set
  112584. * @param emitter defines an optional mesh to use as emitter for the particle systems
  112585. */
  112586. ParticleSystemSet.prototype.start = function (emitter) {
  112587. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  112588. var system = _a[_i];
  112589. if (emitter) {
  112590. system.emitter = emitter;
  112591. }
  112592. system.start();
  112593. }
  112594. };
  112595. /**
  112596. * Release all associated resources
  112597. */
  112598. ParticleSystemSet.prototype.dispose = function () {
  112599. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  112600. var system = _a[_i];
  112601. system.dispose();
  112602. }
  112603. this.systems = [];
  112604. if (this._emitterNode) {
  112605. this._emitterNode.dispose();
  112606. this._emitterNode = null;
  112607. }
  112608. };
  112609. /**
  112610. * Serialize the set into a JSON compatible object
  112611. * @returns a JSON compatible representation of the set
  112612. */
  112613. ParticleSystemSet.prototype.serialize = function () {
  112614. var result = {};
  112615. result.systems = [];
  112616. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  112617. var system = _a[_i];
  112618. result.systems.push(system.serialize());
  112619. }
  112620. if (this._emitterNode) {
  112621. result.emitter = this._emitterCreationOptions;
  112622. }
  112623. return result;
  112624. };
  112625. /**
  112626. * Parse a new ParticleSystemSet from a serialized source
  112627. * @param data defines a JSON compatible representation of the set
  112628. * @param scene defines the hosting scene
  112629. * @param gpu defines if we want GPU particles or CPU particles
  112630. * @returns a new ParticleSystemSet
  112631. */
  112632. ParticleSystemSet.Parse = function (data, scene, gpu) {
  112633. if (gpu === void 0) { gpu = false; }
  112634. var result = new ParticleSystemSet();
  112635. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  112636. scene = scene || BABYLON.Engine.LastCreatedScene;
  112637. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  112638. var system = _a[_i];
  112639. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  112640. }
  112641. if (data.emitter) {
  112642. var options = data.emitter.options;
  112643. switch (data.emitter.kind) {
  112644. case "Sphere":
  112645. result.setEmitterAsSphere({
  112646. diameter: options.diameter,
  112647. segments: options.segments,
  112648. color: BABYLON.Color3.FromArray(options.color)
  112649. }, data.emitter.renderingGroupId, scene);
  112650. break;
  112651. }
  112652. }
  112653. return result;
  112654. };
  112655. return ParticleSystemSet;
  112656. }());
  112657. BABYLON.ParticleSystemSet = ParticleSystemSet;
  112658. })(BABYLON || (BABYLON = {}));
  112659. //# sourceMappingURL=babylon.particleSystemSet.js.map
  112660. var BABYLON;
  112661. (function (BABYLON) {
  112662. /**
  112663. * This class is made for on one-liner static method to help creating particle system set.
  112664. */
  112665. var ParticleHelper = /** @class */ (function () {
  112666. function ParticleHelper() {
  112667. }
  112668. /**
  112669. * Create a default particle system that you can tweak
  112670. * @param emitter defines the emitter to use
  112671. * @param capacity defines the system capacity (default is 500 particles)
  112672. * @param scene defines the hosting scene
  112673. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  112674. * @returns the new Particle system
  112675. */
  112676. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  112677. if (capacity === void 0) { capacity = 500; }
  112678. if (useGPU === void 0) { useGPU = false; }
  112679. var system;
  112680. if (useGPU) {
  112681. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  112682. }
  112683. else {
  112684. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  112685. }
  112686. system.emitter = emitter;
  112687. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  112688. system.createConeEmitter(0.1, Math.PI / 4);
  112689. // Particle color
  112690. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112691. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112692. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  112693. // Particle Size
  112694. system.minSize = 0.1;
  112695. system.maxSize = 0.1;
  112696. // Emission speed
  112697. system.minEmitPower = 2;
  112698. system.maxEmitPower = 2;
  112699. // Update speed
  112700. system.updateSpeed = 1 / 60;
  112701. system.emitRate = 30;
  112702. return system;
  112703. };
  112704. /**
  112705. * This is the main static method (one-liner) of this helper to create different particle systems
  112706. * @param type This string represents the type to the particle system to create
  112707. * @param scene The scene where the particle system should live
  112708. * @param gpu If the system will use gpu
  112709. * @returns the ParticleSystemSet created
  112710. */
  112711. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  112712. if (gpu === void 0) { gpu = false; }
  112713. if (!scene) {
  112714. scene = BABYLON.Engine.LastCreatedScene;
  112715. ;
  112716. }
  112717. var token = {};
  112718. scene._addPendingData(token);
  112719. return new Promise(function (resolve, reject) {
  112720. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  112721. scene._removePendingData(token);
  112722. return reject("Particle system with GPU is not supported.");
  112723. }
  112724. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  112725. scene._removePendingData(token);
  112726. var newData = JSON.parse(data.toString());
  112727. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  112728. }, undefined, undefined, undefined, function (req, exception) {
  112729. scene._removePendingData(token);
  112730. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  112731. });
  112732. });
  112733. };
  112734. /**
  112735. * Static function used to export a particle system to a ParticleSystemSet variable.
  112736. * Please note that the emitter shape is not exported
  112737. * @param system defines the particle systems to export
  112738. */
  112739. ParticleHelper.ExportSet = function (systems) {
  112740. var set = new BABYLON.ParticleSystemSet();
  112741. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  112742. var system = systems_1[_i];
  112743. set.systems.push(system);
  112744. }
  112745. return set;
  112746. };
  112747. /**
  112748. * Gets or sets base Assets URL
  112749. */
  112750. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  112751. return ParticleHelper;
  112752. }());
  112753. BABYLON.ParticleHelper = ParticleHelper;
  112754. })(BABYLON || (BABYLON = {}));
  112755. //# sourceMappingURL=babylon.particleHelper.js.map
  112756. var BABYLON;
  112757. (function (BABYLON) {
  112758. /**
  112759. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  112760. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  112761. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  112762. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112763. */
  112764. var VideoDome = /** @class */ (function (_super) {
  112765. __extends(VideoDome, _super);
  112766. /**
  112767. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  112768. * @param name Element's name, child elements will append suffixes for their own names.
  112769. * @param urlsOrVideo defines the url(s) or the video element to use
  112770. * @param options An object containing optional or exposed sub element properties
  112771. */
  112772. function VideoDome(name, urlsOrVideo, options, scene) {
  112773. var _this = _super.call(this, name, scene) || this;
  112774. _this._useDirectMapping = false;
  112775. // set defaults and manage values
  112776. name = name || "videoDome";
  112777. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112778. options.clickToPlay = Boolean(options.clickToPlay);
  112779. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  112780. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  112781. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112782. if (options.useDirectMapping === undefined) {
  112783. _this._useDirectMapping = true;
  112784. }
  112785. else {
  112786. _this._useDirectMapping = options.useDirectMapping;
  112787. }
  112788. _this._setReady(false);
  112789. // create
  112790. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  112791. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112792. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  112793. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112794. texture.onLoadObservable.addOnce(function () {
  112795. _this._setReady(true);
  112796. });
  112797. // configure material
  112798. material.useEquirectangularFOV = true;
  112799. material.fovMultiplier = 1.0;
  112800. material.opacityFresnel = false;
  112801. if (_this._useDirectMapping) {
  112802. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112803. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112804. material.diffuseTexture = texture;
  112805. }
  112806. else {
  112807. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112808. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112809. material.reflectionTexture = texture;
  112810. }
  112811. // configure mesh
  112812. _this._mesh.material = material;
  112813. _this._mesh.parent = _this;
  112814. // optional configuration
  112815. if (options.clickToPlay) {
  112816. scene.onPointerUp = function () {
  112817. _this._videoTexture.video.play();
  112818. };
  112819. }
  112820. return _this;
  112821. }
  112822. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  112823. /**
  112824. * Gets the video texture being displayed on the sphere
  112825. */
  112826. get: function () {
  112827. return this._videoTexture;
  112828. },
  112829. enumerable: true,
  112830. configurable: true
  112831. });
  112832. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  112833. /**
  112834. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112835. * Also see the options.resolution property.
  112836. */
  112837. get: function () {
  112838. return this._material.fovMultiplier;
  112839. },
  112840. set: function (value) {
  112841. this._material.fovMultiplier = value;
  112842. },
  112843. enumerable: true,
  112844. configurable: true
  112845. });
  112846. /**
  112847. * Releases resources associated with this node.
  112848. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112849. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112850. */
  112851. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112852. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112853. this._videoTexture.dispose();
  112854. this._mesh.dispose();
  112855. this._material.dispose();
  112856. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112857. };
  112858. return VideoDome;
  112859. }(BABYLON.TransformNode));
  112860. BABYLON.VideoDome = VideoDome;
  112861. })(BABYLON || (BABYLON = {}));
  112862. //# sourceMappingURL=babylon.videoDome.js.map
  112863. var BABYLON;
  112864. (function (BABYLON) {
  112865. /**
  112866. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  112867. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  112868. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  112869. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112870. */
  112871. var PhotoDome = /** @class */ (function (_super) {
  112872. __extends(PhotoDome, _super);
  112873. /**
  112874. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  112875. * @param name Element's name, child elements will append suffixes for their own names.
  112876. * @param urlsOfPhoto defines the url of the photo to display
  112877. * @param options defines an object containing optional or exposed sub element properties
  112878. * @param onError defines a callback called when an error occured while loading the texture
  112879. */
  112880. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  112881. if (onError === void 0) { onError = null; }
  112882. var _this = _super.call(this, name, scene) || this;
  112883. _this._useDirectMapping = false;
  112884. /**
  112885. * Observable raised when an error occured while loading the 360 image
  112886. */
  112887. _this.onLoadErrorObservable = new BABYLON.Observable();
  112888. // set defaults and manage values
  112889. name = name || "photoDome";
  112890. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112891. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112892. if (options.useDirectMapping === undefined) {
  112893. _this._useDirectMapping = true;
  112894. }
  112895. else {
  112896. _this._useDirectMapping = options.useDirectMapping;
  112897. }
  112898. _this._setReady(false);
  112899. // create
  112900. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112901. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112902. // configure material
  112903. material.opacityFresnel = false;
  112904. material.useEquirectangularFOV = true;
  112905. material.fovMultiplier = 1.0;
  112906. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  112907. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  112908. if (onError) {
  112909. onError(message, exception);
  112910. }
  112911. });
  112912. _this.photoTexture.onLoadObservable.addOnce(function () {
  112913. _this._setReady(true);
  112914. });
  112915. // configure mesh
  112916. _this._mesh.material = material;
  112917. _this._mesh.parent = _this;
  112918. return _this;
  112919. }
  112920. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  112921. /**
  112922. * Gets or sets the texture being displayed on the sphere
  112923. */
  112924. get: function () {
  112925. return this._photoTexture;
  112926. },
  112927. set: function (value) {
  112928. if (this._photoTexture === value) {
  112929. return;
  112930. }
  112931. this._photoTexture = value;
  112932. if (this._useDirectMapping) {
  112933. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112934. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112935. this._material.diffuseTexture = this._photoTexture;
  112936. }
  112937. else {
  112938. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112939. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112940. this._material.reflectionTexture = this._photoTexture;
  112941. }
  112942. },
  112943. enumerable: true,
  112944. configurable: true
  112945. });
  112946. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  112947. /**
  112948. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112949. * Also see the options.resolution property.
  112950. */
  112951. get: function () {
  112952. return this._material.fovMultiplier;
  112953. },
  112954. set: function (value) {
  112955. this._material.fovMultiplier = value;
  112956. },
  112957. enumerable: true,
  112958. configurable: true
  112959. });
  112960. /**
  112961. * Releases resources associated with this node.
  112962. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112963. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112964. */
  112965. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112966. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112967. this._photoTexture.dispose();
  112968. this._mesh.dispose();
  112969. this._material.dispose();
  112970. this.onLoadErrorObservable.clear();
  112971. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112972. };
  112973. return PhotoDome;
  112974. }(BABYLON.TransformNode));
  112975. BABYLON.PhotoDome = PhotoDome;
  112976. })(BABYLON || (BABYLON = {}));
  112977. //# sourceMappingURL=babylon.photoDome.js.map
  112978. var BABYLON;
  112979. (function (BABYLON) {
  112980. /** @hidden */
  112981. var _OcclusionDataStorage = /** @class */ (function () {
  112982. function _OcclusionDataStorage() {
  112983. /** @hidden */
  112984. this.occlusionInternalRetryCounter = 0;
  112985. /** @hidden */
  112986. this.isOcclusionQueryInProgress = false;
  112987. /** @hidden */
  112988. this.isOccluded = false;
  112989. /** @hidden */
  112990. this.occlusionRetryCount = -1;
  112991. /** @hidden */
  112992. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  112993. /** @hidden */
  112994. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  112995. }
  112996. return _OcclusionDataStorage;
  112997. }());
  112998. BABYLON.Engine.prototype.createQuery = function () {
  112999. return this._gl.createQuery();
  113000. };
  113001. BABYLON.Engine.prototype.deleteQuery = function (query) {
  113002. this._gl.deleteQuery(query);
  113003. return this;
  113004. };
  113005. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  113006. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  113007. };
  113008. BABYLON.Engine.prototype.getQueryResult = function (query) {
  113009. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  113010. };
  113011. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  113012. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  113013. this._gl.beginQuery(glAlgorithm, query);
  113014. return this;
  113015. };
  113016. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  113017. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  113018. this._gl.endQuery(glAlgorithm);
  113019. return this;
  113020. };
  113021. BABYLON.Engine.prototype._createTimeQuery = function () {
  113022. var timerQuery = this.getCaps().timerQuery;
  113023. if (timerQuery.createQueryEXT) {
  113024. return timerQuery.createQueryEXT();
  113025. }
  113026. return this.createQuery();
  113027. };
  113028. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  113029. var timerQuery = this.getCaps().timerQuery;
  113030. if (timerQuery.deleteQueryEXT) {
  113031. timerQuery.deleteQueryEXT(query);
  113032. return;
  113033. }
  113034. this.deleteQuery(query);
  113035. };
  113036. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  113037. var timerQuery = this.getCaps().timerQuery;
  113038. if (timerQuery.getQueryObjectEXT) {
  113039. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  113040. }
  113041. return this.getQueryResult(query);
  113042. };
  113043. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  113044. var timerQuery = this.getCaps().timerQuery;
  113045. if (timerQuery.getQueryObjectEXT) {
  113046. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  113047. }
  113048. return this.isQueryResultAvailable(query);
  113049. };
  113050. BABYLON.Engine.prototype.startTimeQuery = function () {
  113051. var caps = this.getCaps();
  113052. var timerQuery = caps.timerQuery;
  113053. if (!timerQuery) {
  113054. return null;
  113055. }
  113056. var token = new BABYLON._TimeToken();
  113057. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  113058. if (caps.canUseTimestampForTimerQuery) {
  113059. token._startTimeQuery = this._createTimeQuery();
  113060. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  113061. }
  113062. else {
  113063. if (this._currentNonTimestampToken) {
  113064. return this._currentNonTimestampToken;
  113065. }
  113066. token._timeElapsedQuery = this._createTimeQuery();
  113067. if (timerQuery.beginQueryEXT) {
  113068. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  113069. }
  113070. else {
  113071. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  113072. }
  113073. this._currentNonTimestampToken = token;
  113074. }
  113075. return token;
  113076. };
  113077. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  113078. var caps = this.getCaps();
  113079. var timerQuery = caps.timerQuery;
  113080. if (!timerQuery || !token) {
  113081. return -1;
  113082. }
  113083. if (caps.canUseTimestampForTimerQuery) {
  113084. if (!token._startTimeQuery) {
  113085. return -1;
  113086. }
  113087. if (!token._endTimeQuery) {
  113088. token._endTimeQuery = this._createTimeQuery();
  113089. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  113090. }
  113091. }
  113092. else if (!token._timeElapsedQueryEnded) {
  113093. if (!token._timeElapsedQuery) {
  113094. return -1;
  113095. }
  113096. if (timerQuery.endQueryEXT) {
  113097. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  113098. }
  113099. else {
  113100. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  113101. }
  113102. token._timeElapsedQueryEnded = true;
  113103. }
  113104. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  113105. var available = false;
  113106. if (token._endTimeQuery) {
  113107. available = this._getTimeQueryAvailability(token._endTimeQuery);
  113108. }
  113109. else if (token._timeElapsedQuery) {
  113110. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  113111. }
  113112. if (available && !disjoint) {
  113113. var result = 0;
  113114. if (caps.canUseTimestampForTimerQuery) {
  113115. if (!token._startTimeQuery || !token._endTimeQuery) {
  113116. return -1;
  113117. }
  113118. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  113119. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  113120. result = timeEnd - timeStart;
  113121. this._deleteTimeQuery(token._startTimeQuery);
  113122. this._deleteTimeQuery(token._endTimeQuery);
  113123. token._startTimeQuery = null;
  113124. token._endTimeQuery = null;
  113125. }
  113126. else {
  113127. if (!token._timeElapsedQuery) {
  113128. return -1;
  113129. }
  113130. result = this._getTimeQueryResult(token._timeElapsedQuery);
  113131. this._deleteTimeQuery(token._timeElapsedQuery);
  113132. token._timeElapsedQuery = null;
  113133. token._timeElapsedQueryEnded = false;
  113134. this._currentNonTimestampToken = null;
  113135. }
  113136. return result;
  113137. }
  113138. return -1;
  113139. };
  113140. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  113141. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  113142. };
  113143. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  113144. get: function () {
  113145. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  113146. },
  113147. enumerable: false,
  113148. configurable: true
  113149. });
  113150. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  113151. get: function () {
  113152. if (!this.__occlusionDataStorage) {
  113153. this.__occlusionDataStorage = new _OcclusionDataStorage();
  113154. }
  113155. return this.__occlusionDataStorage;
  113156. },
  113157. enumerable: false,
  113158. configurable: true
  113159. });
  113160. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  113161. get: function () {
  113162. return this._occlusionDataStorage.isOccluded;
  113163. },
  113164. set: function (value) {
  113165. this._occlusionDataStorage.isOccluded = value;
  113166. },
  113167. enumerable: true,
  113168. configurable: true
  113169. });
  113170. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  113171. get: function () {
  113172. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  113173. },
  113174. set: function (value) {
  113175. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  113176. },
  113177. enumerable: true,
  113178. configurable: true
  113179. });
  113180. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  113181. get: function () {
  113182. return this._occlusionDataStorage.occlusionType;
  113183. },
  113184. set: function (value) {
  113185. this._occlusionDataStorage.occlusionType = value;
  113186. },
  113187. enumerable: true,
  113188. configurable: true
  113189. });
  113190. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  113191. get: function () {
  113192. return this._occlusionDataStorage.occlusionRetryCount;
  113193. },
  113194. set: function (value) {
  113195. this._occlusionDataStorage.occlusionRetryCount = value;
  113196. },
  113197. enumerable: true,
  113198. configurable: true
  113199. });
  113200. // We also need to update AbstractMesh as there is a portion of the code there
  113201. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  113202. var dataStorage = this._occlusionDataStorage;
  113203. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  113204. dataStorage.isOccluded = false;
  113205. return false;
  113206. }
  113207. var engine = this.getEngine();
  113208. if (engine.webGLVersion < 2) {
  113209. dataStorage.isOccluded = false;
  113210. return false;
  113211. }
  113212. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  113213. dataStorage.isOccluded = false;
  113214. return false;
  113215. }
  113216. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  113217. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  113218. if (isOcclusionQueryAvailable) {
  113219. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  113220. dataStorage.isOcclusionQueryInProgress = false;
  113221. dataStorage.occlusionInternalRetryCounter = 0;
  113222. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  113223. }
  113224. else {
  113225. dataStorage.occlusionInternalRetryCounter++;
  113226. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  113227. dataStorage.isOcclusionQueryInProgress = false;
  113228. dataStorage.occlusionInternalRetryCounter = 0;
  113229. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  113230. // if strict continue the last state of the object.
  113231. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  113232. }
  113233. else {
  113234. return false;
  113235. }
  113236. }
  113237. }
  113238. var scene = this.getScene();
  113239. if (scene.getBoundingBoxRenderer) {
  113240. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  113241. if (!this._occlusionQuery) {
  113242. this._occlusionQuery = engine.createQuery();
  113243. }
  113244. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  113245. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  113246. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  113247. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  113248. }
  113249. return dataStorage.isOccluded;
  113250. };
  113251. })(BABYLON || (BABYLON = {}));
  113252. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  113253. var BABYLON;
  113254. (function (BABYLON) {
  113255. /**
  113256. * Class used to generate noise procedural textures
  113257. */
  113258. var NoiseProceduralTexture = /** @class */ (function (_super) {
  113259. __extends(NoiseProceduralTexture, _super);
  113260. /**
  113261. * Creates a new NoiseProceduralTexture
  113262. * @param name defines the name fo the texture
  113263. * @param size defines the size of the texture (default is 256)
  113264. * @param scene defines the hosting scene
  113265. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  113266. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  113267. */
  113268. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  113269. if (size === void 0) { size = 256; }
  113270. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  113271. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  113272. _this._time = 0;
  113273. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  113274. _this.brightness = 0.2;
  113275. /** Defines the number of octaves to process */
  113276. _this.octaves = 3;
  113277. /** Defines the level of persistence (0.8 by default) */
  113278. _this.persistence = 0.8;
  113279. /** Gets or sets animation speed factor (default is 1) */
  113280. _this.animationSpeedFactor = 1;
  113281. _this._updateShaderUniforms();
  113282. return _this;
  113283. }
  113284. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  113285. var scene = this.getScene();
  113286. if (!scene) {
  113287. return;
  113288. }
  113289. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  113290. this.setFloat("brightness", this.brightness);
  113291. this.setFloat("persistence", this.persistence);
  113292. this.setFloat("timeScale", this._time);
  113293. };
  113294. NoiseProceduralTexture.prototype._getDefines = function () {
  113295. return "#define OCTAVES " + (this.octaves | 0);
  113296. };
  113297. /** Generate the current state of the procedural texture */
  113298. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  113299. this._updateShaderUniforms();
  113300. _super.prototype.render.call(this, useCameraPostProcess);
  113301. };
  113302. /**
  113303. * Serializes this noise procedural texture
  113304. * @returns a serialized noise procedural texture object
  113305. */
  113306. NoiseProceduralTexture.prototype.serialize = function () {
  113307. var serializationObject = {};
  113308. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  113309. serializationObject.brightness = this.brightness;
  113310. serializationObject.octaves = this.octaves;
  113311. serializationObject.persistence = this.persistence;
  113312. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  113313. serializationObject.size = this.getSize().width;
  113314. serializationObject.generateMipMaps = this._generateMipMaps;
  113315. return serializationObject;
  113316. };
  113317. /**
  113318. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  113319. * @param parsedTexture defines parsed texture data
  113320. * @param scene defines the current scene
  113321. * @param rootUrl defines the root URL containing noise procedural texture information
  113322. * @returns a parsed NoiseProceduralTexture
  113323. */
  113324. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  113325. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  113326. texture.brightness = parsedTexture.brightness;
  113327. texture.octaves = parsedTexture.octaves;
  113328. texture.persistence = parsedTexture.persistence;
  113329. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  113330. return texture;
  113331. };
  113332. return NoiseProceduralTexture;
  113333. }(BABYLON.ProceduralTexture));
  113334. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  113335. })(BABYLON || (BABYLON = {}));
  113336. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  113337. var __assign = (this && this.__assign) || function () {
  113338. __assign = Object.assign || function(t) {
  113339. for (var s, i = 1, n = arguments.length; i < n; i++) {
  113340. s = arguments[i];
  113341. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  113342. t[p] = s[p];
  113343. }
  113344. return t;
  113345. };
  113346. return __assign.apply(this, arguments);
  113347. };
  113348. var BABYLON;
  113349. (function (BABYLON) {
  113350. /**
  113351. * This can helps recording videos from BabylonJS.
  113352. * This is based on the available WebRTC functionalities of the browser.
  113353. *
  113354. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  113355. */
  113356. var VideoRecorder = /** @class */ (function () {
  113357. /**
  113358. * Create a new VideoCapture object which can help converting what you see in Babylon to
  113359. * a video file.
  113360. * @param engine Defines the BabylonJS Engine you wish to record
  113361. * @param options Defines options that can be used to customized the capture
  113362. */
  113363. function VideoRecorder(engine, options) {
  113364. if (options === void 0) { options = null; }
  113365. if (!VideoRecorder.IsSupported(engine)) {
  113366. throw "Your browser does not support recording so far.";
  113367. }
  113368. var canvas = engine.getRenderingCanvas();
  113369. if (!canvas) {
  113370. throw "The babylon engine must have a canvas to be recorded";
  113371. }
  113372. this._canvas = canvas;
  113373. this._canvas.isRecording = false;
  113374. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  113375. var stream = this._canvas.captureStream(this._options.fps);
  113376. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  113377. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  113378. this._mediaRecorder.onerror = this._handleError.bind(this);
  113379. this._mediaRecorder.onstop = this._handleStop.bind(this);
  113380. }
  113381. /**
  113382. * Returns wehther or not the VideoRecorder is available in your browser.
  113383. * @param engine Defines the Babylon Engine to check the support for
  113384. * @returns true if supported otherwise false
  113385. */
  113386. VideoRecorder.IsSupported = function (engine) {
  113387. var canvas = engine.getRenderingCanvas();
  113388. return (!!canvas && typeof canvas.captureStream === "function");
  113389. };
  113390. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  113391. /**
  113392. * True wether a recording is already in progress.
  113393. */
  113394. get: function () {
  113395. return !!this._canvas && this._canvas.isRecording;
  113396. },
  113397. enumerable: true,
  113398. configurable: true
  113399. });
  113400. /**
  113401. * Stops the current recording before the default capture timeout passed in the startRecording
  113402. * functions.
  113403. */
  113404. VideoRecorder.prototype.stopRecording = function () {
  113405. if (!this._canvas || !this._mediaRecorder) {
  113406. return;
  113407. }
  113408. if (!this.isRecording) {
  113409. return;
  113410. }
  113411. this._canvas.isRecording = false;
  113412. this._mediaRecorder.stop();
  113413. };
  113414. /**
  113415. * Starts recording the canvas for a max duration specified in parameters.
  113416. * @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.
  113417. * @param maxDuration Defines the maximum recording time in seconds.
  113418. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  113419. * @return a promise callback at the end of the recording with the video data in Blob.
  113420. */
  113421. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  113422. var _this = this;
  113423. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  113424. if (maxDuration === void 0) { maxDuration = 7; }
  113425. if (!this._canvas || !this._mediaRecorder) {
  113426. throw "Recorder has already been disposed";
  113427. }
  113428. if (this.isRecording) {
  113429. throw "Recording already in progress";
  113430. }
  113431. if (maxDuration > 0) {
  113432. setTimeout(function () {
  113433. _this.stopRecording();
  113434. }, maxDuration * 1000);
  113435. }
  113436. this._fileName = fileName;
  113437. this._recordedChunks = [];
  113438. this._resolve = null;
  113439. this._reject = null;
  113440. this._canvas.isRecording = true;
  113441. this._mediaRecorder.start(this._options.recordChunckSize);
  113442. return new Promise(function (resolve, reject) {
  113443. _this._resolve = resolve;
  113444. _this._reject = reject;
  113445. });
  113446. };
  113447. /**
  113448. * Releases internal resources used during the recording.
  113449. */
  113450. VideoRecorder.prototype.dispose = function () {
  113451. this._canvas = null;
  113452. this._mediaRecorder = null;
  113453. this._recordedChunks = [];
  113454. this._fileName = null;
  113455. this._resolve = null;
  113456. this._reject = null;
  113457. };
  113458. VideoRecorder.prototype._handleDataAvailable = function (event) {
  113459. if (event.data.size > 0) {
  113460. this._recordedChunks.push(event.data);
  113461. }
  113462. };
  113463. VideoRecorder.prototype._handleError = function (event) {
  113464. this.stopRecording();
  113465. if (this._reject) {
  113466. this._reject(event.error);
  113467. }
  113468. else {
  113469. throw new event.error;
  113470. }
  113471. };
  113472. VideoRecorder.prototype._handleStop = function () {
  113473. this.stopRecording();
  113474. var superBuffer = new Blob(this._recordedChunks);
  113475. if (this._resolve) {
  113476. this._resolve(superBuffer);
  113477. }
  113478. window.URL.createObjectURL(superBuffer);
  113479. if (this._fileName) {
  113480. BABYLON.Tools.Download(superBuffer, this._fileName);
  113481. }
  113482. };
  113483. VideoRecorder._defaultOptions = {
  113484. mimeType: "video/webm",
  113485. fps: 25,
  113486. recordChunckSize: 3000
  113487. };
  113488. return VideoRecorder;
  113489. }());
  113490. BABYLON.VideoRecorder = VideoRecorder;
  113491. })(BABYLON || (BABYLON = {}));
  113492. //# sourceMappingURL=babylon.videoRecorder.js.map
  113493. var BABYLON;
  113494. (function (BABYLON) {
  113495. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  113496. if (replace === void 0) { replace = false; }
  113497. // Dispose existing light in replace mode.
  113498. if (replace) {
  113499. if (this.lights) {
  113500. for (var i = 0; i < this.lights.length; i++) {
  113501. this.lights[i].dispose();
  113502. }
  113503. }
  113504. }
  113505. // Light
  113506. if (this.lights.length === 0) {
  113507. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  113508. }
  113509. };
  113510. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  113511. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  113512. if (replace === void 0) { replace = false; }
  113513. if (attachCameraControls === void 0) { attachCameraControls = false; }
  113514. // Dispose existing camera in replace mode.
  113515. if (replace) {
  113516. if (this.activeCamera) {
  113517. this.activeCamera.dispose();
  113518. this.activeCamera = null;
  113519. }
  113520. }
  113521. // Camera
  113522. if (!this.activeCamera) {
  113523. var worldExtends = this.getWorldExtends();
  113524. var worldSize = worldExtends.max.subtract(worldExtends.min);
  113525. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  113526. var camera;
  113527. var radius = worldSize.length() * 1.5;
  113528. // empty scene scenario!
  113529. if (!isFinite(radius)) {
  113530. radius = 1;
  113531. worldCenter.copyFromFloats(0, 0, 0);
  113532. }
  113533. if (createArcRotateCamera) {
  113534. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  113535. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  113536. arcRotateCamera.wheelPrecision = 100 / radius;
  113537. camera = arcRotateCamera;
  113538. }
  113539. else {
  113540. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  113541. freeCamera.setTarget(worldCenter);
  113542. camera = freeCamera;
  113543. }
  113544. camera.minZ = radius * 0.01;
  113545. camera.maxZ = radius * 1000;
  113546. camera.speed = radius * 0.2;
  113547. this.activeCamera = camera;
  113548. var canvas = this.getEngine().getRenderingCanvas();
  113549. if (attachCameraControls && canvas) {
  113550. camera.attachControl(canvas);
  113551. }
  113552. }
  113553. };
  113554. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  113555. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  113556. if (replace === void 0) { replace = false; }
  113557. if (attachCameraControls === void 0) { attachCameraControls = false; }
  113558. this.createDefaultLight(replace);
  113559. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  113560. };
  113561. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  113562. if (pbr === void 0) { pbr = false; }
  113563. if (scale === void 0) { scale = 1000; }
  113564. if (blur === void 0) { blur = 0; }
  113565. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  113566. if (!environmentTexture) {
  113567. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  113568. return null;
  113569. }
  113570. if (setGlobalEnvTexture) {
  113571. if (environmentTexture) {
  113572. this.environmentTexture = environmentTexture;
  113573. }
  113574. }
  113575. // Skybox
  113576. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  113577. if (pbr) {
  113578. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  113579. hdrSkyboxMaterial.backFaceCulling = false;
  113580. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  113581. if (hdrSkyboxMaterial.reflectionTexture) {
  113582. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  113583. }
  113584. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  113585. hdrSkyboxMaterial.disableLighting = true;
  113586. hdrSkyboxMaterial.twoSidedLighting = true;
  113587. hdrSkybox.infiniteDistance = true;
  113588. hdrSkybox.material = hdrSkyboxMaterial;
  113589. }
  113590. else {
  113591. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  113592. skyboxMaterial.backFaceCulling = false;
  113593. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  113594. if (skyboxMaterial.reflectionTexture) {
  113595. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  113596. }
  113597. skyboxMaterial.disableLighting = true;
  113598. hdrSkybox.infiniteDistance = true;
  113599. hdrSkybox.material = skyboxMaterial;
  113600. }
  113601. return hdrSkybox;
  113602. };
  113603. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  113604. if (BABYLON.EnvironmentHelper) {
  113605. return new BABYLON.EnvironmentHelper(options, this);
  113606. }
  113607. return null;
  113608. };
  113609. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  113610. if (webVROptions === void 0) { webVROptions = {}; }
  113611. return new BABYLON.VRExperienceHelper(this, webVROptions);
  113612. };
  113613. })(BABYLON || (BABYLON = {}));
  113614. //# sourceMappingURL=babylon.sceneHelpers.js.map
  113615. 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(normalize(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"};
  113616. 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};"};
  113617. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  113618. globalObject["BABYLON"] = BABYLON;
  113619. //backwards compatibility
  113620. if(typeof earcut !== 'undefined') {
  113621. globalObject["Earcut"] = {
  113622. earcut: earcut
  113623. };
  113624. }
  113625. return BABYLON;
  113626. });